我在将子程序中的变量带入另一个子程序时遇到了一些麻烦。将子程序中的变量全局化为另一个子程序
下面是代码:
def loop1():
try:
age=int(input("How old are you? "))
except ValueError:
print ("Please enter a numerical integer of your age. For example: 19 ")
print("")
loop1()
if age>0:
program()
def program():
print("")
print("[1] - Knife/Spray Paint/Lottery Ticket ")
print("[2] - Alcohol/Tobacco ")
print("[3] - Anything else ")
print("")
loop2()
def loop2():
try:
item=int(input("What would you like to buy from the options above? "))
print("")
except ValueError:
print ("Please enter a numerical integer of your item. For example (if you wanted to buy alcohol): 2 ")
print("")
loop2()
if item>0:
validation()
def validation():
if item == 1 and 16>age :
print("Sale Denied - Item cannot be sold to Under 16s. ")
elif item == 1 and 16<age:
print("Sale Accepted. ")
elif item == 2 and 18>age:
print("Sale Denied - Item cannot be sold to Under 18s. ")
elif item == 2 and 25>age>18:
print("Check ID before selling alcohol - Challenge 25. ")
elif item == 2 and 18<age:
print("Sale Accepted. ")
elif item == 3:
print("Sale Accepted. ")
loop1()
这里是结果:
How old are you? 21
[1] - Knife/Spray Paint/Lottery Ticket
[2] - Alcohol/Tobacco
[3] - Anything else
What would you like to buy from the options above? 2
Traceback (most recent call last):
File "D:/Shop Program.py", line 48, in <module>
loop1()
File "D:/Test.py", line 9, in loop1
program()
File "D:/Shop Program.py", line 17, in program
loop2()
File "D:/Shop Program.py", line 28, in loop2
validation()
File "D:/Shop Program.py", line 33, in validation
if item == 1 and 16>age :
NameError: global name 'item' is not defined
你可以从错误信息看它上面说global name 'item' is not defined
。我试图将global item
,def vaildation():
以上,但我仍然得到同样的错误。
你为什么要通过'global'范围来做这件事?相反,只需定义适当的输入参数和“返回”值即可。 – jonrsharpe
感谢您的回复。 请解释一下,我不明白。 – Anonymous