+ 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
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!")
+ 2
This works:
i=1
while i<=5:
print(i)
i=i+1
print("Finished!")
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.
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
0
Thank you. It worked!
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