[英]Input number A and B and sum them together, given that A has a pre-defined limit in 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
我是 python 新手並且卡住了,現在需要幫助!
執行以下操作時,您將創建一個本地方法的變量num2
,它只能在方法的范圍內訪問,您需要以一種方式從方法返回值並以另一種方式將它們作為參數傳遞
def ans_num2():
num2 = input("Enter your 2st num: ")
給予:
def welcome():
print("Welcome user\n")
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()
num1
和num2
是局部變量,即它們在它們聲明的函數之外沒有作用域。 修復它們在函數之外聲明它們或添加 global 關鍵字。 你也寫過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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.