XYZ1007
XYZ1007

Reputation: 41

python: difference b/w multiple-ifs and if-elif-else in a while loop

I am new to Python and I have a question about using if statements inside while loop:

the code is for writing a number-guessing game till the number you entered matches the random integer generated.

the sample code is written as follows:

import random
answer=int(random.uniform(1,10))
number=int(input("guess:"))
if number==answer:
    print("correct!")
while(number!=answer):
    if number > answer:
        print("smaller!")
        number=int(input("guess again"))
    if number < answer:
        print("bigger!")
        number=int(input("guess again"))
    if number == answer:
        print("bingo!!")
        break

and the result I got was:

guess: 5 smaller! guess again 3 bigger! guess again 4 bingo!!

but when I used if-elif-elif or if-elif-else inside the while loop instead of the multiple if's, in the case of first guess was wrong and subsequent guess(es) were correct, the last bingo!! was not shown, for example:

import random
answer=int(random.uniform(1,10))
number=int(input("guess:"))
if number==answer:
    print("correct!")
while(number!=answer):
    if number > answer:
        print("smaller!")
        number=int(input("guess again"))
    elif number < answer:
        print("bigger!")
        number=int(input("guess again"))
    elif number == answer:
        print("bingo!!")
        break

the results became:

guess: 5 smaller! guess again 3

as shown, after last correct guess, the code just stopped, and "bingo!!" was not displayed.

Can anyone help me understand why this difference occurred when using multiple if's and if-elif-else/elif inside while loop? Thank you very much!

added: I realized my question eventually is, every time after I enter a new value for number, from where in the code it will be run again with the new number, and how is this different when I used multiple if's or if-elif-else.

Upvotes: 3

Views: 3902

Answers (4)

CrazyElf
CrazyElf

Reputation: 763

This behaves different

if condition1: -> checks
    do1 -> executes if condition1 is true
if condition2: -> checks too in any case!!
    do2 -> executes if condition2 is true

than this

if condition1: -> checks
    do1 -> executes if condition1 is true
elif condition2: -> checks only if condition1 is false!!
    do2 -> executes if condition1 is false and condition2 is true!!

Upvotes: 1

V&#237;ctor L&#243;pez
V&#237;ctor L&#243;pez

Reputation: 817

The solution is quite simple.

In your first example (if's node) you are using a if after if, so, when you ask the guess for a number, you will check the next if.

For example:

From this code:

while(number!=answer):
    if number > answer:
        print("smaller!")
        number=int(input("guess again"))
    if number < answer:
        print("bigger!")
        number=int(input("guess again"))
    if number == answer:
        print("bingo!!")
        break

If your number is bigger (Second if) and you type the correct one, you will check it in the third if. So the message will be printed.

In the other hand, we have the second example with the if/elif/else.

while(number!=answer):
    if number > answer:
        print("smaller!")
        number=int(input("guess again"))
    elif number < answer:
        print("bigger!")
        number=int(input("guess again"))
    elif number == answer:
        print("bingo!!")
        break

If we have the example in case number 1, and our guess say a bigger number, it will not check the third condition, because it's a condition of the first if. Code will go to while again, and it will not continue in case of "bingo".

Try this and you will see that code is the same. Try to use if/elif/else more than an if tree, because is the correct way to check things in python.

import random
number=-1
answer=int(random.uniform(1,10))
while(number!=answer):
    number=int(input("guess:"))
    if number > answer:
        print("smaller!")
        number=int(input("guess again"))
    elif number < answer:
        print("bigger!")
        number=int(input("guess again"))
    elif number == answer:
        print("bingo!!")
        break

Upvotes: 0

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95479

Simply put, "elif" (short for "else if") only executes if the prior "if" (or "elif") case didn't execute. If you have a series of "if" statements (rather than "if" followed by a series of "elif" statements), all the conditions in the former will be evaluated (and for any case where the condition evaluates to something truthy, the body of the corresponding "if" will be evaluated, too); by contrast, once a truthy case is found in the "if"..."elif" chain, no additional conditionals in the chain will be considered.

When using it in a loop (or anywhere, for that matter), you need to consider your intended behavior. A good habit to get into as a programmer is to ask yourself, "how could this go wrong?". And, as a good way of guessing that, consider "is it possible for both cases to be true? should both of these cases be executed if both situations match?". Note, also, that in the loop, you can get the same effect of "if ... elif" with a sequences of "if" by adding an explicit "continue" statement to get back to skip to the next iteration of the loop without evaluating the remaining "if" (or other) statements that remain.

Upvotes: 3

Tim Pietzcker
Tim Pietzcker

Reputation: 336118

Imagine the following (first program):

  1. You guess the wrong number (let's say 8 instead of 5) the first time.
  2. The while loop is entered because number!=answer
  3. You get the "smaller!" message, are prompted to guess again. Now you enter 5.
  4. The if number==answer: test is done within the same loop. Since it's now True, "bingo!!" is displayed.
  5. The while condition is tested, and since now your answer is correct, the loop will not be entered again.
  6. The program exits.

Now the second program:

  1. You guess the wrong number (let's say 8 instead of 5) the first time.
  2. The while loop is entered because number!=answer
  3. You get the "smaller!" message, are prompted to guess again. Now you enter 5.
  4. The elif number==answer: test is not done because the previous if clause already succeeded. No message is displayed.
  5. The while condition is tested, and since now your answer is correct, the loop will not be entered again.
  6. The program exits.

Upvotes: 0

Related Questions