【问题标题】:Python function not working inside another function when calling itPython函数在调用它时不能在另一个函数中工作
【发布时间】:2021-03-18 06:18:50
【问题描述】:

当我在转换运行后尝试在每个选项中调用菜单函数时,它会将我带回菜单,但只会在原始选择中进行转换。如果我在运行 convertCelsius 函数后首先选择选项 1 并将我带回菜单函数,则任何选择仍只会转换为摄氏度。如何调用菜单功能,以便再次运行每个选项。

def menu():
    print("1. Celsius to Fahrenheit")
    print('2. Fahrenheit to Celsius')
    print('3. Exit')
    pick = int(input('Enter a choice: '))
    return pick

def convertCelsius():
    temperature = float(input('Write temp to convert from Celsius to Fahrenheit: '))
    fahrenheitTemperature = ((temperature * 1.8) + 32)
    print('Fahrenheit temperature is: ',fahrenheitTemperature)
def convertFahrenheit():
        temperature = float(input('Write tempt to convert from Fahrenheit to Celsius: '))
        celsiusTemperature = ((temperature - 32)* 5/9)
        print("Celsius temperature is: ", celsiusTemperature)

def main():
    choice = menu()
    while choice != 3:
        if choice == 1:
           convertCelsius()
           menu()
        elif choice == 2:
            convertFahrenheit()
            menu()
        elif choice==3:
           choice = menu()
main()

【问题讨论】:

  • 进入循环后,您永远不会更新choice。你应该每次都做choice = menu()

标签: python function data-conversion


【解决方案1】:

我认为你的意思是每次都做choice = menu()

def main():
    choice = menu()
    while choice != 3:
        if choice == 1:
           convertCelsius()
        elif choice == 2:
            convertFahrenheit()
        choice = menu()

【讨论】:

    猜你喜欢
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 2017-09-01
    • 2014-05-04
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    相关资源
    最近更新 更多