使用条件python的原始输入

使用条件python的原始输入,python,raw-input,conditional,Python,Raw Input,Conditional,我正在尝试为一些学生做一个简单的测验,如果他们输入了错误的字母,我想重复这个问题,但我不确定我将如何去做。有人能帮忙吗 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

我正在尝试为一些学生做一个简单的测验,如果他们输入了错误的字母,我想重复这个问题,但我不确定我将如何去做。有人能帮忙吗

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

通常,确保正确输入(如果输入不正确,则重新提示)的最佳方法是使用循环。在本例中,让我们执行
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")

一个简单的方法是将其放入循环中并不断尝试,直到他们给出可接受的输入:

#... 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"

重复和布尔值有点令人不快,因此可以重构。

首先——您可能想标记为“家庭作业协助”?第二,如果你想循环,那么你需要添加一个循环。@user590028:我们不再用家庭作业状态标记问题(请参阅)。为什么玩家的分数是一个列表而不仅仅是一个字符串/整数?从什么时候起,
None
有了
casefold
方法?;^)@DSM他们在Python4.11中添加了它。我有超早期开发版本(已修复)string是否有casefold方法?(不在python 2.7中…):s@AndyHayden
str.casefold
是在Python3中添加的一种更具攻击性的小写形式。您可以在while循环的开头设置
done=True
,然后在else块中设置
done=False