[英]python: global name 'user_input' is not defined
I keep getting the error message "global name 'user_input' not defined. new to python and to SO, hope you can help. Here's my code. Sorry if it's a mess. just starting out and teaching myself... 我不断收到错误消息“未定义全局名'user_input'。这是python和SO的新功能,希望您能提供帮助。这是我的代码。对不起,如果真是一团糟。
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
在menu
功能中,将显示ask_user()
的行更改为user_input = ask_user()
。
When you do: 当您这样做时:
user_input = input("Make a selection: ")
Inside the ask_user()
function, you can only access user_input
inside that function. 在
ask_user()
函数内部,您只能访问该函数内部的user_input
。 It is a local variable, contained only in that scope. 它是一个局部变量,仅包含在该范围内。
If you want to access it elsewhere, you can globalise it: 如果要在其他位置访问它,可以对其进行全球化:
global user_input
user_input = input("Make a selection: ")
I think what you were trying was to return the output and then use it. 我认为您正在尝试返回输出然后使用它。 You kind of got it, but instead of
ask_user()
, you have to put the returned data into a variable. 您有点了解,但是必须将返回的数据放入变量中,而不是
ask_user()
。 So: 所以:
user_input = ask_user()
THere's no need to globalise the variable (as I showed above) if you use this method. 如果使用此方法,则无需全局化变量(如我上面显示的那样)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.