简体   繁体   中英

My Python program won't terminate properly?

When I use the command to terminate the program, it does not terminate and instead assumes that I want to open another program when I say 'no' Here's my code:

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()

Look at:

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

Here you have several statements that always evaluate to True; each of 'internet' or 'Chrome' or 'Google chrome' is aa non-empty string. It doesn't matter what values do.lower() has. This means python sees that line as the equivalent of if something or True.

What you want to do instead is use the in operator to test if do is one of several options:

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

Note that I lowercased all options in the list to test; after all, you lowercase your input as well, so it'll never match "Chrome"; it'll be "chrome" or something else.

The same applies to your if oth.lower() == 'yes' or 'ye' or 'yeah': line.

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

You problem is in the above line.

In python, the truth value of a string depends on whether it is empty or not. eg bool('') is False . bool('ye') is True .

You probably want something like:

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

Consequently, you have the same problem in your browser check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM