"print" throws an invalid syntax error in Python 3 - python

I am brand new to python. I have been working on the courses on Codecademy. I am also currently using Pydev / LiClipse.
In one of the first lessons on Codecademy it wants you to set the variable parrot to "Norwegian Blue". Then it wants you to print the length of parrot using the len string method. It is very simple, and I got the answer right away with:
parrot = "Norwegian Blue"
print len(parrot)
When I put the exact same code into LiClipse it returned:
SyntaxError: invalid syntax
It work in LiClipse when I changed it to:
print (len(parrot))
Can someone let me know why that worked in codecademy, but not in LiClipse, and why adding the parenthesis fixed it?

It sounds like Pydev/LiClipse is using Python 3 while Codeacademy is using python 2.x or some other older version. One of the changes made when python updated from 2.x to 3 was print is now a function.
Python 2:
print "stuff to be printed"
Python 3:
print("stuff to be printed")

You must take into account the version in which you are working.
In Python 2 your code would look like this:
parrot = "Norwegian Blue"
print len(parrot)
In Python 3 your code would look like this:
parrot = "Norwegian Blue"
print ( len(parrot) )

It worked in CodeAcademy because their interpreter is a Python 2.7, where you didn't need the parenthesis because print was a statement. In Python 3.0+, print requires the parentheses because it's a function.
More information on what's different between Python 2.7 and 3.0+ can be found here:
What's New In Python 3.0
Some of the sample differences with print on the above page:
Old: print "The answer is", 2*2
New: print("The answer is", 2*2)
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
Old: print # Prints a newline
New: print() # You must call the function!
It's good to know the differences between both, in case you're working with legacy systems and the lot vs. in your private environment. In Python 2.7 and below, print() works; however, omitting the ()s does not work in Python 3.0+, so it's better to get into the habit of using them for print.
End of life for Python 2.7 is expected to be in 2020, so you have plenty of time anyway.

In Python 3 print was changed to require parenthesis. CodeAcademy is probably using Python 2 and it looks like you're using Python 3.
https://docs.python.org/3/whatsnew/3.0.html#print-is-a-function
From the docs
Print Is A Function
The print statement has been replaced with a
print() function, with keyword arguments to replace most of the
special syntax of the old print statement (PEP 3105). Examples:

Related

Does escaping work differently in Python shell? (Compared to code in file)

In a Python 3.7 shell I get some unexpected results when escaping strings, see examples below. Got the same results in the Python 2.7 shell.
A quick read in the Python docs seems to say that escaping can be done in strings, but doesn't seem to say it can't be used in the shell. (Or I have missed it).
Can someone explain why escaping doesn't seem to work as expected.
Example one:
input:
>>> "I am 6'2\" tall"
output:
'I am 6\'2" tall'
while >>> print("I am 6'2\" tall")
returns (what I expected):
I am 6'2" tall
(I also wonder how the backslash, in the unexpected result, ends up behind the 6?)
Another example:
input:
>>> "\tI'm tabbed in."
output:
"\tI'm tabbed in."
When inside print() the tab is replaced with a proper tab. (Can't show it, because stackoverflow seems the remove the tab/spaces in front of the line I use inside a code block).
Basically your terminal is calling repr magic method of the string when you enter it in terminal as is. In the same time when you call print over the string it calls __str__ method on it:
s = "I am 6'2\" tall"
s.__repr__()
'\'I am 6\\\'2" tall\''
s.__str__()
'I am 6\'2" tall'
See more on that comparison between those two methods: str vs. repr
and that SO Difference between __str__ and __repr__? question.
Good Lack in your future python adventures.
The interactive shell will give you a representation of the return value of your last command. It gives you that value using the repr() method, which tries to give a valid source code representation of the value; i.e. something you could copy and paste into code as is.
print on the other hand prints the contents of the string to the console, without regards whether it would be valid source code or not.

how to run old code where print is used as keyword with python 3.x?

I know that in python 3 the keyword print became a function.
But is it possible to reuse my old code without replacing every
print "Error text"
by:
print("Error text")
per hand?
I would suggest you to read about Automated Python 2 to 3 code translation and see if it can be useful to you or not ?

'{:08b}' .format(i) Equivalent in Python 2.x

I have a small bit of code in Python 3 -
'{:08b}' .format(i)
that gives an error in Python 2.x. Does anyone know the equivalent?
Your original code actually works in Python 2.7. For Python 2.6, you need to introduce a reference to your format argument - either an index (0):
'{0:08b}'.format(i)
or a name:
'{x:08b}'.format(x=i) # or:
'{i:08b}'.format(i=i) # or even:
'{_:08b}'.format(_=i) # (since you don't care about the name)
Strangely enough, this particular quirk doesn't seem to be mentioned in the documentation about string formatting :(
Try this:
def fun(i):
print ('{0:08b}'.format(i))
fun(i) # Put any decimal number instead of i in fun(i) like fun(5). The result will be the binary code for number five which is 00000101

Python print statement shows unwanted characters

I am new to python and am having difficulties with an assignment for a class.
Here's my code:
print ('Plants for each semicircle garden: ',round(semiPlants,0))
Here's what gets printed:
('Plants for each semicircle garden:', 50.0)
As you see I am getting the parenthesis and apostrophes, which I do not want shown.
You're clearly using python2.x when you think you're using python3.x. In python 2.x, the stuff in the parenthesis is being interpreted as a tuple.
One fix is to use string formatting to do this:
print ( 'Plants for each semicircle garden: {0}'.format(round(semiPlants,0)))
which will work with python2.6 and onward (parenthesis around a single argument aren't interpreted as a tuple. To get a 1-tuple, you need to do (some_object,))
You've tagged this question Python-3.x, but it looks like you are actually running your code with Python 2.
To see what version you're using, run, "python -V".
Remove the parentheses as print is a statement, not a function in Python 2.x:
print 'Plants for each semicircle garden: ',round(semiPlants,0)
Plants for each simicircle garden: 50.0

Weird program behaviour in Python

When running the following code, which is an easy problem, the Python interpreter works weirdly:
n = input()
for i in range(n):
testcase = raw_input()
#print i
print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]
The problem consists in taking n strings and deleting a single character from them.
For example, given the string "4 PYTHON", the program should output "PYTON".
The code runs ok, but if I take out the comment mark, the statement print i makes the interpreter give an unexpected EOF while parsing. Any idea on why this happens?
EDIT: I'm working under Python 2.5, 32 bits in Windows.
Are you sure that the problem is the print i statement? The code works as
expected when I uncomment that statement and run it. However, if I forget to
enter a value for the first input() call, and just enter "4 PYTHON" right off
the bat, then I get:
"SyntaxError: unexpected EOF while parsing"
This happens because input() is not simply storing the text you enter, but also
running eval() on it. And "4 PYTHON" isn't valid python code.
I am yet another who has no trouble with or without the commented print statement. The input function on the first line is no problem as long as I give it something Python can evaluate. So the most likely explanation is that when you are getting that error, you have typed something that isn't a valid Python expression.
Do you always get that error? Can you post a transcript of your interactive session, complete with stack trace?
This worked for me too, give it a try...
n = raw_input()
n = int(n)
for i in range(n):
testcase = raw_input()
print i
print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]
Note the n = int(n)
PS: You can continue to use n = input() on the first line; i prefer raw_input.

Categories

Resources