I'm moving to Python from PHP and I seem to be stuck in my first hour of learning Python.
This seems to be such a basic question that I'm having trouble finding an answer - so please forgive me.
When I try to create a dictionary I enter:
numbers = ('Bob':'322', 'Mary':'110', 'Joe':'839')
I get the error:
File "<stdin>", line 1
numbers = ('Bob':'322', 'Mary':'110', 'Joe':'839')
^
SyntaxError: invalid syntax
I've tried this in both the command line and in IDLE and the same error appears. What am I doing wrong? I really can't see it. Again sorry for low level of this question.
Dictionaries use curly braces {}, not parentheses ()
numbers = {'Bob':'322', 'Mary':'110', 'Joe':'839'}
Related
I am a newcomer to Python, and I'm using anaconda/jupyter.
Have been unable to decipher the following error message:
sims=[500]
For _ in range(1000):
File "<ipython-input-264-b9c4f88d1aeb>", line 1
for i in range(sims):
^
SyntaxError: unexpected EOF while parsing
In know the meaning of EOF but cannot find he error.
Help will be greatly appreciated
Considering the previous comments:
Your variable sims doesn't have to be a list because it is just a single number, or maybe you can call it later as for i in range(sims[0]):
Your code is finishing after that for, set for i in range(sims[0]):pass to let Python to know it is ending.
You have an uppercase in your first For, change it to for
I am working on a project using Python 2.7 and I am attempting to output a few string literals with objects. Ideally, each string literal should jump to the next line after each \n newline character.
I am still learning and am a novice programmer, so if I need to include more information please let me know and I will edit the question.
Here is what I am working on:
output = (
f"\nFinancial Analysis\n"
f"----------------------------\n"
f"Total Months: {total_months}\n"
f"Total Revenue: ${total_revenue}\n"
f"Average Revenue Change: ${revenue_avg}\n"
f"Greatest Increase in Revenue: {greatest_increase[0]}(${greatest_increase[1]})\n"
f"Greatest Decrease in Revenue: {greatest_decrease[0]} (${greatest_decrease[1]})\n")
Each time I run my script in the terminal, I receive the following error message:
SyntaxError: invalid syntax
(base) Grants-MacBook-Pro-2:PyBank grant$ python PyBank.py
File "PyBank.py", line 45
f"\nFinancial Analysis\n"
Can anyone offer a suggestion as to how I can tweak my code and correct the syntax? Thanks!
Python 2.7 doesn't have f-strings. Switch to 3.6+ or use .format() instead
For example you need to replace
f"Total Months: {total_months}\n"
with
"Total Months: {}\n".format(total_months)
If I have a file python_error_msg.py
x = [e for e in range(x)
x+=1
And I run it
$ python3 python_error_msg.py
The missing bracket gives the following error:
File "python_error_msg.py", line 2
x+=1
^
SyntaxError: invalid syntax
Why does it happen this way? My error was in forgetting the ] on the list comprehension. Is this something that could be made better, or is it a deeper matter of how Python syntax works?
Also, where can I look in the
codebase
to get an idea of how error reporting works in Python?
The problem is the error isn't official until that second line. Python keeps reading while inside parentheses (or brackets, braces, etc)
What if your code were this?
x = [e for e in range(x)
]
No error.
That said, in these cases I wish SyntaxError would say:
SyntaxError: invalid syntax on line 2 of parenthetical
(After all, even the most experienced programmers forget to close parentheses sometimes
This question already has answers here:
Syntax error on print with Python 3 [duplicate]
(3 answers)
Closed 9 years ago.
Note: This was not answered by the question that was marked as the original. This is more than just a Python v2 vs v3 problem, which I explain in the comments below.
Original post:
I am trying to learn Python at work, so I am currently using Portable Python 3.2.1.1 (which will henceforth be referred to as PP). (I mention this because this problem doesn't happen at home when I use my Mac and regular Python.)
I am working through exercise 16 of Learning Python the Hard Way (http://learnpythonthehardway.org/book/ex16.html). I've heard this isn't the best learning tool, but I am a complete programming n00b and I'm a hands-on learner. If you have any better suggestions, I'm open!
The first few lines of the exercise read:
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
My script is titled Ex16.py and the file I am using is Python.txt, and both of these are in the same folder as the PP .exes. I don't think that's necessary, but hoped maybe it would fix the problem... negative. When I press "Run" in PP, it doesn't work because argv requires you provide an argument when you start the script: python Ex16.py Python.txt
When I launch Python.exe (which, in PP is Portable-Python.exe), I get the standard Python prompt, >>>, but whatever I enter I get the same error message:
File "<stdin>", line 1
with whatever I've just tried repeated back to me with the marker to
indicate where the problem is. (has not been helpful so far)
SyntaxError: invalid syntax
I have tried typing the following at the >>> prompt:
python Ex16.py Python.txt,,
Ex16.py Python.txt,,
"%PATH&\Ex16.py" "%PATH%\Python.txt" (with the actual filepaths),,
print 'hello world'
I just keep getting the same invalid syntax error over and over. Even a basic print command returned an invalid syntax error. The only one that triggered a different error was the one where I tried whole filepaths. That one returned:
File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
position 2-3: truncated \UXXXXXXXX escape
Yes, I have Googled the crap outta both errors. I read that sometimes the problem is not doubling the backspaces, so I tried that, too, putting two \ where just one had been before in both filepaths. I even tried putting — # -*- coding: utf-8 -*- at the beginning of the script thinking maybe there was some unicode error. That, with the full filepaths, resulted in the same unicode error mentioned earlier.
Yes, I have checked that my code is matching that in the exercise.
Yes, this works at home on non-PP.
All this leads me to believe that the problem is probably in the way I'm trying to run the scripts in PP (but why won't print work?), but I haven't a clue what I'm doing wrong.
Thanks!
print is a function in Python 3:
print('my string with content and the like')
It is no longer supported as being a 'statement'. You might want to check out a list of things that changed from python2.x to python3.x (there's a number of incompatibilities). Also, you might be better off finding a tutorial using Python3.
You have to type:
Portable-Python.exe Ex16.py Python.txt
at your command prompt. To get a command prompt, press WindowsKey-R, then type "cmd" and press enter. You should now be looking at something like c:\>. Navigate to your portable python installation by using the cd command.
I am getting invalid syntax error in my python script for this statement
44 f = open(filename, 'r')
45 return
return
^
SyntaxError: invalid syntax
I am not sure what exactly is wrong here? I am a python newbie and so will greatly appreciate if someone can please help.
I am using version 2.3.4
I had the same problem. Here was my code:
def gccontent(genomefile):
nbases = 0
totalbases = 0
GC = 0
for line in genomefile.xreadlines():
nbases += count(seq, 'N')
totalbases += len(line)
GC += count(line, 'G' or 'C')
gcpercent = (float(GC)/(totalbases - nbases)*100
return gcpercent
'return'was invalid syntax
I simply failed to close the bracket on the following code:
gcpercent = (float(GC)/(totalbases - nbases)*100
Hope this helps.
I got an "Invalid Syntax" on return when I forgot to close the bracket on my code.
elif year1==year2 and month1 != month2:
total_days = (30-day1)+(day2)+((month2-(month1+1))*30
return (total_days)
Invalid syntax on return.
((month2-(month1+1))*30 <---- there should be another bracket
((month2-(month1+1)))*30
Now my code works.
They should improve python to tell you if you forgot to close your brackets instead of having an "invalid" syntax on return.
Getting "invalid syntax" on a plain return statement is pretty much impossible. If you use it outside of a function, you get 'return' outside function, if you have the wrong indentation you get IndentationError, etc.
The only way I can get a SyntaxError: invalid syntax on a return statement, is if in fact it doesn't say return at all, but if it contains non-ascii characters, such as retürn. That give this error. Now, how can you have that error without seeing it? Again, the only idea I can come up with is that you in fact have indentation, but that this indentation is not spaces or tabs. You can for example have somehow inserted a non-breaking space in your code.
Yes, this can happen. Yes, I have had that happen to me. Yes, you get SyntaxError: invalid syntax.
i just looked this up because i was having the same problem (invalid syntax error on plan return statement), and i am extremely new at python (first month) so i have no idea what i'm doing most of the time.
well i found my error, i had forgotten an ending parentheses on the previous line. try checking the end of the previous line for a forgotten parentheses or quote?
>>> 45 return
File "<stdin>", line 1
45 return
^
SyntaxError: invalid syntax
>>>
That might explain it. It doesn't explain the 44 f = open(filename, 'r'), but I suspect that someone copied and pasted 45 lines of code where the indentation was lost and line numbers included.
Usually it's a parenthetical syntax error. Check around the error.
I encountered a similar problem by trying to return a simple variable assignation within an "if" block.
elif len(available_spots)==0:
return score=0
That would give me a syntax error. I fixed it simply by adding a statement before the return
elif len(available_spots)==0:
score=0
return score
I had the same problem. The issue in my case was, that i mixed up datatypes in my return statement. E.g.
return string + list + string