0

Need help - on exercice with While Loops "Time's up"

Hi everyone, Here's my code, and I didn't get the expected output: 3 2 1 0 # take the number as input number = int(input()) #use a while loop for the countdown while number > 0 : number = number - 1 print(number )

9th Apr 2025, 6:14 PM
Stef
Stef - avatar
4 Antworten
+ 5
If you want to print each number, the print() needs to be in the loop – not after it. Also, you decrease the number before printing it. When I enter 4, the first number printed will be 3.
9th Apr 2025, 6:21 PM
Lisa
Lisa - avatar
+ 4
Thank you all for your answer, I found m'y mistake.
9th Apr 2025, 11:48 PM
Stef
Stef - avatar
+ 2
In your code, as long as the while loop statement holds true, the number is decreased by 1. It is not printed because the print() function is not indented inside the while loop. So, it will only be executed once the loop breaks. Now, the last value of 'number ' before the loop terminates is 0. So, print () displays only 0 on the screen no matter what you enter as your number. You might want to change the order as follows: while number > 0: number -= 1 #same as number= number -1 print(number) For entering 4, the output will be: 3 2 1 0 To better suit an exercise "Time's up", you might want to print the user-entered number (here, 4) as well, because that is apparently how a stopwatch displays it. For that, you need to write the code as: while number > 0: print() number -= 1 #this code ensures that the number gets printed first, then decreased by one before the computer iterates over the while loop again.
9th Apr 2025, 11:37 PM
Ushasi Bhattacharya
+ 1
Stef, you're welcome.
9th Apr 2025, 11:57 PM
Ushasi Bhattacharya