Can anyone explain how to do a loop while using an if-else statement. | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
0

Can anyone explain how to do a loop while using an if-else statement.

#enter a number b/w 1 and 11, stop when user enters 0 or total goes over 21 user_num = int(input()) total = 0 while user_num >= 1 and user_num <= 11: if user_num != 0 or total < 21: print(user_num) total += user_num else: print("your total is", total) #is an infinite loop but not understand why

25th Sep 2016, 5:40 PM
Sarah
3 Respuestas
0
user_num never changes. Once total exceeds 21 you print "your total is" ... forever. Why not put an assignment in the else clause like user_num = 99 to break the loop? or you can use a break statement. Search on "break" and "continue" in Python for usage details.
25th Sep 2016, 6:07 PM
Frank Columbus
0
In your code is the condition of the while loop always true, because you assigned user_num outside the while-loop. So the value never can change and the condition is true again and again. the assignment of user_num has to be into the while-loop!!!
25th Sep 2016, 6:08 PM
Amarie
0
move the input to inside the while loop and add a break after the line "your total is". otherwise your loop will either never run (user inputs a number outside the range) or it will infinitely run (the user input is always the same, so the while loop is always true). better way is to do it this way.. total = 0 while True: #start infinite loop user_num = input ('enter a num > 0 and < 11: ') if user_num < 1 or user_num > 10: print ('entered a bad num') elif total >= 21: print ('your total is ', total) break #exits the loop only if total is 21 or more else: total += user_num print (user_num)
25th Sep 2016, 8:47 PM
Luke Armstrong