while loop intro (slides)

CSc 110 - Intro to While Loops

Announcements

  • Midterm 1 Febuary 19 – BRING PHOTO ID
  • Modules 1 to 5 – study guide under practice problems page on website

While loops

  • A while loop allows a programmer to repeat code
  • You can think of it as an if-statement with the potential to repeat
statements . . .

while conditionA:
    statementA
    statementB
    . . .
    statementN

statements . . .

What will happen?

number = 15
while number < 50:
    print('number is less than 50')

While loops

  • What if the condition never evaluates to False?
    • Infinite loop!
  • There are two ways around this:
    • Break (do not use in this class!)
    • Designing the code such that the condition will eventually become False

What will happen?

To ensure our condition (number < 50) will eventually be evaluated as False, we need to updated number inside our loop:

number = 15
while number < 50:
    print('number is less than 50')
    number += 5
print('End')

While loops – visualization

Go to Python Tutor to visualize how the while loop runs.

While loop – example

Factorial: 5! = 1 * 2 * 3 * 4 * 5 = 120

def factorial(n):
  result = 1
  current = 1
  while current <= n:
    result = result * current
    current += 1
  return result

def main():
  print( factorial(5) )
  print( factorial(6) )
  
main()
120
720

while loops table

Consider n = 5, start with result = 1, current = 1:

current <= 5 result = result * current current += 1
True result = 1 * 1 current = 1 + 1
True result = 1 * 2 current = 2 + 1
True result = 2 * 3 current = 3 + 1
True result = 6 * 4 current = 4 + 1
True result = 24 * 5 current = 5 + 1
False - -

Write a function

Write a function called add_up_to that takes an numeric argument n. The function should add all numbers from 1 to n in a while loop, and then (outside the loop) return the sum

print( add_up_to(5) ) # 15
print( add_up_to(10) ) # 55

Name your file sum_up.py and submit it to attendance on gradescope

Write a function – solution

def add_up_to(n):
  sum = 0
  current = 0
  while current <= n:
    sum += current
    current += 1
  return sum

def main():
  print( add_up_to(5) )
  print( add_up_to(10) )
  
main()
15
55

Age milestones

Modify main function: use a while loop to request a valid input from the user.

def age_milestones(age):
  message = ""
  if age >= 18:
      message += 'You may apply to join the military.'
     
  if age >= 21:
      message += ' You may drink.'
     
  if age > 35:
      message += ' You may run for president.'
      
  return message

def validate_age(age):
  return age.isnumeric()
     
def main():
  str_age = input('How old are you?\n')
  if validate_age(str_age):
    age = int(str_age)
    print(age_milestones(age))
  else:
    print("Invalid age entered.")
 
main()

Age milestones continued

Program behavior in your standard output:

How old are you?
abc
How old are you?
10abc
How old are you?
55
You may apply to join the military. You may drink. You may 
run for president.

Age milestones – solution

Modify main function: use a while loop to request a valid input from the user.

def age_milestones(age):
  message = ""
  if age >= 18:
      message += 'You may apply to join the military.'
     
  if age >= 21:
      message += ' You may drink.'
     
  if age > 35:
      message += ' You may run for president.'
      
  return message

def validate_age(age):
  return age.isnumeric()
     
def main():
  str_age = input('How old are you?\n')
  while validate_age(str_age) == False:
    str_age = input('How old are you?\n')
  age = int(str_age)
  print(age_milestones(age))
  
main()

Write functions

  1. Write a function to_do that takes a numeric argument temp.
  2. It returns
    • ‘go for a swim’ if is greater equal to 86 and less than 104
    • ‘go for a hike’ if is greater equal to 68 and less than 86
    • ‘stay at home’ for all other cases
  3. Write a main function to request input from user until it is valid (only digits 0-9), print "Let us" and the message

Write functions continued

Program behavior in your standard output:

Enter a temperature:
abc
Enter a temperature:
100abc
Enter a temperature:
89
Let us go for a swim

Write functions – solution

def to_do(temp):
    if temp >= 86 and temp < 104:
        return "go for a swim"
    elif temp >= 68 and temp < 86:
        return "go for a hike"
    else:
        return "stay at home"
    

def main():
    str_temp = input("Enter a temperature:\n")
    while str_temp.isnumeric() == False:
        str_temp =  input("Enter a temperature:\n")
    message = to_do(int(str_temp))
    print("Let us", message)

main()