False?
FalseTo ensure our condition (number < 50) will eventually be evaluated as False, we need to updated number inside our loop:
Go to Python Tutor to visualize how the while loop runs.
Factorial: 5! = 1 * 2 * 3 * 4 * 5 = 120
while loops tableConsider 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 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
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()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.
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()