我有一个程序,是简单指标的转换。我对python是个超级新手,需要一些帮助。
def main():
use_menu()
if feet_inches():
def use_menu():
get_menu()
selection = int(input('Please make a menu selection:'))
if selection == 1:
feet_inches()
elif selection == 2:
yards_feet()
elif selection == 3:
miles_yards()
elif selection == 4:
miles_feet()
def get_menu():
print('1. Convert feet to inches')
print('2. Convert yards to feet')
print('3. Convert miles to yards')
print('4. Convert miles to feet')
print('5. Exit')
def feet_inches():
feet2inches = int(input('Enter the number of feet:'))
answer1 = feet2inches / 3
return answer1
def yards_feet():
yards2feet = int(input('Enter the number of yards:'))
answer2 = yards2feet * 3
return answer2
def miles_yards():
miles2yards = int(input('Enter the number of miles:'))
answer3 = miles2yards * 1760
return answer3
def miles_feet():
miles2feet = int(input('Enter the number of miles:'))
answer4 = miles2feet * 5280
return answer4
main()
如何在主函数中打印返回值?当我试图将answer1设置为主函数中的变量时,我不断得到未解决的引用。我也在为如何写if/elif而挣扎。只要在正确的方向上稍微推动一下,我就很感激了。
第三行:
if feet_inches():
下面没有条件操作。
你可以尝试这样做:删除上面的第3行。
def use_menu():
get_menu()
selection = int(input('Please make a menu selection:'))
if selection == 1:
fi = feet_inches()
print(fi)
elif selection == 2:
yf = yards_feet()
print(yf)
elif selection == 3:
my = miles_yards()
print(my)
elif selection == 4:
mf = miles_feet()
print(mf)
您也可以在use_menu
中使用返回语句。然后将答案设置为该函数在主函数中的返回值。
def main():
answer = use_menu()
print(answer)
def use_menu():
get_menu()
selection = int(input('Please make a menu selection:'))
if selection == 1:
return feet_inches()
elif selection == 2:
return yards_feet()
elif selection == 3:
return miles_yards()
elif selection == 4:
return miles_feet()
您可以这样修改代码:
def main():
# First, retrieve function to be applied
func = use_menu()
if func is not None:
# Apply function - Could be done in one liner
res = func()
print(res)
def use_menu():
get_menu()
selection = int(input('Please make a menu selection:'))
if selection == 1:
return feet_inches
elif selection == 2:
return yards_feet
elif selection == 3:
return miles_yards
elif selection == 4:
return miles_feet
else:
return None