This question already has answers here:
python print done after while
(4 answers)
Closed 7 years ago.
li=['ram', 12, 13, 'shyam']
>>> for i in li:
... print(i)
... print("hi")
File "<stdin>", line 3
print("hi")
^
SyntaxError: invalid syntax
I'm working on Ubuntu shell with Python-1.7.2 and trying to simply loop through a list and want to add a print statement at the end. But it raises exception as above.
I don't be able to understand why it raise above exception. As for loop reaches it's end and I simply add a print statement outside for loop.
Please! help me to figure out what's going wrong?
After completing the block, you have to press Enter one more time.
When running in interactive interpreter, you need to leave an empty line after a block to indicate the end of the block, otherwise the interpreter assumes that the lines that come after the block are part of the block, and through the invalid syntax error (Like it did in your case).
Example -
>>> for i in li:
... print(i)
... # <---- notice the empty line
>>> print("hi")
Related
This question already has answers here:
Why doesn't the main() function run when I start a Python script? Where does the script start running (what is its entry point)?
(5 answers)
Closed 11 months ago.
This post was edited and submitted for review 11 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I am writing a function which is supposed to get the user's response, yet when I run the file nothing happens, its just an empty screen, how do I fix that? I tried searching up in stackoverflow but I couldnt find what im looking for, thanks in advance :)
def get_user_response():
while True:
try:
print ('Enter the number of clickbait headlines to generate: (0 to exit)')
user = int(input('> '))
print ('HEADLINES')
if user == 0:
for x in range (0,4):
l = "Exiting Program" + "." * x
print (l, end="\r")
sleep(1)
break
else:
print ('a')
except:
print ('Invalid - Enter an integer')
You defined a function but never called it anywhere. That's why the program is not running in the first place. Just write
get_user_response()
anywhere outside of the function.
Also consider wrapping only the user input line into the try except statement, otherwise you will literally catch every possible error that might occur in your function without ever getting an error message.
def get_user_response(trueorfalse):
while trueorfalse:
.....your codes
get_user_response(True)
your function should have arg like thaht
This question already has answers here:
Why doesn't exec("break") work inside a while loop
(6 answers)
Closed 3 years ago.
A recent question made me think if it is possible to do something like:
def defA(flag) :
return "value = 'yes'" if flag else "continue"
flag = False
#n can be a reasonable number like 100
for x in range(n):
#some logic that may change the flag
exec(defA(flag))
here, you got a variable assignment if the flag is true, or continue the for loop otherwise, but it gives me an odd error:
SyntaxError: 'continue' not properly in loop
Is it possible or should I let it go?
Because exec doesn't carry the context over to the statement being executed.
pass can be used anywhere, so the context doesn't matter. continue can only be used in the context of a loop, but that context is not available to exec.
You can only use continue in an exec statement if the loop itself is also part of the executed code:
f = 'for x in range(n): if(flag) continue' exec f
In other words, you can only use exec for complete statements, where a single continue (or break) is not complete.
This question already has answers here:
Printing on the same line with time.sleep()
(2 answers)
Closed 8 years ago.
I'm using Python 2.7.3 and I running the code below
def t2():
print "Waiting...",
time.sleep(3)
print "done."
time.sleep(1)
print "test"
time.sleep(2)
print "testing"
When I run this code, the string "Waiting... done." appear at same time. It's like the sleep(2) is before the first print.
If I don't use comma to remove new line (Like "test" and "testing" examples), sleep function works ok but I get "Waiting..." and "done." on different lines.
I already tried:
for i in range(0, 5): time.sleep(1)
and
subprocess.check_output(["sleep", "5"])
What can I do?
Thank you.
Depending what you are working with data doesn't necessarily get written right away. In particular,
display output often waits until it receives a newline before printing anything.
flush() makes sure it all gets written right now.
Background reading that helps explain better than I can:
Usage of sys.stdout.flush() method
Version: Python 3.3.2 (default, Sep 11 2013, 20:16:42)
Hey,
I'm doing some tests with python, fiddling a bit with the shell, but I get a strange error.
>>> a = 5
>>> if a > 0:
... print("a is a positive number.")
... if a < 0:
File "<stdin>", line 3
if a < 0:
^
SyntaxError: invalid syntax
I don't know why this error appears. I know I can use elif or else, but I just want to test.
Help?
This is valid Python syntax when it is located in a module, but in the interactive interpreter you need to separate blocks of code with a blank line.
The handy rule of thumb here is that you can't start a new block with if, def, class, for, while, with, or try unless you have the >>> prompt.
Are you pressing backspace to enter the second if? The shell doesn't like that. It's expecting another line in the logic block, or to be able to execute the block (by pressing enter one more time). The shell can only execute one block at a time, i.e. finish the first if first, then you can enter the second if. You can use elif because it's still considered part of the same logic block.
The REPL is still working on the previous code block. Enter an empty line on its own to terminate it first.
You need a blank line after your print statement, the Python interpreter thinks you're continuing a block until you do that, so you get an indentation error on your second if statement. This is not "invalid", the interactive interpreter is designed to work that way.
This code works when I try it from a .py file, but fails in the command line interpreter and Idle.
>>> try:
... fsock = open("/bla")
... except IOError:
... print "Caught"
... print "continue"
File "<stdin>", line 5
print "continue"
^
SyntaxError: invalid syntax
I'm using python 2.6
With Python 3, print is a function and not a statement, so you would need parentheses around the arguments, as in print("continue"), if you were using Python 3.
The caret, however, is pointing to an earlier position than it would be with Python 3, so you must be using Python 2.x instead. In this case, the error is because you are entering this in the interactive interpreter, and it needs a little "help" to figure out what you are trying to tell it. Enter a blank line after the previous block, so that it can decipher the indentation properly, as in this:
>>> try:
... fsock = open("/bla")
... except IOError:
... print "Caught"
...
(some output shows here)
>>> print "continue"
You need to leave a blank line to close the except block. The ... indicates it is still trying to put code in that block, even though you dedent it. This is just a quirk of the interactive interpreter.
Try this one in the interpreter:
try:
fsock = open("/bla")
except IOError:
print "Caught"
print "continue"
Important here is the empty line after the indentation. I'm using the python 2.6 interpreter and it throws the same Syntax error as you.
This is because the interpreter expects single blocks separated by blank lines. Additionally the blank line (two new line characters) indicates the end of the block and that the interpreter should execute it.
Like if/else or for or while, try/except is a compound statement. In a Python shell prompt, statements after control keywords: ... need to be indented because the statement or compound statement is executed one by one. Your last print("continue") is aligned with the top-level try: and considered another statement hence syntax error.
If you want to test out try/except/else/finally interactively, you can wrap them in a function:
>>> def t():
... try:
... print(x)
... except:
... print('exception')
... return
... finally:
... print('finally')
... print('continue')
... print('end function t()')
...
>>> t()
exception
finally
>>> x = 99
>>> t()
99
finally
continue
end function t()
>>>
This was done with Windows python shell. When I tried on PyCharm IDE python console, it allows one more statement after the compound statement to execute.
>>> n = 0
>>> while n!= 5:
... n+=1
... print('n = {}'.format(n))
n = 5 # no syntax error
>>>