我在將子程序中的變量帶入另一個子程序時遇到了一些麻煩。將子程序中的變量全局化爲另一個子程序
下面是代碼:
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