【问题标题】:Prompting a user to quit or continue提示用户退出或继续
【发布时间】:2020-02-14 03:03:55
【问题描述】:

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

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】:

    if 'exit' 返回True,因为它是一个非空字符串。

    >>> bool('')
    False
    >>> bool('exit')
    True
    

    这意味着您每次迭代都调用break,因为exit 始终是True

    您还有一个问题,默认情况下input() 存储string 值。在您的用例中,您尝试返回整数和字符串。

    function(range(0,10)): 线上,您将获得TypeError

    test = '1'
    

    测试(范围(0,10))

    Traceback(最近一次调用最后一次): 文件“”,第 1 行,在 测试(范围(0,10))

    TypeError: 'str' 对象不可调用

    即使修复了这个TypeError,你也会得到False的回报,因为string不会存在于range()值中。

    bool(test in range (0, 10))
    #False
    

    我们可以通过将您的代码调整为以下来解决问题,请参阅 cmets 以获取有关每行功能的信息。

    run = True #We will run our loop based on the value of run
    terminate = ['quit', 'exit'] #Prompt termination words
    
    while run:
        function = input(prompt)
    
        # If the value stored in function is a NOT a digit Example: 'quit' AND the word exists in our terminate queries.
    
        if function.isdigit() is False and function in terminate:
    
            # Break the loop by setting run to False
    
            run = False
    
        # Else if, the valye stored in function IS a digit Example: '1' AND it is between 1-9
    
        elif function.isdigit() and 9 >= int(function) > 0:
            print(f"You entered {function}!")
        else:
            print("Invalid Answer, try again.")
    

    【讨论】:

      【解决方案2】:

      您的问题在这里:

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

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

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

      这会测试function 是否在列表中,如果在则中断。


      进行更改后,您的代码仍然会出现错误。目前尚不清楚您是要运行用户选择的功能,还是告诉他们他们选择了哪个功能。你应该尽可能多地澄清你的问题,或者问另一个问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-19
        • 2018-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多