我正在尝试创建连续的用户输入,但如果输入了错误的信息,则不希望它从头开始重新启动。例如,
a = 1
while a ==1:
Number = raw_input("Number: ")
if len(Number) != 3:
print "\n Error, please enter 4 digits \n"
else:
Day = raw_input("Day: ")
if not Day.isdigit():
print "\n Error, please enter day in digits \n"
此处,如果此人输入第一个输入的非4位数,则循环将结束并再次返回到开始。但是,如果他进入第二个输入并输入一个非数字字符串,循环也将结束并返回到开始。我如何让它不回到开始但又要求那一天?
答案 0 :(得分:3)
def myMethod():
a = 1
while True:
if a is 1 and len(raw_input("NUMBER: ")) is not 3:
print "ERROR IS HERE IN NUMBER"
else:
a = 2
if a is not 1 and raw_input("DAY: ").isdigit() is True:
a = 1
else:
print "ERROR IS HERE IN DAY"
myMethod()
你可以将它用于你的目的。关键是你需要保持一个键来检查DAY或NUMBER中是否有错误。
如果您需要任何其他说明,请与我们联系。 这会问你DAY:和NUMBER:无限
答案 1 :(得分:2)
您可以按功能简化:
def input_number(prompt, digits_num=0):
while 1:
s = raw_input(prompt)
if not s.isdigit():
print "\n Error, please input digits \n"
continue
if digits_num:
if len(s) != digits_num:
print "\n Error, please enter %d digits \n" % digits_num
continue
result = int(s)
break
return result
number = input_number("Number: ", 4)
day = input_number("Day: ")
print "\n number=%d, day=%d" % (number, day)
答案 2 :(得分:1)
为此,您需要两个单独的while
循环。一个用于number
,另一个用于day
。这是更正后的代码:
number = ""
day = ""
while True:
number = raw_input("Number: ")
if not number.isdigit() or len(number) != 4:
print "Error, Please enter a 4 digit number \n"
else:
break
while True:
day = raw_input("Day: ")
if not day.isdigit():
print "\n Error, please enter day in digits \n"
else:
break
print "Number: ", number
print "Day: ", day
答案 3 :(得分:1)
如果您可以在此类方案中使用Python 3,请使用Enum作为生产级代码。您可以随时根据需要操纵条件。我们走了:
from enum import Enum
class Status(Enum):
START = 1
MIDDLE = 2
END = 3
state = Status.START
while state != Status.END:
while state == Status.START:
Number = input("Number:")
if len(Number) != 3:
print("Invalid Number !")
else:
state = Status.MIDDLE
while state == Status.MIDDLE:
Day = input("Day:")
if not Day.isdigit():
print("Invaid Day !")
else:
state = Status.END
答案 4 :(得分:-3)
提升异常直到有效输入
template<typename T, typename K>
void update(T& sortedValues, const K& valuesToAdd) {
for (auto value : valuesToAdd) {
auto position = std::lower_bound(sortedValues.begin(), sortedValues.end(), value);
sortedValues.insert(position, value);
}
}