我的程序在继续之前需要数学输入并检查错误,这是我需要帮助的代码的一部分:
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()
答案 0 :(得分: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
的{{1}}
打破了while循环。expression
,您需要在while循环之外声明它。答案 1 :(得分:1)
如果您无法使用all()
或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