2017-02-06 65 views
1

我需要帮助,这些错误是:我做错了什么?在Python中将变量从一个函数传递到下一个函数

Traceback (most recent call last): 
    File "python", line 64, in <module> 
    File "python", line 6, in walmart 
    File "python", line 28, in shopping 
    File "python", line 53, in drink 
    File "python", line 61, in total_price 
NameError: global name 'price' is not defined 

我的代码:

def walmart(): 
    print "Hello welcome to the store!" 
    answer = raw_input("What's your name?") 
    if len(answer) > 0: 
     print "okay great %s, Lets go!...." % (answer) 
     shopping() 
    else: 
     print "Sorry try typing something" 
     walmart() 
def shopping(): 
    print "Ok lets get shopping" 
    shop_list = {"pizza" : 10.00 , "fries" : 15.00 , "burger" : 15.00} 
    print "Here are a list of food avaliable..." 
    print shop_list 
    ans1 = raw_input("Please select your item...").lower() 
    price = shop_list[ans1] 

    if "pizza" in ans1: 
     print "Your current price is... " + str(shop_list[ans1]) 
     drink(price) 

    elif "burger" in ans1: 
     print "Your current price is... " + str(shop_list[ans1]) 
     drink(price) 

    elif "fries" in ans1: 
     print "Your current price is... " + str(shop_list[ans1]) 
     drink(price) 

    else: 
     print "Please type something on the list..." 
     shopping() 
    return price 

def drink(price): 
    print "Okay let's pick you a drink" 
    drink_list = {"water" : 1 , "soda" : 2 , "tea" : 3} 
    print "Here is a list of drinks..." 
    print drink_list 
    ans2 = raw_input("Please type your choice here...").lower() 
    price_drink = drink_list[ans2] 

    if "water" in ans2: 
     print "Great healthy choice!" 
     total_price(price_drink) 

    elif "soda" in ans2: 
     print "Not that heaalthy but whatever floats your boat!" 
     total_price(price_drink) 

    elif "tea" in ans2: 
     print "OOOOO Tea great choice " 
     total_price(price_drink) 

    else: 
     print " Try again!" 
     drink(price) 
    return price_drink 

def total_price(price_drink): 
    totalprice = drink(price) + shopping() 
    print "Thanks for shopping....\nHere is your total price..." 
    print totalprice 
walmart() 
+0

就像错误说的那样,'price'没有在'total_price'中定义。你有什么问题? – Carcigenicate

回答

2

的问题是你的变量“价格”是局部变量,只存在在函数内部,因此在功能上TOTAL_PRICE,变“价格”不存在。您可以通过将变量“价格”定义为函数之外的全局变量来修复。

# Before functions 

price = 0 

# your functions go here 
def ...... 
+0

谢谢,生病了! –

2

你不传递从一个函数变量到另一个。如果您想使用在多个功能的变量是什么,你所能做的就是在全球范围定义变量,然后在不同的功能

global_var = 10 

def func1(): 
    global global_var 
    #rest of the function 

def func1(): 
    global global_var 
    #rest of the function 

UPDATE我下面想注释使用它,我想我应该分享这个和你。虽然在你的情况下,全局变量似乎是一个不错的选择,但请记住,使用全局变量是而不是被认为是良好的做法。所以我会建议你使用参数传递。我会建议你通过这个http://www.learncpp.com/cpp-tutorial/4-2a-why-global-variables-are-evil/

+0

请不要推荐全局变量。 –

相关问题