I keep receiving SyntaxError message on ex41.py OR oop_test.py, and I've run through the whole script, everything is exactly as it is in the book, but I keep getting this - the variable {answer} is seemingly only defined in the try: section, so I have no clue why I am getting this SyntaxError.
***:hardway ***$ python ex41.py english
File "ex41.py", line 76
print(f"ANSWER: {answer}\n\n")
^
SyntaxError: invalid syntax
Here is the try: section, where the variable is at:
try:
while True:
snippets = list(PHRASES.keys())
random.shuffle(snippets)
for snippet in snippets:
phrase = PHRASES[snippet]
question, answer = convert(snippet, phrase)
if PHRASE_FIRST:
question, answer = answer, question
print(question)
input("> ")
print(f"ANSWER: {answer}\n\n")
except EOFError:
print("\nBye") `
The entirety of the code can be found here: Learning Python The hard way Ex. 41 - Learning to Speak Object-Oriented
Your code looks fine. The problem is the Python version you are running.
As mentioned in the comments above f strings were first introduced in Python 3.6 (see official documentation). If you want to use this feature you need to update to Python 3.6.
If you do not (or cannot) switch version you can use format() instead:
print("ANSWER: {}\n\n".format(answer))
OR use the old style %s (formatting string) operator:
print("ANSWER: %s\n\n" %answer)
See: What does %s mean in Python?
I would suggest format() over the second method though.
If you are making code that will be run on Python versions before Python 3.6 it it a good idea to use the alternatives listed above.
Related
I have received a python notebook that is full of expressions like f"{expr=}" that in my environment produce error messages:
var=7
print(f"{var=}")
File "<fstring>", line 1
(var=)
^
SyntaxError: invalid syntax
I suspect/expect that it could be in fact a new syntax for f"expr={expr}", i.e. as in the following print statement:
print(f"var={var}")
var=7
In fact I often use expressions like the latter for debug, and it would be nice to have a shorthand for it.
Is that a higher version of python than mine (3.7.6)? Or is it a customization of the fstring module?
Searching for it on the web or in SE was not productive.
And if it is not a standard feature, how can I get it to work?
Answer - Python Version 3.8
f-strings simplified a lot of places where str.format and % style formatting. There was still a place where you want to print a value of the variable or expression and also add some context with the string like variable name or some arbitrary name so that when you have many statements you can differentiate between the printed values. So using variable name followed by value is more common format of print style debugging.
Blockquote
This caused users to write f"name = {name}" and can get unwieldy when
variable names are long like filtered_data_from_third_party would be
written as f"filtered_data_from_third_party =
{filtered_data_from_third_party}". In those cases we resort to shorter
names we understand easily at the context like f"filtered data
{filtered_data_from_third_pary}". f-strings also support format
specifiers so you can write f"{name!r}" which is same as
f"{repr(name)}".
Given the above boilerplate an idea was posted in python-ideas around
a format specifier where you can use it and the f-string would expand
like a macro into <variable_name> = <value_of_variable>. Initially !d
was chosen so f"{name!d}" would expand to f"name={repr(name)}". This
was initially implemented in bpo36774. After discussion !d was changed
to use = with input from Guido and other core devs since there could
be usecases served by !d in the future and to reserve alphabetical
names in format-string for other uses. So this was changed to use = as
the notation for this feature in bpo36817. An overview of it’s usage
is as below with various features available.
Read more here
This feature was discussed in Python issue 36817 and released in Python 3.8.
I'm a beginner in programming, and I started my journey with Python. In my view, as shown below in the code block, the output to be come does matter, like, I used to think multiple type variables couldn't be wrote in one single line of code, but after having this exercise from one of the sources I learn from, I changed my view. This is because the code's output wouldn't have any other variable type rather than than string, so the line of code was right. Is this view right, or is it some different case?
Programming language= Python(version 3), IDE: PyCharm
Below is the code:
print("I said " + ("Hey "*2) + "Hey!")
print("I said "+"Hey "*2+"Hey!")
print("I said"+" Hey"*3+"!")
Below is the output:
I said Hey Hey Hey!
I said Hey Hey Hey!
I said Hey Hey Hey!
This is because Python has by default overloaded operators for the + and * operations. That means that these operators have specific definitions for the string class, in this case, concat for + and n concat of the same string for "string"*n
Here is more information about Operator overloading in Python
I am very new to programming and I'm starting out with Python. I tried to look up my question here but didn't really find anything.
I'm trying to work a very simple print command but I'm getting an error for some reason that I don't understand.
last = 'smith'
middle = 'paul'
first = 'john'
print(first.capitalize(), middle.capitalize(), last.capitalize(), sep='\t')
According to the answer in the book, this should be right, but every time I try to run it, I get an error with the 'sep':
print(first.capitalize(), middle.capitalize(), last.capitalize(), sep='\t')
^
SyntaxError: invalid syntax
Can someone tell me what I'm doing wrong. for what it's worth I'm using PyScripter.
[EDIT]
Thanks for that. I found out that I'm using Python 2.7.3 instead of 3.3. So I looked up the manual to see how the separator works. It seems to me that the only difference is with the square bracket. The manual describes the print function as :
print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout])
So I changed my print command and added the square bracket:
print ([first.capitalize(),middle.capitalize(),last.capitalize()] [, sep='\t'])
but unfortunately this doesn't work either as I get an error that highlights the square brackets around sep='\t'. Even when I take the brackets out, the error doesn't go away.
I'm not sure what I'm doing wrong, it seems like it should be very simple.
You aren't actually using Python 3, you just think you are. Try:
import sys
print(sys.version)
and see what comes out. The Python 2 print ... statement (not print(...) function in Python 3) interprets this as
print (first.capitalize(), middle.capitalize(), last.capitalize(), sep='\t')
which is trying to print a tuple with a keyword argument, thus the syntax error on sep
One of my early courses in the University I attend, was some basic training in Python 3 years ago. Now I was looking for a program that could help me resize some Grid stuff and I found something that could help me in Python. I reinstalled Python to my PC and found my old editor. However when I run the code I get an invalid syntax error that I can't understand. This is the part of the code that the error appears in :
def downsize(mode, cell_size, inpath, outpath):
from VolumeData import fileformats
try:
grid_data = fileformats.open_file(inpath)
except fileformats.Uknown_File_Type, e:
sys.stderr.write(str(e))
sys.exit(1)
reduced = Reduced_Grid(grid_data, mode, cell_size)
from VolumeData.netcdf.netcdf_grid import write_grid_as_netcdf
write_grid_as_netcdf(reduced, outpath)
The exact invalid syntax error is in the "except fileformats.Uknown_File_Type, e:" line. Can you help me ?
If you are using Python 3.x, you cannot use except fileformats.Uknown_File_Type, e. The comma works as an as statement (in the try/except block), so you should replace it with: except fileformats.Uknown_File_Type as e.
The comma works in Python 2.7, but not 3.x. However, the as should work for both.
Reference: Handling errors in Python 3.3
Maybe you misspelled 'Unknown'?
Here's my python code. Could someone show me what's wrong with it.
while 1:
date=input("Example: March 21 | What is the date? ")
if date=="June 21":
sd="23.5° North Latitude"
if date=="March 21" | date=="September 21":
sd="0° Latitude"
if date=="December 21":
sd="23.5° South Latitude"
if sd:
print sd
And Here's what happens:
>>>
Example: March 21 | What is the date?
Traceback (most recent call last):
File "C:\Users\Daniel\Desktop\Solar Declination Calculater.py", line 2, in <module>
date=input("Example: March 21 | What is the date? ")
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
>>>
Use raw_input instead of input :)
If you use input, then the data you
type is is interpreted as a Python
Expression which means that you
end up with gawd knows what type of
object in your target variable, and a
heck of a wide range of exceptions
that can be generated. So you should
NOT use input unless you're putting
something in for temporary testing, to
be used only by someone who knows a
bit about Python expressions.
raw_input always returns a string
because, heck, that's what you always
type in ... but then you can easily
convert it to the specific type you
want, and catch the specific
exceptions that may occur. Hopefully
with that explanation, it's a
no-brainer to know which you should
use.
Reference
Note: this is only for Python 2. For Python 3, raw_input() has become plain input() and the Python 2 input() has been removed.
Indent it! first. That would take care of your SyntaxError.
Apart from that there are couple of other problems in your program.
Use raw_input when you want accept string as an input. input takes only Python expressions and it does an eval on them.
You are using certain 8bit characters in your script like 0°. You might need to define the encoding at the top of your script using # -*- coding:latin-1 -*- line commonly called as coding-cookie.
Also, while doing str comparison, normalize the strings and compare. (people using lower() it) This helps in giving little flexibility with user input.
I also think that reading Python tutorial might helpful to you. :)
Sample Code
#-*- coding: latin1 -*-
while 1:
date=raw_input("Example: March 21 | What is the date? ")
if date.lower() == "march 21":
....
I had this error, because of a missing closing parenthesis on a line.
I started off having an issue with a line saying:
invalid syntax (<string>, line ...)?
at the end of my script.
I deleted that line, then got the EOF message.
While #simon's answer is most helpful in Python 2, raw_input is not present in Python 3. I'd suggest doing the following to make sure your code works equally well in Python 2 and Python 3:
First, pip install future:
$ pip install future
Second: import input from future.builtins
# my_file.py
from future.builtins import input
str_value = input('Type something in: ')
And for the specific example listed above:
# example.py
from future.builtins import input
my_date = input("Example: March 21 | What is the date? ")
I'm using the follow code to get Python 2 and 3 compatibility
if sys.version_info < (3, 0):
input = raw_input
I'm trying to answer in general, not related to this question, this error generally occurs when you break a syntax in half and forget the other half. Like in my case it was:
try :
....
since python was searching for a
except Exception as e:
....
but it encountered an EOF (End Of File), hence the error. See if you can find any incomplete syntax in your code.
i came across the same thing and i figured out what is the issue. When we use the method input, the response we should type should be in double quotes. Like in your line
date=input("Example: March 21 | What is the date? ")
You should type when prompted on console "12/12/2015" - note the " thing before and after. This way it will take that as a string and process it as expected. I am not sure if this is limitation of this input method - but it works this way.
Hope it helps
After the first if statement instead of typing "if" type "elif" and then it should work.
Ex.
` while 1:
date=input("Example: March 21 | What is the date? ")
if date=="June 21":
sd="23.5° North Latitude
elif date=="March 21" | date=="September 21":
sd="0° Latitude"
elif date=="December 21":
sd="23.5° South Latitude"
elif sd:
print sd `
What you can try is writing your code as normal for python using the normal input command. However the trick is to add at the beginning of you program the command input=raw_input.
Now all you have to do is disable (or enable) depending on if you're running in Python/IDLE or Terminal. You do this by simply adding '#' when needed.
Switched off for use in Python/IDLE
#input=raw_input
And of course switched on for use in terminal.
input=raw_input
I'm not sure if it will always work, but its a possible solution for simple programs or scripts.
Check the version of your Compiler.
if you are dealing with Python2 then use -
n= raw_input("Enter your Input: ")
if you are dealing with python3 use -
n= input("Enter your Input: ")
Check if all the parameters of functions are defined before they are called.
I faced this problem while practicing Kaggle.