0

Can someone help me understand while loops?

I can't understand how both for and while loops work. I was having a problem with this piece of code items = int(input()) days = int(input()) #your code goes here while days>0: items *= 2 days-=1 print(items)

29th Mar 2022, 3:25 PM
Gabriel Bueno
4 Answers
+ 2
Basically, the way both loops work is based on repeating something until either the "while" or "for" condition is met. While: It will repeat the code while the condition "amount of days are greater than 0" You have a -1 days there, so each time the amount of days will eventually get to 0 and stop the loop. For: Normally, you set the repeats for an amount of times. For example, the amount of days = 4, then the loop would print until the amount of days = 0.
29th Mar 2022, 6:51 PM
Ausgrindtube
Ausgrindtube - avatar
+ 4
I recommend you to put a print statement into the while loop and output items and days on each iteration to see what is going on.
29th Mar 2022, 3:30 PM
Lisa
Lisa - avatar
+ 1
G'day lol if Lisa and Ausgrindtube have answered your question, you can edit your post to start with [Solved]. You could also adjust the tags to be something better than the silly "help", eg "python" "while" "loop" I see the Python while loop as being kind of like: test the condition, if false then skip, if true then run the following: code (indented for python) more indented code code not indented, this is where false would skip to, it is after the loops are finished. Your example: test if days is greater than zero indented code to do the algorithm indented code to reduce the counter loops now finished, print the result.
30th Mar 2022, 12:34 AM
HungryTradie
HungryTradie - avatar
0
This is the answer that sololearn shows you, I want to know how while and for loops work
29th Mar 2022, 6:22 PM
Gabriel Bueno