输入数字A和B,并将它们相加,假设A在Python中有预定义的限制

  • 本文关键字:假设 Python 预定义 数字 python
  • 更新时间 :
  • 英文 :


我正在做一个计算器,输入数字a和数字B,然后将它们相加,假设a有一个预定义的限制(例如a必须小于8(

def welcome():
print("Welcome user")
print("")
def ans_num1():
num1 = int(input("Enter your 1st num: "))
while num1 <= limit1:
print("Good boy")
break
else:
print("Wrong input")
ans_num1()
def ans_num2():
num2 = input("Enter your 2st num: ")

def calculator():   
print("The sum of 2 numbers are: ")
print(num1 + num2)
print("")
def thanks():
print("Thank you and Goodbye :)")

welcome()
limit1 = int(input("Enter your limit: "))
asknum1()
asknum2()
calculator()
thanks()

但我收到一条错误消息,上面写着:

The sum of 2 numbers are: Traceback (most recent call last): line 31, in <module> calculator() line 20, in calculator print(num1 + num2) NameError: name 'num1' is not defined

我是蟒蛇新手,现在需要帮助!

执行以下操作时,您在方法的本地创建一个变量num2,它只能在方法的范围内访问,您需要以一种方式从方法返回值,并以另一种方式将其作为参数传递

def ans_num2():
num2 = input("Enter your 2st num: ")

给予:

def welcome():
print("Welcome usern")
def asknum(limit, nb):
res = int(input("Enter your number %s " % nb))
while res > limit:
res = int(input("Enter your number %s " % nb))
return res
def calculator(num1, num2):
print("The sum of 2 numbers are: ", num1 + num2, "n")
def thanks():
print("Thank you and Goodbye :)")
welcome()
limit = int(input("Enter your limit: "))
num1 = asknum(limit, 1)
num2 = asknum(limit, 2)
calculator(num1, num2)
thanks()

num1num2是局部变量,即它们在声明的函数之外没有作用域。要修复它们,请在函数外声明它们或添加全局关键字。你也写了asknum1()而不是ans_num1(),与ans_num2()相同

def welcome():
print("Welcome user")
print("")
def ans_num1():
global num1                                #num1 is declared globally
num1 = int(input("Enter your 1st num: "))
while num1 <= limit1:
print("Good boy")
break
else:
print("Wrong input")
ans_num1()
def ans_num2():
global num2                                 #declared globally
num2= int(input("Enter your 2st num: "))

def calculator():
print("The sum of 2 numbers are: ")
print(num1 + num2)
print("")
def thanks():
print("Thank you and Goodbye :)")

welcome()
limit1 = int(input("Enter your limit: "))     #already declared globally
ans_num1()                                    #fixed the function name
ans_num2()
calculator()
thanks()

最新更新