2012-07-12 55 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