Ryan Werner
Ryan Werner

Reputation: 65

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

Upvotes: 0

Views: 153

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121236

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 a a 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.

Upvotes: 4

mgilson
mgilson

Reputation: 309821

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. e.g. 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.

Upvotes: 0

Related Questions