python:全局名称';用户输入';没有定义

python:全局名称';用户输入';没有定义,python,global-variables,nameerror,Python,Global Variables,Nameerror,我一直收到错误消息“未定义全局名称'user_input'。对于python和其他语言来说都是新手,希望您能提供帮助。这是我的代码。如果它太乱,很抱歉。我只是开始自学 def menu(): '''list of options of unit types to have converted for the user ex: >>> _1)Length _2)Tempurature _3)Volume '''

我一直收到错误消息“未定义全局名称'user_input'。对于python和其他语言来说都是新手,希望您能提供帮助。这是我的代码。如果它太乱,很抱歉。我只是开始自学

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

菜单
功能中,当您执行以下操作时,将显示
询问用户()
的行更改为
用户输入=询问用户()

user_input = input("Make a selection: ")
ask_user()
函数中,您只能访问该函数中的
user_input
。它是一个局部变量,仅包含在该范围内

如果您想在其他地方访问它,您可以将其全球化:

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

我认为您尝试的是返回输出,然后使用它。您得到了它,但是您必须将返回的数据放入变量中,而不是
ask\u user()
。因此:

user_input = ask_user()

如果使用此方法,则无需全局化变量(如上所示)。

因为
user\u input
是在
ask\u user()
的范围内定义的,您可以在
sub\u menu()
中检查它。谢谢!昨晚这让我发疯了。现在我看到它在工作,这很有意义。