我如何“循环”这个其他声明?

时间:2017-12-12 20:22:23

标签: python python-3.x

我对Python很陌生,我正在创建这个'测验'。

answer_1_choices = {
    'A' : 'A: A list is a datatype that stores a sequence of items with individual indexes that are mutable.',
    'B' : 'B: A list is a datatype that stores a sequence of items with individual indexes that are immutable.',
    'C' : 'C: A list is a datatype that stores a sequence of items assigned to individual keys that are immutable.'
    }
Number_One = '1. What is a list?'

def answer():
    x = input()
    if x == 'A' or x == 'a':
        print('Correct!')
    else:
        print('That is an incorrect response.  Please try again.' + '\n' + '\n' + Number_One + '\n')
        print(answer_1_choices['A'] + '\n' + '\n' + answer_1_choices['B'] + '\n' + '\n' +  answer_1_choices['C'])
        print('\n' + 'Is the answer A, B, or C?  Type the letter of your choice.')

def question_one():
    print(Number_One + '\n')
    print(answer_1_choices['A'] + '\n' + '\n' + answer_1_choices['B'] + '\n' + '\n' +  answer_1_choices['C'])
    print('\n' + 'Is the answer A, B, or C?  Type the letter of your choice.')


question_one()
answer()

每当输入不是“A”或“a”时,我希望else语句无限运行。我知道我必须使用某种循环或其他东西,但我似乎无法弄明白。有人能帮助我吗?

2 个答案:

答案 0 :(得分:7)

您正在考虑的是while循环。您可以尝试测试x = 'A' or x = 'a'是不是x还是'A',而不是检查'a'

试试这个:

while (x != 'A' and x != 'a'):
    print('That is an incorrect response.  Please try again.' + '\n' + '\n' + Number_One + '\n')
    print(answer_1_choices['A'] + '\n' + '\n' + answer_1_choices['B'] + '\n' + '\n' +  answer_1_choices['C'])
    x = input('\n' + 'Is the answer A, B, or C?  Type the letter of your choice.')
print('Correct!')

这样,它只会打印"正确!"一旦破裂条件得到满足。

答案 1 :(得分:-1)

在else案例的最后一行添加一个递归调用:

 answer()

完整代码:

def answer():
    x = input()
    if x == 'A' or x == 'a':
        print('Correct!')
    else:
        print('That is an incorrect response.  Please try again.' + '\n' + '\n' + Number_One + '\n')
        print(answer_1_choices['A'] + '\n' + '\n' + answer_1_choices['B'] + '\n' + '\n' +  answer_1_choices['C'])
        print('\n' + 'Is the answer A, B, or C?  Type the letter of your choice.')
        answer()