while-loop


A while-loop repeats code while a certain condition is met. The condition should be a “boolean” which evaluates to either True or False

 while condition: 
   body

GuessNum Example

Here's a game called GuessMyNumber. When the program starts, the computer will choose a random number. Then you will guess the number, and it will tell you whether it's too high or too low until you get it right.

Here's a sample output of the GuessMyNumber game:

I am thinking of a number between 0 and 99…
Enter a guess: 50
Your guess is too high 

Enter a new number: 25
Your guess is too high 

Enter a new number: 40
Your guess is too low

Enter a new number: 45
Your guess is too low  

Enter a new number: 48
Congrats! The number was: 48

This is the code for this program, with comments to describe what each line does:

#generate a random number, store it in the variable secret_number
secret_number = random.randint(1, 99)
print("I am thinking of a number between 1 and 99…")

#get our first guess from the user 
guess = int(input("Enter a guess: "))

# True if guess is not equal to secret number 
while guess != secret_number: 
   # True if guess is less than secret number 
   if guess < secret_number: 
      print("Your guess is too low")
   else: 
      print("Your guess is too high")
   print("") # an empty line 

   # get another guess from the user 
   guess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

Sentinel

A sentinel is a value that signals the end of user input

An example: Write a program that prompts the user for numbers until the user types -1, then output the total of the numbers. In this case, -1 is the sentinel value.

An example run of this program:

Type a number: 10
Type a number: 20
Type a number: 30
Type a number: -1
total is 60

Here's the code for this program, with comments to describe what each line does:

def main(): 
   #total is a variable to track the sum of the numbers
   #at the start of the program, we initialize total to be 0
   total = 0 
   
   # we get the first number from the user
   num = int(input("Type a number: "))
   # we have to first get a value for num because the next line of 
   # code checks for num's value 

   # -1 is our sentinel value. Our loop will stop if num == -1 
   while num != -1: 
      # update total to include our new number
      total += num

      # get another number for the user 
      num = int(input("Type a number: "))
      
      

   print(total) #print out the total once the user enters -1