+ 1

I can't understand this while statement in Python.

>>> i = 1 >>> while i <=5: ... print(i) ... i = i + 1 ... print("Finished") ... I typed it in Python, and got the following result: 1 Finished 2 Finished 3 Finished 4 Finished 5 Finished What's my mistake??? I want the output to be: 1 2 3 4 5 Finished

18th Jul 2020, 3:00 PM
Advik
Advik - avatar
8 ответов
+ 3
Ok, so do the following: i = 1 while i <=5: print(i) i = i + 1 print("Finished") #Don't use identation (Whitespace)with the while loop otherwise it will be considered as the part of looping so it will keep repeating it. Leaving a line after it will not be considered as the part of while loop.. So, this will give you your desired output. Try it yourself, you will get to know about that.. Hope it's clear now 🙂
18th Jul 2020, 5:15 PM
Arctic Fox
Arctic Fox - avatar
+ 3
Whats mistake? You mean Finished also printing in loop..? Since it added you as part of while loop.. It is also printing.. Make it out of loop.... Identation is important in python. Which tells which statements belong to which block.. Check this : i = 1 while i <=5: print(i) i = i + 1 print("Finished") Edit: ADVIK this lines works for that. Do you checked it? (1,2,5 lines with no space. 3,4 lines have tab space)
18th Jul 2020, 3:04 PM
Jayakrishna 🇮🇳
+ 2
Here's there is no mistake. Instead,you can ask what do you want the code to do and show your attempt. Then,we would have helped you. While Loop keeps iterating until it evaluates to false. In your given example: I can't understand this while statement in Python. i = 1 # i is assigned the value 1 while i <=5: # while loop is used. # It will keep repeating itself until the statement is evaluated to false. print(i) i is printed before adding 1 to it. i = i + 1 # Keeps running until it will become equal to or greater than 5 print("Finished") # keeps printing "Finished" each time it will iterate (repeat) i.e 5 times..
18th Jul 2020, 3:52 PM
Arctic Fox
Arctic Fox - avatar
+ 2
ADVIK I think, Better to paste that code in code playground and share it's link here.. Writing here may have some identation problem..
19th Jul 2020, 6:43 AM
Arctic Fox
Arctic Fox - avatar
+ 2
Got it dude, thanks for the help!!!
19th Jul 2020, 1:45 PM
Advik
Advik - avatar
+ 1
ADVIK while test the condition for true if its true then it executes As your case, at first "i" is 1 which is true for i<=5. So the code executes
18th Jul 2020, 3:03 PM
AKSHAY🇮🇳
AKSHAY🇮🇳 - avatar
0
Hey dude, I want the output to be: 1 2 3 4 5 Finished That's what they showed in the lesson.
18th Jul 2020, 5:04 PM
Advik
Advik - avatar
0
Hey dude, I still can't get it. I typed the following in pycharm:- i = 1 while i <=5: print(i) i = i + 1 print ("Finished") And still getting the same result...
19th Jul 2020, 2:58 AM
Advik
Advik - avatar