提示用户退出或继续



我正在尝试编写一个提示用户选择函数或退出的代码。我希望它不断提示他们,直到他们输入"退出"或"退出"(任何形式,即所有大写或全部小写(。我似乎不知道如何让它运行。有什么提示吗?

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}

您的问题在这里:

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

Python 将这个条件分解为if function == 'quit'if 'exit',如果其中任何一个为真,就会中断。if 'exit'永远是正确的,因为你没有比较任何东西,'exit'也不是一个空字符串。应将此行更改为:

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

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


进行该更改后,代码仍将存在错误。不清楚是要运行用户选择的函数,还是告诉他们选择了哪个函数。你应该尽可能多地澄清你的问题,或者问另一个问题。

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

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

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

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

在线function(range(0,10)):你会得到一个TypeError.

test = '1'

测试(范围(0,10((

回溯(最近一次调用(: 文件 ",第 1 行,在 测试(范围(0,10((

类型错误:"str"对象不可调用

即使在修复此TypeError后,您也会得到False的回报,因为string不会存在于range()值中。

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

我们可以通过将代码调整为以下内容来解决这些问题,有关每行功能的信息,请参阅注释。

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.")

最新更新