2015-04-17 34 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),其中字符串处理非常不舒服而且很贵。

相关问题