繁体   English   中英

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

[英]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()

num1num2是局部变量,即它们在它们声明的函数之外没有作用域。 修复它们在函数之外声明它们或添加 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM