+ 1

Invalid Syntax?

Hi! I tried the codes shown below, got an error somehow, does anyone know why? >>> i=1 >>> while i<=5: ... print(i) ... i=i+1 ... print("Finished!") File "<stdin>", line 4 print("Finished!") ^ SyntaxError: invalid syntax

20th Jan 2020, 8:00 PM
yang
yang - avatar
6 Réponses
+ 3
Because in the interactive shell the last print should be entered on a new block (>>>): >>> i=1 >>> while i<=5: ... print(i) ... i=i+1 ... >>> print("Finished!")
20th Jan 2020, 9:15 PM
visph
visph - avatar
+ 2
This works: i=1 while i<=5: print(i) i=i+1 print("Finished!")
20th Jan 2020, 8:04 PM
Denise Roßberg
Denise Roßberg - avatar
0
I am getting the same error. However, the interactive shell doesn't allow to create a new block and just continues in the loop. PLEASE HELP >>> i=1 >>> while i<=6: print(i) i= i+1 print("Finished") SyntaxError: invalid syntax If I press enter before writing print("Finished") code I get this: >>> i=1 >>> while i<=6: print(i) i=i+1 1 2 3 4 5 6 >>> I am not able to create a new block in python and IDLE both. I hope I am able to convey my doubt.
26th Jul 2020, 4:22 PM
Krupa Upadhyay
Krupa Upadhyay - avatar
0
That's the principle of interactive shell: you execute immediatly the command entered until it require a block... (only one statement at once). So, the only way to "embed" your print statement as a kind of workaround is to use nested statement/blocks, such as: >>> i=1 >>> for x in range(1): ... while i<=6: ... print(i) ... i = i+1 ... print("Finished") ... 1 2 3 4 5 6 Finished
26th Jul 2020, 7:24 PM
visph
visph - avatar
0
Thank you. It worked!
27th Jul 2020, 5:39 PM
Krupa Upadhyay
Krupa Upadhyay - avatar
0
Notice tgat the first statement (assignation of 1 to variable i) is executed immediatly after pressing enter key (before typing the rest), but you see nothing as assignation don't return any value ^^ A cleaner way to execute "many blocks" (many statements) at once would be to define a function embeding the code you want to execute at once (1st statement, without visible return value, as assignation), and then call it (2nd statement): >>> def f(): ... i = 1 ... while i<=6: ... print(i) ... i = i+1 ... print("Finished") ... >>> f() 1 2 3 4 5 6 Finished
27th Jul 2020, 6:52 PM
visph
visph - avatar