Use if inside while : While « Language Basics « Python






Use if inside while

Use if inside while
 

import random  

# set the initial values from 1 to 5
the_number = random.randrange(5) + 1
guess = int(raw_input("Take a guess: "))
tries = 1

# guessing loop
while (guess != the_number):
    if (guess > the_number):
        print "Lower..."
    else:
        print "Higher..."
            
    guess = int(raw_input("Take a guess: "))
    tries += 1

print "You guessed it!  The number was", the_number
print "And it only took you", tries, "tries!\n"

           
         
  








Related examples in the same category

1.While loop with counter-controlled repetition.While loop with counter-controlled repetition.
2.While loop with sentinel-controlled repetiton.While loop with sentinel-controlled repetiton.
3.Analysis of examination results.
4.While loopWhile loop
5.How to use whileHow to use while
6.While loop demoWhile loop demo
7.While with breakWhile with break
8.Write an initial sub-sequence of the Fibonacci series
9.While with elseWhile with else
10.Guess My Number
11.A trailing comma avoids the newline after the output