Functions

Functions in Python are super useful in separating your code, but they don’t stop there. Any code that you think you will ever use anywhere else, you should probably put in a function. You can also add arguments to your functions to have more flexible functions, but we will get to that in a little bit. You can define a function by using the keyword def before your function name. Let’s use our first Python function.

Example

Result

boo

It is necessary to define functions before they are called. Even though we have to skip over the function while reading to see the first statement, someFunction(). This throws us back up into the def someFunction():, again with a colon following it. Then after we acknowledge that the function is being called, we create a new line with four spaces for our simple print statement.

Functions with Arguments

Simple functions like the one above are great and can be used quite often. However, there usually comes a time where we want to have the function act on data that the user inputs. We can do this with arguments inside of the () the follows the function name.

Example

Result

463

Using the statement someFunction(12,451), we pass in 12, which becomes a in our function, and 451, which becomes b. Then, we just have a little print statement that adds them and prints them out.

Function Scope

Python does support global variables without you having to explicitly express that they are global variables. It’s much easier just to show rather than explain:

Example

This will cause an error because our variable, a, is in the local scope of someFunction. So, when we try to print a, Python will bite and say a isn’t defined. Technically, it is defined, but just not in the global scope. Now, let’s look at an example that works.

Example

In this example, we defined a in the global scope. This means that we can call it or edit it from anywhere, including inside functions. However, you cannot declare a variable inside a function, local scope, to be used outside in a global scope.

If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Facebook
Share on Google+
Google+
Share on StumbleUpon
StumbleUpon
Digg this
Digg
Tweet about this on Twitter
Twitter
Share on Reddit
Reddit

Leave a Comment

  1. There is a small grammatical error, nothing major. It says;"This will cause an error because is in the local scope of someFunction." there should be an it after the because i think. But other than that this guide is amazing so far.

  2. The examples in this section does not work in Phyton.

    Copied from Phyton Shell:

    >>> def someFunction():
    print("boo")
    someFunction()
    SyntaxError: invalid syntax

    To fix the problem, press enter until you see the >>> sign again before calling the function.

    Copied from Phyton Shell:

    >>> def someFunction():
    print("boo")

    >>> someFunction()
    boo
    >>>

  3. Error after error. Python will not pick up on the second somefunction:

    def somefunction(a, b):
    print(a+b)
    somefunction(12, 451)
    SyntaxError: invalid syntax

  4. Short and sweet. Great job in teaching Python. I bet you could even use twitter to teach a topic without exceeding the 140 character limit! 🙂 JK. But seriously, echoing Jeremy F below, thanks for these tutorials. Its fantastic!

  5. Great tutorial but I get some syntax error while put the codes from the examples. And after trying the solutions as Erica said in the comment, I got the exact result. I’m using Python 3.3.2 Shell.
    Keep up the great work 🙂

  6. I am using Python 2.7.5 on a Fedora 19 install. I use the development IDE program called Geany for an editor and testing code. So far, all the code in this tutorial has worked as instructed. I had purchased two books on Python but they were over my head right now and when I looked for beginner tutorials I found this site. Thank you for providing an easy way for us to learn.

  7. Tutorial is simple & clear. But why Code Simulator doesn’t work? Nothing happens to the test codes on pressing ‘Test Code’ button.

  8. i wrote the exact same code:
    def someFunction(a, b):
    print(a+b)
    someFunction(12,451)

    But this appears: File "<pyshell#57>", line 3
    someFunction(12,451)
    ^
    IndentationError: unindent does not match any outer indentation level

    any ideas?

  9. Great tutorial!.but i was trying to test my code and its tellin me error in line 3,pls can any body help me detect my error?
    This is how i wrote the code:
    def function():
    print("boo")
    some function().
    Thats all,but its telling me parse error:bad input in line 3.pls i need your help after hour programmers.

  10. How can I del my comment which is by mistake posted twice 🙁
    Suggetion – There should a cancel or delete button for removing comment..

  11. I really like the order that the lesson come in (at least, while perusing the Python section, since that is the only one I have tried so far).

    One possible error. On the "Python Functions" page, it says, "Python does support global variables." I think that you meant that it does *not* support…

  12. "However, you cannot declare a variable inside a function, local scope, to be used outside in a global scope." Why is this so?

  13. RAGhav, you must type:
    def er(a,b):
    print (a + b)
    er(10,12)

    or
    a = 10
    b = 12
    def er():
    print (a + b)
    er()

    the problem are the variables, "However, you cannot declare a variable inside a function, local scope, to be used outside in a global scope"

  14. so…

    a = 69

    def getitonwiththewife():
    print (a)

    getitonwiththewife()

    ——————————————
    69

  15. If there we can find some other complicated examples it`d be great! Thanks, since now, so far, so good! Keep up the good work!

  16. (�°�°��︵ ��� FLIP THIS TABLE!
    ��� ︵ �(°�°�) FLIP THAT TABLE!
    ��� ︵ \( °�° )/ ︵ ��� FLIP ALL THE TABLES NAO!
    ಠ_ಠ Put.
    ಠ__ಠ The tables.
    ಠ___ಠ Back…
    (�°-°)���� ��� ���

  17. Python 3.2.3 (default, Feb 27 2014, 21:33:50)
    [GCC 4.6.3] on linux2
    Type “copyright”, “credits” or “license()” for more information.
    ==== No Subprocess ====
    >>> a=10
    >>> def someFunction():
    print(a)
    someFunction()

    SyntaxError: unindent does not match any outer indentation level
    >>>

  18. Python 3.2.3 (default, Feb 27 2014, 21:33:50)
    [GCC 4.6.3] on linux2
    Type “copyright”, “credits” or “license()” for more information.
    ==== No Subprocess ====
    >>> a=10
    >>> def someFunction():
    print(a)
    someFunction()

    SyntaxError: unindent does not match any outer indentation level
    >>>

  19. >>> def someFunction(a,b):

    print(a+b)

    >>> someFunction(12,451)

    Need to learn my spacing got it to work by putting in a couple of returns etc.

  20. NameError: name ‘someFuntion’ is not defined on line 4

    I keep getting this anyone know why ? What I inputted

    j = 56
    def someFunction():
    print (j)
    someFuntion()

  21. For those getting an error, remember to leave the line after defining the function empty. For example:
    def someFunction(a, b):
    print(a+b)
    # this line should be empty to avoid syntax error
    somefunction(12,451)

  22. def someFunction():
    print(“boo”)
    someFunction() <---- has a syntax error when I put it in and hit enter. What am I doing wrong?

  23. There’s a typo in the first paragraph after “Functions with Arguments.” In the third sentence, the second instance of “the” should be “that”: “We can do this with arguments inside of the () [the] >that< follows the function name.

  24. Can’t we define a function for if?

    for eg:

    def posorneg(num):
    if num<0:
    print("-ve")
    elif num>0:
    print(“+ve”)
    else:
    print (“neutral”)

  25. I tested the claim:
    “… we can call [a variable] or *edit* it from anywhere, including inside functions.”

    with the following code:

    a = 10

    def aFunction(a):
    a += 1
    print(a)

    aFunction(a)
    print(a)

    This returns
    11
    10

    Which indicates we *cannot* edit a variable inside a function.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.