Python更新循环

2024-04-29 10:34:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序接受一个数学输入并在继续之前检查它是否有错误,下面是我需要帮助的代码部分:

expression= introduction()#just asks user to input a math expression    
operators= set("*/+-")
numbers= set("0123456789")
for i in expression:
    while i not in numbers and i not in operators:
        print("Please enter valid inputs, please try again.")
        expression= introduction()

现在我已经设置了一个错误循环,但是我遇到的问题是我不知道在这个场景中用什么来更新循环。有人吗?你知道吗

我需要一些简单的东西,比如下面答案中的“while True”代码。其余的都太先进了。我需要一些接近这篇文章的代码


Tags: 代码in程序错误not数学justintroduction
2条回答
expression = introduction()    
operators = {'*', '/', '+', '-'}
while any(not char.isnumeric() and char not in operators for char in expression):
    print("Please enter valid inputs, please try again.")
    expression = introduction()

我会这样做:

valid = operators | numbers
while True:
    expression = introduction()
    if set(expression) - valid:
        print 'not a valid expression, try again'
    else: 
        break

您只想在每个坏的expression调用introduction()一次。现在的方法是,为expression中的每个无效字符调用introduction()。你知道吗

相关问题 更多 >