BubbleMonster
BubbleMonster

Reputation: 1416

If else statement - how to skip past else?

My code below works great, however, if I select '1', the code will run the if statement and print "success" but it will also run the else statement and exit. How can I stop the else statement running if the user selects 1,2 or 3?

Thanks!

print "\nWelcome to the tool suite.\nWhich tool would you like to use?\n"
print "SPIES - press 1"
print "SPADE - press 2"
print "SPKF - press 3"
print "For information on tools - press i\n"

choice = raw_input("")
if choice == "1":
    execfile("lot.py")
    print ("success")

if choice == "2":
    #execfile("spade.py")
    print ("success")

if choice == "3":
    #execfile("spkf.py")
    print ("success")

if choice == "i":
    print "Google Maps is awesome.\n"
    print "SPADE\n"
    print "SPKF\n\n"

else:
    print "Error, exiting to terminal"
    exit(1)

Upvotes: 1

Views: 6181

Answers (3)

dawg
dawg

Reputation: 103844

Rather than a long chain of if, elif, else, you can also use a mapping to do this:

def one():
    print "success one"

def two():
    print "success two"  

def three():
    print "success three"

def inf():
    print "Google Maps is awesome."
    print "SPADE"
    print "SPKF\n"    

choices={
    '1':one,
    '2':two,
    '3':three,
    'i':inf
}

try:
    choices[raw_input("Enter choice: ").lower()]()
except KeyError:
    print "Error, exiting to terminal"
    exit(1) 

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304175

You're looking for elif

if choice == "1":
    execfile("lot.py")
    print ("success")

elif choice == "2":
    #execfile("spade.py")
    print ("success")

elif choice == "3":
    #execfile("spkf.py")
    print ("success")

elif choice == "i":
    print "Google Maps is awesome.\n"
    print "SPADE\n"
    print "SPKF\n\n"

else:
    print "Error, exiting to terminal"
    exit(1)

This makes the entire block above a single conditional construct

Upvotes: 2

Dietrich Epp
Dietrich Epp

Reputation: 213338

You want the elif construct.

if choice == "1":
    ...
elif choice == "2":
    ...
else: # choice != "1" and choice != "2"
    ...

Otherwise, the different if statements are disconnected from each other. I've added a blank line for emphasis:

if choice == "1":
    ...

if choice == "2":
    ...
else: # choice != 2
    ...

Upvotes: 9

Related Questions