2013-11-01 30 views
0

我一直收到錯誤消息「global name'user_input'not defined。python new to希望你能幫到忙,這是我的代碼,很抱歉如果是一團糟。 。剛開始,教自己...python:未定義全局名'user_input'

def menu(): 
    '''list of options of unit types to have converted for the user 
    ex: 
    >>> _1)Length 
     _2)Tempurature 
     _3)Volume 
    ''' 

    print('_1)Length\n' '_2)Temperature\n' '_3)Volume\n' '_4)Mass\n' '_5)Area\n' 
      '_6)Time\n' '_7)Speed\n' '_8)Digital Storage\n') 

    ask_user() 
    sub_menu(user_input) 

def ask_user(): 
    ''' asks the user what units they would like converted 
    ex: 
    >>> what units do you need to convert? meter, feet 
    >>> 3.281 
    ''' 
    user_input = input("Make a selection: ") 
    print ("you entered", user_input) 
    #conversion(user_input) 
    return user_input 

def convert_meters_to_feet(num): 
    '''converts a user determined ammount of meters into feet 
    ex: 
    >>> convert_meters_to_feet(50) 
    >>> 164.042 
    ''' 

    num_feet = num * 3.28084 
    print(num_feet) 


def convert_fahrenheit_to_celsius(num): 
    '''converts a user determined temperature in fahrenheit to celsius 
    ex: 
    >>> convert_fahrenheit_to_celsius(60) 
    >>> 15.6 
    >>> convert_fahrenheit_to_celsius(32) 
    >>> 0 
    ''' 

    degree_celsius = (num - 32) * (5/9) 
    print(round(degree_celsius, 2)) 


def sub_menu(num): 
    '''routes the user from the main menu to a sub menu based on 
    their first selection''' 

    if user_input == '1': 
     print('_1)Kilometers\n' '_2)Meters\n' '_3)Centimeters\n' '_4)Millimeters\n' 
       '_5)Mile\n' '_6)Yard\n' '_7)Foot\n' '_8)Inch\n' '_9)Nautical Mile\n') 

     ask = input('Make a selection (starting unit)') 
     return 
    if user_input == '2': 
     print('_1)Fahrenheit\n' '_2)Celsius\n' '_3)Kelvin\n') 
     ask = input('Make a selection (starting unit)') 
     return 
+1

因爲'user_input'在'ask_user()'的範圍內定義,所以你在'sub_menu()'中檢查它。 – zero323

回答

0

當你這樣做:

user_input = input("Make a selection: ") 

ask_user()函數中,您只能在該函數內部訪問user_input。它是一個局部變量,僅包含在該範圍內。

如果你想在其他地方訪問它,你可以全球化它:

global user_input 
user_input = input("Make a selection: ") 

我想你試圖是要返回輸出,然後使用它。你有這種感覺,但不是ask_user(),你必須把返回的數據放入一個變量中。所以:

user_input = ask_user() 

如果您使用此方法,則無需全局化變量(如上所示)。

+0

謝謝!昨晚我瘋了。現在我看到它的工作原理很有意義。 – borgy88

0

在你menu功能,改變說ask_user()user_input = ask_user()