提示用户退出或继续

问题描述 投票:0回答:1

我正在尝试编写代码,以提示用户选择功能或退出。我希望它不断提示他们,直到他们键入“退出”或“退出”(任何形式,即全部大写或全部小写)。我似乎无法弄清楚如何使其运行。有提示吗?

import math

prompt = '''Enter a number for the function you want to execute.
        Type 'exit' or 'quit' to terminate.
1 sin(x)
2 cos(x)
3 tan(x)
4 asin(x)
5 acos(x)
6 atan(x)
7 ln(x)
8 sqrt(x)
9 factorial(x)
:'''

while True:
    function = input(prompt)

    if function == 'quit' or 'exit':
        break
    elif function(range(0,10)):
        print(f"You entered {function()}!")
    else:
        print("Answer not valid try again")

functions = {1: math.sin, 2: math.cos, 3: math.tan, 4: math.asin,
             5: math.acos, 6: math.atan, 7: math.log, 8: math.sqrt, 9: math.factorial}
python math input prompt
1个回答
0
投票

您的问题在这里。

if function == 'quit' or 'exit':

Python将此条件分为if function == 'quit'if 'exit',并且如果其中一个为true,则将中断。 if 'exit'始终为true,因为您没有进行任何比较,并且'exit'不是空字符串。您应该将此行更改为

if function in ['quit', 'exit']:

此测试是否function在列表中,如果存在则中断。

© www.soinside.com 2019 - 2024. All rights reserved.