我是靠谱客的博主 优雅铅笔,最近开发中收集的这篇文章主要介绍python max函数代码_Python max() and min()用法及代码示例,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

本文为您带来了一个非常有趣且鲜为人知的Python函数,即max()和min()。现在,与仅允许两个参数(过于严格地为float,int或char)的C++相比,这些函数不仅限于2个元素,而且可以容纳许多元素作为参数,并在其参数中支持字符串,因此也可以显示字典上最小或最大的字符串。详细功能说明如下。

max()

此函数用于计算在其参数中传递的值的最大值,在将字符串作为参数传递时,按字典顺序计算最大值。

用法:

max(a,b,c,..)

参数:

a,b,c,..: similar type of data.

返回值:

Returns the maximum of all the arguments.

Exceptions:

Returns TypeError when conflicting types are compared.

# Python code to demonstrate the working of

# max()

# printing the maximum of 4,12,43.3,19,100

print("Maximum of 4,12,43.3,19 and 100 is:",end="")

print (max( 4,12,43.3,19,100 ) )

输出:

Maximum of 4,12,43.3,19 and 100 is:100

min()

此函数用于计算在其参数中传递的值的最小值,在将字符串作为参数传递时,按字典顺序计算的最小值。

用法:

min(a,b,c,..)

参数:

a,b,c,..: similar type of data.

返回值:

Returns the minimum of all the arguments.

Exceptions:

Returns TypeError when conflicting types are compared.

# Python code to demonstrate the working of

# min()

# printing the minimum of 4,12,43.3,19,100

print("Minimum of 4,12,43.3,19 and 100 is:",end="")

print (min( 4,12,43.3,19,100 ) )

输出:

Minimum of 4,12,43.3,19 and 100 is:4

异常

1. TypeError:比较冲突的数据类型时,这些函数将引发TypeError。

# Python code to demonstrate the Exception of

# min() and max()

# printing the minimum of 4,12,43.3,19, "GeeksforGeeks"

# Throws Exception

print("Minimum of 4,12,43.3,19 and GeeksforGeeks is:",end="")

print (min( 4,12,43.3,19,"GeeksforGeeks" ) )

输出:

Minimum of 4,12,43.3,19 and GeeksforGeeks is:

运行时错误:

Traceback (most recent call last):

File "/home/b5da1d7f834a267f94fbbefe1b31a83c.py", line 7, in

print (min( 4,12,43.3,19,"GeeksforGeeks" ) )

TypeError:unorderable types:str() < int()

实际应用

在许多字典中,实际应用之一是找到按字典顺序排列的最大和最小的字符串,即在字典中排在最前或最后的字符串。

# Python code to demonstrate the Application of

# min() and max()

# printing the word occurring 1st among these in dict.

# "geeks", "manjeet", "algorithm", "programming"

print("The word occurring 1st in dict. among given is:",end="")

print (min( "geeks", "manjeet", "algorithm", "programming" ) )

# printing the word occurring last among these in dict.

# "geeks", "manjeet", "algorithm", "programming"

print("The word occurring last in dict. among given is:",end="")

print (max( "geeks", "manjeet", "algorithm", "programming" ) )

输出:

The word occurring 1st in dict. among given is:algorithm

The word occurring last in dict. among given is:programming

最后

以上就是优雅铅笔为你收集整理的python max函数代码_Python max() and min()用法及代码示例的全部内容,希望文章能够帮你解决python max函数代码_Python max() and min()用法及代码示例所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(79)

评论列表共有 0 条评论

立即
投稿
返回
顶部