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.
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.
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:
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.
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.
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.
Thanks a lot for tutorial!!!
I guess multiline function and return statement will be discussed later
def someFunction():
print(“boo”)
someFunction()
😀 It’s fun !!!
Man I love these things
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”)
the follows the function name.
THAT
add an extra line after the print line, then do the next line of code and your result will show
so far so good, l am loving it 🙂
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.
@Calvinhobbe: As Python uses white space indentation the most likely cause is the lack of lines or spaces.
def someFunction():
print(“boo”)
someFunction() <---- has a syntax error when I put it in and hit enter. What am I doing wrong?
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)
if you had an experience in c or c++ it’s very easy to learn.
a=3 def function(): print(a+2) print(a) function() print(a)
@10032 typo … line 4
the best way to see the “Function Scope” is to try this:
a=3
def function():
print(a+2)
print(a)
function()
print(a)
@10032
This worked on mine :/ idk
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()
so far so good
I did something like a converter from mb to kb
Its just great to program in python
>>> def someFunction():
print(“boo”)
someFunction()
I couldn’t get this to work on IDLE
Random Level up names ahha
>>> 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.
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
>>>
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
>>>
This is really helpfull tnx!
(â?¯Â°â?¡Â°ï¼?â?¯ï¸µ â?»â?â?» FLIP THIS TABLE!
â?»â?â?» ︵ ã?½(°â?¡Â°ã?½) FLIP THAT TABLE!
â?»â?â?» ︵ ï¼¼( °â?¡Â° )ï¼ ï¸µ â?»â?â?» FLIP ALL THE TABLES NAO!
ಠ_ಠPut.
ಠ__ಠThe tables.
ಠ___ಠBack…
(â?®Â°-°)â?®â?³â?â?³ â?³â?â?³ â?³â?â?³
im just here… trying to get my commenter badge…
im just here… trying to get my commenter badge…
im just here… trying to get my commenter badge…
mwa lub this. this tutorial is helping me alot 🙂 (im a learner)
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!
so…
a = 69
def getitonwiththewife():
print (a)
getitonwiththewife()
——————————————
69
nice once
gr8 easily understood
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"
"However, you cannot declare a variable inside a function, local scope, to be used outside in a global scope." Why is this so?
Because i just got one… Lol
and, how the heck do you get xp to level up???
are you putting the two parentheses?
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…
this was a very good lesson ,very exited to start programming.
One another step in the syntax of the function statement and it’s errors sources.
It’s easy to define the function statement in Python. Many thanks for the syntax explanation
def addFunction():
a = 23
# print (a)
a+= 22
print (a)
addFunction()
a = (23)
b = (65)
def hFunction():
print (a + b)
hFunction()
How can I del my comment which is by mistake posted twice 🙁
Suggetion – There should a cancel or delete button for removing comment..
a = "Aqdas"
def someFunction():
print (a)
someFunction()
Love It to print my name again and again 🙂
same here works on tester but not on python3.3.3….this sections need a clearer example!!
Like many others said, it does not work in the Phyton 3.3.3 shell but does work in your "code tester".
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.
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?
Your print (a+b) is out of function-
try this:
def someFunction(a, b):
print(a+b)
someFunction(12,451
Tutorial is simple & clear. But why Code Simulator doesn’t work? Nothing happens to the test codes on pressing ‘Test Code’ button.
Should have mention how python can return values, it can also return more then one value.
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.
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 🙂
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!
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
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
>>>
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.