如何在Python中从控制台删除未知用户输入

时间:2017-09-03 15:15:08

标签: python python-3.x

运行此代码后,如果我放了任何东西"是"或者" no",它的响应出现在控制台中,可以简单地删除它而只是出现"错误答案。" ?

import random

print("The random number is:")

for x in range(1):
    print(random.randint(1, 6))

while True:

    answer = input("Do you want to roll again? 'yes' or 'no' ")

    print(answer)

    if answer == 'yes':
        for x in range(1):
            print("The new number is:")
            print(random.randint(1, 6))


    elif answer == 'no':
        print("Thanks for playing.")
        break

    else:
        print("Wrong answer.")
        break

1 个答案:

答案 0 :(得分:1)

我建议只在“是”或“否”的情况下打印answer

while True:
    answer = input("Do you want to roll again? 'yes' or 'no' : ")

    if answer.lower() in ['y','yes', 'of course']:
        print('Yes')
        for x in range(1):
            print("The new number is:")
            print(random.randint(1, 6))


    elif answer.lower() in ['n', 'no', 'never']:
        print('No')
        print("Thanks for playing.")
        break

    else:
        print("Wrong answer.")

我刚刚更改了可能的答案以允许其他答案(更灵活的不区分大小写,添加其他单词......)

另外,我删除了else声明中的中断,我认为你应该让那些犯错误的用户有机会:)

(我不确定你需要一个for循环来获取随机数)