Skip to main content
 首页 » 编程设计

python之如何检查是否缺少参数

2024年10月25日8haluo1

我写了这段代码:

def suma(num1,num2): 
 
    if(isinstance(num1,int)) or (isinstance(num2,int)) : 
       if num1<0 or num2<0: 
            print("iavo") 
       elif num1!=int(num1)or num2!=int(num2): 
            print("iao") 
       else: 
            suma_a = num1+num2 
            return suma_a 
    else: 
        print("ia") 

我需要检查是否有 num1 或 num2。如果没有,程序应该打印出缺少参数。

请您参考如下方法:

如果您没有分配默认值并且用户没有提供两个参数,您将在进入函数之前得到一个TypeError: suma() missing 1 required positional argument:

def suma(num1=None,num2=None): 
     # make sure user has entered two args and both are numbers 
    if num1 is None or num2 is None: 
        return "You Must choose two numbers" 
    # rest of code