[Tutor] functions

Steven D'Aprano steve at pearwood.info
Tue Dec 15 08:00:17 EST 2015


On Tue, Dec 15, 2015 at 11:19:33AM +0000, Matthew Lintern wrote:
> Hello,
> 
> I'm new to python and I've been following some youtube videos etc to learn
> python. I'm using the spyder IDE.  Im having problems with the following
> piece of code:
> 
> def myfun(x):
>     y=x**2
>     return y
> 
> print myfun(5)
> 
> the answer I should get is obviously 25, and this is the case in the video
> (https://www.youtube.com/v/GT1UfkLIeZ4?version=3&vq=hd1080&autoplay=1)
> 
> However, Spyder tells me theres a syntax error with myfun(5).  However, the
> videos shows no issue....?

I'm not familiar with Spyder, but I expect it should actually show 
you where the error is, or at least, where it *notices* the error 
for the first time.

For instance, you might see something like this:

py> print func(5}
  File "<stdin>", line 1
    print func(5}
                ^
SyntaxError: invalid syntax

Look carefully, and you will see I mis-typed the closing bracket ) as } 
instead.

Or you might get something like this:

py>   print func(5)
  File "<stdin>", line 1
    print func(5)
    ^
IndentationError: unexpected indent

Spyder might treat that as a syntax error.


If you get this:

py> print func(5)
  File "<stdin>", line 1
    print func(5)
             ^
SyntaxError: invalid syntax

Notice the caret ^ pointing just after the first word following "print"? 
In that case, try running these twolines of code instead:

import sys
print(sys.version)


If the version starts with 3, then you have discovered a minor nuisance 
when programming in Python: a slight difference between Python version 3 
and older versions.

In Python 3, "print" is a normal function, and so it must be called with 
parentheses:

    print(func(5))

In Python 2, "print" is a special statement, which doesn't require 
parentheses, so you can write this:

    print func(5)

Many tutorials are written for Python 2, and so they will show print 
with a space, but that's a syntax error in Python 3. Just remember to 
always use an extra pair of brackets for printing, and you should be 
fine.



-- 
Steve


More information about the Tutor mailing list