While statement | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

While statement

While learning how to use “while” it was given this example: i = 1 while i <=5: print(i) i = i + 1 print("Finished!") I got it that this code will repeat every number from 1 to = or < than 5. What I didn’t get is why that line i = i +1? What’s the reason for that? I’d appreciate if someone could help me.

12th Dec 2018, 3:09 PM
Victor Biscio
Victor Biscio - avatar
5 Answers
+ 3
If i remains == 1, the loop will go on eternally. By increasing i, eventually it will be >5 and the loop will end. It is just an example for how a while loop works mechanically; normally you would have a condition that makes sense in the context of your program.
12th Dec 2018, 3:21 PM
HonFu
HonFu - avatar
+ 1
For example if you wanted to split a longer integer into its digits. a=[] n=547 while(n): # this means n!=0 a.append(n%10) n //= 10 the digits, starting from the last, will heap up in a, while n gets successively smaller. When it's gone (5//10==0), the loop ends. Another one: a=[] x = input() while(x): a.append(x) x = input() So as long as the user keeps inputting stuff, it will be appended, but as soon as there's no input (and x becomes an empty string == False) the loop ends. If the user doesn't even input anything at the start, the loop will never happen.
12th Dec 2018, 6:29 PM
HonFu
HonFu - avatar
+ 1
Another way is to not define a condition. print('(y)es or (n)o?') while True: # this runs forever x = input() if x in ('y', 'n'): break So here the loop is broken by force from the inside. An example of my own: https://code.sololearn.com/cx5AbYU28x9Z/?ref=app This function takes a string consisting of words and formats it into bookprint look. Two of the loops are: while words: So as long as there are words left in the original list, the whole procedure gets looped over and over while the word list shrinks. while len(line)<width: In that part I fill up the line with whitespace until the width and the length of the line are matched. while line[pos] == ' ': In that part, I just increase pos (index) by 1 until this 'cursor' is not over whitespace any longer. You can really make up any condition you want for your loop, and you can also break the condition (to leave the loop) however you need it.
12th Dec 2018, 6:43 PM
HonFu
HonFu - avatar
+ 1
HonFu Im still quite newbie but i think now with your last example its way clearer to me... I really appreciate your time and attention mate!
12th Dec 2018, 9:10 PM
Victor Biscio
Victor Biscio - avatar
0
HonFu So it could be anything like i = i + 10? if its possible could you give me an simple example for that? its still kinda cloudy for me. thank you so much!
12th Dec 2018, 5:59 PM
Victor Biscio
Victor Biscio - avatar