2012-07-12 22 views
0

当我使用命令来终止程序,它并没有终止,而是假定我想,当我说“不” 这里是我的代码来打开另一个程序:我的Python程序不会正确终止?

import getpass 
print 'Hello', getpass.getuser(), ', welcome!' 
do = raw_input ('What program would you like to open? ') 
if do.lower() == 'browser' or 'internet' or 'Chrome' or 'Google chrome': 
    import webbrowser 
    webbrowser.open ('www.google.com') 
    oth = raw_input ('Are there any others? ') 
    if oth.lower() == 'yes' or 'ye' or 'yeah': 
     oth2 = raw_input ('Please name the program you would like to open! ') 
else: 
    import sys 
    sys.exit() 

回答

0
if oth.lower() == 'yes' or 'ye' or 'yeah': 

你的问题是在上面的行中。

在python中,字符串的真值取决于它是否为空。例如bool('')Falsebool('ye')True

你可能想是这样的:

if oth.lower() in ('yes','ye','yeah'): 

因此,你必须在你的浏览器检查了同样的问题。

if do.lower() == 'browser' or 'internet' or 'Chrome' or 'Google chrome': 

这里有几个语句总是为true;:在

4

看'internet'或'Chrome'或'Google chrome'中的每一个都是非空字符串。 do.lower()具有什么值并不重要。这意味着python将该行看作等同于if或True的行。

你想要做的,而不是什么是使用in运算符来测试,如果do是几个选项之一:

if do.lower() in ('browser', 'internet', 'chrome', 'google chrome'): 

注意,我在列表中测试小写所有选择;毕竟,你也小写了你的输入,所以它永远不会匹配“Chrome”;它会是“铬”或其他东西。

这同样适用于您的if oth.lower() == 'yes' or 'ye' or 'yeah':系列。

+0

在选项的“元组”中; ^) – mgilson 2012-07-12 14:58:29