Python中最多两个数字
给定两个数字,编写Python代码来找出这两个数字的最大值。
例子:
Input: a = 2, b = 4
Output: 4
Input: a = -1, b = -4
Output: -1
方法#1:这是一种简单的方法,我们将使用 if-else 语句比较两个数字并相应地打印输出。
例子:
Python3
# Python program to find the
# maximum of two numbers
def maximum(a, b):
if a >= b:
return a
else:
return b
# Driver code
a = 2
b = 4
print(maximum(a, b))
Python3
# Python program to find the
# maximum of two numbers
a = 2
b = 4
maximum = max(a, b)
print(maximum)
Python3
# Python program to find the
# maximum of two numbers
# Driver code
a = 2
b = 4
# Use of ternary operator
print(a if a >= b else b)
# This code is contributed by AnkThon
输出
4
方法 #2:使用 max()函数
此函数用于查找作为其参数传递的值的最大值。
例子:
Python3
# Python program to find the
# maximum of two numbers
a = 2
b = 4
maximum = max(a, b)
print(maximum)
输出
4
方法#3:使用三元运算符
该运算符也称为条件表达式,是根据条件为真或假来评估某些内容的运算符。它只是允许在一行中测试一个条件
例子:
Python3
# Python program to find the
# maximum of two numbers
# Driver code
a = 2
b = 4
# Use of ternary operator
print(a if a >= b else b)
# This code is contributed by AnkThon
输出
4