Skip to main content
 首页 » 编程设计

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

2025年02月15日8bonelee

运行此代码后,如果我输入任何"is"或“否”,它的响应将出现在控制台中,可以简单地删除它并只显示“错误答案”。 ?

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 

请您参考如下方法:

我建议只在 Yes 或 No 的情况下打印 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 语句中的 break,我认为您应该给打错字的用户一个机会 :)

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