Why are both the 'else' and 'if' statements running?

Viewed 1119

While posting this question, I've already checked the other links that have similar titles. All of those either don't have an answer to my question, or don't apply to this piece of code. For example, the link here: Why is my batch script running both if and else statement when if statement matches? says that it's because the OP used echo in the script. Here, I don't use it but I still get the result of both the if and the else.

while True:
    selection = input("Type a command or use a page selection")
    if selection in ('exit','quit'):
        sys.exit()
    if selection in ('page 1','1'):
        print("Page 1 text here")
    if selection in ('page 2','2'):
        print("Page 2 text here")
    else:
        print("Invalid command or page number")
3 Answers

If this is one long conditional - you have to use elif in the middle:

if 1:
    a()
elif 2:
    b()
elif 3:
    c()
else:
    d()

Probably you want to use if-elif-else in these kind of situations:

while True:
    selection = input("Type a command or use a page selection")
    if selection in ('exit','quit'):
        sys.exit()
    elif selection in ('page 1','1'):
        print("Page 1 text here")
    elif selection in ('page 2','2'):
        print("Page 2 text here")
    else:
        print("Invalid command or page number")

To run only one if statement in a series of them you must have and else if statement, elif, everythime you put if, it is considered with the other if/elif/else statements. Your else statement is independent of the first two if statements, I fixed it below.

while True:
    selection = input("Type a command or use a page selection: ")
    if selection in ('exit','quit'):
        sys.exit()
    elif selection in ('page 1','1'):
        print("Page 1 text here")
    elif selection in ('page 2','2'):
        print("Page 2 text here")
    else:
        print("Invalid command or page number")
Related