False
?
False
To 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
Name your file sum_up.py
and submit it to attendance on gradescope
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()
to_do
that takes a numeric argument temp
.86
and less than 104
68
and less than 86
main
function to request input from user until it is valid (only digits 0-9), print "Let us"
and the messageProgram behavior in your standard output:
Enter a temperature: abc Enter a temperature: 100abc Enter a temperature: 89 Let us go for a swim
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()