IF语句忽略键盘输入

时间:2018-04-26 18:14:47

标签: python if-statement stdin

我一直在尝试使用键盘输入来运行程序来决定是否运行程序而if语句忽略输入并始终默认为else语句。这是我的代码。

import random
import time
import sys

print("Do you want to run the program? Yes/No")
ans = sys.stdin.readline()

time.sleep(1)

if ans == "Yes" or ans == "yes":

    '''Body of IF statement'''

else:
    print("Alright, have a great day!")

1 个答案:

答案 0 :(得分:2)

readline()在其结果中包含换行符。使用strip()删除它(以及任何其他周围的空格)。

ans = sys.stdin.readline().strip()

或者使用更正常的input()函数:

ans = input("Do you want to run the program? Yes/No")

并使用lower() intead or来允许不区分大小写的响应(除非您确实希望将YESyES视为否)。

if ans.lower() == 'yes':
相关问题