python logo

python function


Python hosting: Host, run, and code Python in the cloud!

Python functions are powerful tools in programming. They enable you to create reusable blocks of code, thereby enhancing the efficiency and readability of your programs.
Python is renowned for its simplicity and functions play a vital role in this. By leveraging functions, programmers can reduce repetition, increase code clarity, and simplify testing and modifications.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Understanding Python Functions

To comprehend the power and structure of functions in Python, it’s essential to first understand their syntax and formation.

In Python, the def keyword signals the beginning of a function. This is followed by the function name and any parameters the function might need. The body of the function contains the operations to be carried out, and the function may or may not return a value.

Here’s a basic structure:

def function_name(parameters):
# Body of the function
return value

A Simple Python Function in Action

To illustrate, let’s look at a function that calculates the square of a number.

#!/usr/bin/python

def square(x):
return x * x

print(square(3))

This will produce the output:

9

The above example demonstrates a function with a single parameter, x. It’s worth noting that while functions can return a value (like our square function), not all functions are required to.

Delving Deeper: Multiple Parameters in Python Functions

Functions in Python can be more intricate. They can accept multiple parameters, making them incredibly versatile.

Consider this example:

#!/usr/bin/python

def multiply(x, y):
print(f'You called multiply(x,y) with the values x = {x} and y = {y}')
print(f'x * y = {x * y}')

multiply(3, 2)

The output will be:

You called multiply(x,y) with the values x = 3 and y = 2
x * y = 6

The key takeaway here is the versatility of functions in Python. Whether you’re working with a single parameter or multiple ones, Python functions are designed to streamline your programming efforts.

Dive deeper with Python exercises here

BackAdvance to the next topic





Leave a Reply:




Tony Sun, 03 May 2015

THe concept of scope isn't really all that clear in your example. The first code snippet will actually work, because the function isn't actually doing anything with z.

Perhaps:

#!/usr/bin/python


def f(x,y):
print 'You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str($
print 'x * y = ' + str(x*y)
print str(z) # cannot reach z, so THIS WON'T WORK

z = 3
f(3,2)

Perhaps other examples of code that does work as well:

#!/usr/bin/python

def f(x,y,a):
print 'You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str($
print 'x * y = ' + str(x*y)
print str(a) # can reach z, because it was passed to function f as parameter "a"

z = 3
f(3,2,z)

#!/usr/bin/python

def f(x,y):
z = 3
print 'You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str($
print 'x * y = ' + str(x*y)
print str(z) # z is local to function f, so it is reachable!

f(3,2)

... and an example of the confusion that can arise from reusing variable names:

#!/usr/bin/python

z = 5
print str(z)

def f(x,y,z):
print 'You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str($
print 'x * y = ' + str(x*y)
print str(z) # can reach z, because it was passed to function f as parameter "z"

z = 3
f(3,2,z)
Frank Sun, 03 May 2015

Hi Tony,

I extended this part to contain more code examples. It's rather late here so hope everything went fine. Thanks for the heads up!

Stuartjk Mon, 11 May 2015

Not sure how this one got missed as Tony obviously time looking at this one, but in all examples, the end of the first print line is incomplete.

print 'You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str($

will never work as you fail to correctly wrap the last str parameter ($), which itself is invalid.

should it not read

print 'You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y)

Stuartjk Mon, 11 May 2015

Also, in this example


#!/usr/bin/python

def doA():
a = 5

def doB(a):
print a # we pass variable as parameter, this will work

doB(3)


It is important to note that doB will print 3 which is the value passed to it, a=5 is contained within Doa and is still never used and therefore never visible to doB or the rest of the code.

Frank Mon, 11 May 2015

Thanks stuartjk, I extended the article :-)

Frank Mon, 11 May 2015

Thanks stuartjk! It seemed to disturb nobody thus far, but you are right.
The error came from copying source code from a terminal which capped the line. I fixed it and I'll copy from an IDE in the future. I hope you enjoy my articles, more will come soon.

Nub Sun, 12 Jul 2015

Hey Frank, thank you very much for providing this tutorial set. it is the best one i have come across. i have no programming experience besides playing around in HS, and the KISS method you use made this very easy

Anuj Wed, 15 Jul 2015

Hey frank .. What does +str (x) ...+Str(y) means ???

Frank Thu, 16 Jul 2015

Hi, this converts integers/floats to strings. Integers or floats are simply bytes in the memory and you cannot output them directly to the screen. str() converts them to human readable text.

Sh Tue, 21 Jul 2015

I agree with Tony.
Right now the article states:

#!/usr/bin/python

def f(x,y):
print 'You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str($
print 'x * y = ' + str(x*y)
print str(z) # cannot reach z, so THIS WON'T WORK

z = 3
f(3,2)


but I do see 3 get printed when I run the code.

Frank Tue, 21 Jul 2015

Hi, thanks for your comment! You can print it but not modify it. Try z = 4 inside the function and it will give you an error. I will update the article.

Roger's Mod Mon, 10 Aug 2015

Oh, didn't noticed that it's also explained here, really sorry.

Roger's Mod Mon, 10 Aug 2015

Does pointers exist in Python?
I'm not sure if 'pointers' is the right word ... I mean the direction of a variable in memory.
Can you use that as a parameter in order to modify the content of a variable as you can do in C programming?

Staff Mon, 10 Aug 2015

If you mean accessing the memory address directly, this is not a standard practice in Python. The language abstracts that for the programmer, in a similar way that C abstracts assembly or assembly abstracts machine language.

In Python 2.7 you can get the memory address, but this does not work with Jython, PyPy and Iron Python. It's a little tricky but here goes:

#!/usr/bin/env python

x = 3
print hex(id(x))

Python functions can return multiple return values, unlike C or C++, which you can then use to set your output variables. Variables (or objects) can be passed as parameters to a function.

Staff Mon, 10 Aug 2015

Hi Roger, no problem

Petr Sun, 16 Aug 2015

Please correct me if i wrong, but in this example:

#!/usr/bin/python


def f(x,y):
print 'You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y)
print 'x * y = ' + str(x*y)
z = 4 # cannot reach z, so THIS WON'T WORK

z = 3
f(3,2)


we declared global variable z and then trying to use it inside function. This variable is global and should be reached everywhere in the code, isn't it? So, why cannot we change a value? and what i have to do if i want to use the same name inside the function, but for local variable? is it impossible?

Frank Sun, 16 Aug 2015

Hi Petr, It is global if we define 'global z' inside the function. If not, Python creates a local variable z and sets that to 4. printing z after f(3,2) will show z is still 3.

#!/usr/bin/python

def f(x,y):
print 'You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y)
print 'x * y = ' + str(x*y)
z = 4 # cannot reach z, so THIS WON'T WORK
print('local variable in function, z = ' + str(z))

z = 3
f(3,2)
print('z outside function = ' + str(z))

Thus we have two variables 'z' in this case, one outside the function and one inside. To use the global z, we must define 'global z' on top of the function. To use a global variable z (no locals):

#!/usr/bin/python

def f(x,y):
global z
print 'You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y)
print 'x * y = ' + str(x*y)
z = 4 # cannot reach z, so THIS WON'T WORK
print('local variable in function, z = ' + str(z))

z = 3
f(3,2)
print('z outside function = ' + str(z))

To summarize, if we do not define 'global z', the global variable is out of the scope of the function. I hope you enjoy the site!

Rong Wed, 09 Sep 2015

Hi Frank,

When I run below program in https://repl.it/BG8w/2

def f(x,y):
print ('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))
print ('x * y = ' + str(x*y))
print('local variable in function, z = ' + str(z))

z = 3
f(3,2)
print('z outside function = ' + str(z))

I do get this result: local variable in function, z = 3. z is accessible in f(x,y). Why?

Frank Wed, 09 Sep 2015

You can print the variable inside f(x,y), but if you try z=2 inside the function it throws an exception. The Python interpreter executes all code at the 0th level of indention, which is why you can print z. The value of z cannot be changed inside the function because it is not a global variable nor parameter.

Sadia Thu, 24 Dec 2015

Dear Frank,
i am trying this code and it is giving me error: method() missing 1 required positional argument: 'a'
please guide me what i am doing wrong in this code.

def method(self,a):
return (self.a)

b=method(7)
print("the value of a is", a)
Frank Sat, 26 Dec 2015

Hi Sadia, you are mixing OOP with functional programming
Try this:

def method(a):
return a

b = method(7)
print("the value of b is " + str(b))
Sadia Wed, 10 Feb 2016

Hi Frank,
please let me know why it is important to keep same name of list while passing to function. here is a simple function that receives list on call and then add. if i change the name of list "a" in method call then it gives me error. why it is not allowed to change. in java while passing arguments we can change name.


def method(a):
print(a+a)
method(a=[1,2,4])

Frank Wed, 10 Feb 2016

In your example you give the name in the function call. Try calling it with method([1,2,3])