2015-04-17 36 views
0

我在將子程序中的變量帶入另一個子程序時遇到了一些麻煩。將子程序中的變量全局化爲另一個子程序

下面是代碼:

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 itemdef vaildation():以上,但我仍然得到同樣的錯誤。

+0

你爲什麼要通過'global'範圍來做這件事?相反,只需定義適當的輸入參數和「返回」值即可。 – jonrsharpe

+0

感謝您的回覆。 請解釋一下,我不明白。 – Anonymous

回答

2

而不是使用global,這是一個bad practice(Python和其他地方),明確從loop2通過itemvalidation

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時傳入。使用遞歸進行輸入驗證並不理想;有關替代方法,請參閱Asking the user for input until they give a valid response

+0

謝謝,這已解決項目錯誤,但我現在得到一個錯誤,說:* NameError:全球名稱'年齡'未定義* – Anonymous

+0

@當然匿名!所以**應用相同的邏輯**'年齡'... – jonrsharpe

+0

我已經試過 – Anonymous

0

請原諒我,如果您已經知道這一點,但還有另一種方法可以將物品放入validate子例程中,這可能對您更好。您可以將變量「傳入」子程序(也稱爲方法或函數)。您「傳入」到子例程的變量稱爲參數。 要使用子程序參數,你必須做兩件事情:

  1. 定義在子程序定義
  2. 參數指定變量,以「傳遞」當你調用子程序

所以對於你,在你的日常validate定義參數item是這樣的:

def validate(item): 
    if item == 1 and 16>age : 

查看如何I S括號之間的集圈item

然後,所有你需要做的是項目「中通」的驗證功能:

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(item) 

注意我是如何把item括號之間的調用validation子程序的最後一行。

希望幫助

+0

是的,jonrsharpe剛告訴我這件事# – Anonymous

+0

感謝您的回答 – Anonymous

0

除了你原來的問題:有一個在LOOP1和環路2無限循環的可能性,如果該異常上升,作爲函數調用自己。

一個更好的方法是在成功轉換後使用循環(while True:...)並暫停。

此外,在每種編程語言中,按照您的方式鏈接函數是不好的做法。這比使用goto更糟糕,通常被稱爲意大利麪代碼。 更好的是具有連續調用函數,並傳遞原函數的結果作爲參數傳遞給下一個功能單一的主要功能:

age = get_age() 
item = get_item() 
if age < 16 and item == ...: 
    print("Not allowed") 
... 

一個更好的辦法是使用{「項目」的字典:minimal_age}:

items = { "butter": 0 , "knife": 16, "booze": 18, "beer": 17 } 

age = ... 
item = get_item(items) # the list can be built automatically from dict 
if age < items[item]: 
    print("Too young for", item) 
else: 
    purchase(item) 

這將避免if .. elif ..測試的loooooong列表。 如果項目由字符串而不是數字標識,則會增加可讀性。一般來說,在Python中,numberincal的值只能用於「自然」的地方,否則使用適當的類型,如字符串,集合等。 請注意,這與其他語言不同(例如C),其中字符串處理非常不舒服而且很貴。

相關問題