2014-10-18 56 views
0

因此,我目前正在学习如何编写Python代码。我决定做一个小程序,它要求用户输入一个词来命令程序做某些事情。尽管把这个词的每个变体都放入代码中,但我一直都有这个问题。我的问题是,我怎样才能防止这种情况?任何帮助,将不胜感激。请记住,我仍在学习Python,可能无法理解所有内容。这里是我的代码:如何使Python 3.4输入不敏感?

#This is the main program. 
if choice == '1': 
    print ("Not Availble Yet") 
    print (" ") 
    time.sleep(2.5) 
    main() 

#This is if you wish to quit. 
if choice =='2': 
    end = input ("Are you sure you'd like to quit? ") 

    #These are all the "I'd like to quit" options. 
    if end == 'yes': 
     print ("Closing Program in 5 seconds").lower 
     time.sleep(5) 
     quit 
    if end == 'Yes': 
     print ("Closing Program in 5 seconds").lower 
     time.sleep(5) 
     quit 
    if end == 'yEs': 
     print ("Closing Program in 5 seconds").lower 
     time.sleep(5) 
     quit 
    if end == ("yeS"): 
     print ("Closing Program in 5 seconds").lower 
     time.sleep(5) 
     quit 
    if end == ("YES"): 
     print ("Closing Program in 5 seconds").lower 
     time.sleep(5) 
     quit 


    #These are all the "I wouldn't like to quit" options. 
    if end == 'no': 
     print ("Continuing Program").lower 
     time.sleep(2.5) 
     main() 

谢谢!

+0

的if/elif的开关之前小写用户输入。哦,并且确实将它切换到if/elif struct,这会使它更具可读性。 – 2014-10-18 19:49:01

+1

请注意,“print(...)。lower”不起作用的原因至少有两个。 – jonrsharpe 2014-10-18 19:50:30

+0

要锐化@jonrsharpe留下的评论 - 您需要用圆括号实际调用lower()函数。简单地把'lower'这个单词返回给函数本身,而不是实际使字符串小写。我不太清楚还有什么其他原因使它无法工作......也许他会愿意详细说明吗? – Lix 2014-10-18 19:52:30

回答

3

小写输入:

end = input ("Are you sure you'd like to quit? ") 
end = end.lower() 

然后检查只"yes""no"

(这是所谓的“输入标准化”的一般原则,为了简化程序的非常常见的方式的实例。)

+0

非常感谢!就像我说的,我正在学习Python,但无法弄清楚这一点。你的方法帮助了我!谢谢! :d – oiestin 2014-10-19 19:27:28