我正在尝试为一些学生做一个简单的测验,如果他们输入错误的字母我想要重复这个问题,但我不确定我会怎么做。有人可以帮忙吗?
player score=[]
x2=raw_input("Question 3" '\n'
"How many tests have you taken in past 24 hours?" '\n'
"A) 0" '\n'
"B) 1" '\n'
"C) 2" '\n'
"D) 3" '\n'
"E) Too many to count"'\n')
if x2=="A":
player_score.append('0')
elif x2=="B":
player_score.append('1')
elif x2=="C":
player_score.append('2')
elif x2=="D":
player_score.append('3')
elif x2=="E":
player_score.append('4')
else:
print "you typed the wrong letter"
print player_score
答案 0 :(得分:1)
通常,确保正确输入(以及输入不正确时重新提示)的最佳方法是使用循环。在这种情况下,让我们做一个while
循环。
player_score = []
answer = ''
while answer.casefold() not in ('a','b','c','d','e'):
answer = raw_input("Question 3" "\n"
# etc etc etc
那就是说,看起来你正在建立一个测验,所以可能有更好的方法来解决这个问题。我假设每个问题("A" == 0
,"B" == 1
,"C" == 2
,"D" == 3
,"E"==4
)的答案都是相同的,所以让我们这样做。 ..
questions = [
"""Question 3
How many tests have you taken in past 24 hours?
A) 0
B) 1
C) 2
D) 3
E) Too many to count""",
"""Question 4
What kind of question should you write here?
A) I don't know
B) No bloomin' idea
C) It escapes me
D) Foobar
E) One with a question mark?"""]
player_score = []
for question in questions:
answer = ''
while answer.casefold() not in ('a','b','c','d','e'):
answer = raw_input(question+"\n>>")
answer = answer.casefold()
if answer == 'a': player_score.append(0)
if answer == 'b': player_score.append(1)
if answer == 'c': player_score.append(2)
if answer == 'd': player_score.append(3)
if answer == 'e': player_score.append(4)
else: print("Invalid response")
答案 1 :(得分:0)
一件简单的事情就是把它放在循环中并继续尝试直到它们给出可接受的输入:
#... as before, then...
done = False
while done == False:
x2=raw_input("Question 3" '\n'
"How many tests have you taken in past 24 hours?" '\n'
"A) 0" '\n'
"B) 1" '\n'
"C) 2" '\n'
"D) 3" '\n'
"E) Too many to count"'\n')
if x2=="A":
player_score.append('0')
done = True
elif x2=="B":
player_score.append('1')
done = True
elif x2=="C":
player_score.append('2')
done = True
elif x2=="D":
player_score.append('3')
done = True
elif x2=="E":
player_score.append('4')
done = True
else:
print "you typed the wrong letter"
重复和布尔值有点不愉快,因此可以重构。