0

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

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()

现在我已经设置了一个错误循环,但我遇到的问题是我不知道在这种情况下用什么来更新循环。任何人?

我需要一些简单的东西。我需要与此 OP 中发布的代码接近的东西。就像是:

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

请注意,此代码也不起作用。它针对用户为“表达式”输入的每一个错误循环。

诸如以下内容之类的东西太高级了,我无法使用它们:

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

import string

expression = introduction()    
operators = {'*', '/', '+', '-'}
numbers = set(string.digits)
while any(char not in numbers and char not in operators for char in expression):
    print("Please enter valid inputs, please try again.")
    expression = introduction()
4

2 回答 2

1

您在第二个代码中非常接近。你需要做一些改变,你的代码应该是这样的: -

expression = ""
operators= set("*/+-")
numbers= set("0123456789")
while True:
    expression= introduction()  # You should read the next expression here
    for i in expression:
        if i not in numbers and i not in operators:
            print("Please enter valid inputs, please try again.")
            break # You should have a break here
    else:
        break

print expression  # Print if valid
  • 如果表达式无效,它只会跳出for loop 并继续while循环。
  • 并且,如果表达式有效,它将执行else block你的for-loop并跳出 while 循环。
  • expression在 while 循环之外使用,您需要在 while 循环之外声明它。
于 2012-11-08T11:00:47.853 回答
1

如果您不能使用all()or any(),您可以测试包含错误的列表的长度:

if [c for c in expression if c not in operators|numbers]:
    # error

没有|运算符:

if [c for c in expression if c not in operators and c not in numbers]:
    # error
于 2012-11-08T11:02:40.707 回答