我尝试使用函数查找用户输入的两个数字中较大的数字。请帮助我识别代码中产生错误结果的错误:
def func1(n1,n2):
if (n1 > n2):
print(n1," is greater than ",n2)
else:
print(n2," is greater than ",n1)
print("Find which number is greater")
num1 = input("Enter the first number: ")
num2 = input("Enter the second number: ")
func1(num1, num2)
它显示了一个错误的结果:
Find which number is greater
Enter the first number: 10
Enter the second number: 5
5 is greater than 10
原因是,输入函数生成一个字符串值。因此,将代码更改为:
输出:
使用
pydantic
。你可以python -m pip install --user pydantic
当数据无效时,Pydantic将帮助您执行数据验证、对话和友好错误
为什么使用Pydantic而不是简单的铸造
如果传递无效的输入,
int(input...)
将失败。两者的不同之处在于,其中一个会准确地告诉你问题所在你可以在pydantic上找到更多信息
强制输入到int
对于您的功能,您可以在一行中实现这一点
相关问题 更多 >
编程相关推荐