For whatever reason when I type the print command in a function (NOT in the main code) it gives me a strange error message ‘Invalid Syntax, perhaps you forgot a comma’.
This is the code I was trying to run:
def gameTick ():
print (“string %s” % variable)
ONLy the second print command doesn’t work
variables = 0 # or whatever value you need to initialize it to
def gameTick ():
print ('string %s' % variables)
Note that you have to assign the variable “variables” outside the function and before it is assigned as a global inside the function definition.
You can’t call a function before it has been defined.
variables had two different spellings
As a side note, to enter code, use three of these: ~ in series (the key is just underneath the esc key. Press it along with the shift key. There should be three in series as in: ~~~) Include this series both above and below your code so that it appears as code here.
Not strictly true. All that has to happen is that the variable be assigned before it’s referenced (which applies to all variables). It’s often convenient to have a nice section up the top where you initialize all your globals, but that’s not actually a Python requirement, and sometimes it’s easiest to initialize something within the function that uses it.
Please read the pinned message about how to format your code. Currently the indentation is messed up and we can’t tell what your code actually is. Also please include the full error message and make sure that the example you provide reproduces this exact error message.
It may not be possible for us to help you on the basis of this small snippet of the code. Can you post a complete self-contained program that has the same problem? It might be necessary to cut out unnecessary parts, but keep on testing the program and make sure it’s still exhibiting the same problem.
Ah, well. That’s different from the code you showed us, which doesn’t have that mistake (but does have other mistakes or omissions, which could cause different problems). And either way, it’s different from what you already have - because the forum will convert ordinary quotes (the ones that you get by typing ' or " in a plain text editor) to “smart” quotes (nicer-looking ones that you might get automatically from a word processor; this is not caused by using a special font for the text, but is actually a different character), and doesn’t preserve the indentation of the code. Indentation is crucial in Python, because it’s how Python knows the structure of the code (e.g. which lines of code are inside a function and which are after it).
In order to understand code properly, we need to see it exactly as you actually have it - hence the formatting guidelines. Please read the pinned thread; proper formatting makes things easier for everyone.