将变量从一个子例程传递到另一个子例程时遇到麻烦。
这是代码:
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
,这是一种不好的做法(在Python和其他地方),明确地传递item
从loop2
到validation
:
def loop2(age):
...
if item > 0:
validation(item, age)
# ^ pass it here
def validation(item, age):
# ^ receive it here
if item == 1 and 16 > age:
...
请注意,我对做了类似的事情age
,应该在loop2
调用时传递。使用递归进行输入验证不是理想的方法。请参阅要求用户提供输入信息,直到他们给出有效的替代方法答复为止。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句