使用函数查找两个数中的较大数

2024-06-17 09:59:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用函数查找用户输入的两个数字中较大的数字。请帮助我识别代码中产生错误结果的错误:

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

Tags: thenumberwhichis错误数字findprint
3条回答

原因是,输入函数生成一个字符串值。因此,将代码更改为:

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 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
func1(num1,num2)   

输出:

Find which number is greater
Enter the first number: 5
Enter the second number: 10
10  is greater than  5

使用pydantic。你可以python -m pip install --user pydantic

当数据无效时,Pydantic将帮助您执行数据验证、对话和友好错误

from pydantic import BaseModel

class InputValues(BaseModel):
    n1: int
    n2: int


def f(n1,n2):
   # let PyDantic deal with conversation 
    num = InputValues(n1=n1, n2=n2)
    if (num.n1 > num.n2):
        print(f"{n1} is greater than {n2}")
    else:
        print(f"{n2} is greater than {n1}")

# Example:

n = "10"
m = "5"

f(n,m)

为什么使用Pydantic而不是简单的铸造

如果传递无效的输入,int(input...)将失败。两者的不同之处在于,其中一个会准确地告诉你问题所在

你可以在pydantic上找到更多信息

强制输入到int

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 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
func1(num1, num2) 

对于您的功能,您可以在一行中实现这一点

def func1(n1,n2):
        return str(n1)+" is greater than "+str(n2) if n1>n2 else str(n2)+" is greater than "+str(n1)
        

相关问题 更多 >