0% found this document useful (0 votes)
4 views7 pages

Python Functions: Arguments & Return Values

The document provides an overview of Python functions, including how to create and call functions, pass arguments, and use default parameter values. It explains the difference between passing by reference for mutable objects and passing by value for immutable objects, along with examples for each case. Additionally, it covers the use of *args and **kwargs for variable-length arguments and keyword arguments.

Uploaded by

princesonaxs
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views7 pages

Python Functions: Arguments & Return Values

The document provides an overview of Python functions, including how to create and call functions, pass arguments, and use default parameter values. It explains the difference between passing by reference for mutable objects and passing by value for immutable objects, along with examples for each case. Additionally, it covers the use of *args and **kwargs for variable-length arguments and keyword arguments.

Uploaded by

princesonaxs
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1- Python Functions

Creating a Function:
In Python a function is defined using the def keyword:

def my_function():
print("Hello from a function")

Calling a Function:
To call a function, use the function name followed by parenthesis:

def my_function():
print("Hello from a function")

my_function()
Output:
Hello from a function

2- Arguments

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as
many arguments as you want, just separate them with a comma.

def my_function(fname):

print(fname + " Refsnes")

my_function("Emil")

my_function("Tobias")

my_function("Linus")

Number of Arguments:
This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):


​ print(fname + " " + lname)
my_function("Emil", "Refsnes")
Arbitrary Arguments, *args:
If you do not know how many arguments that will be passed into your function, add a *
before the parameter name in the function definition.

This way the function will receive a tuple of arguments, and can access the items
accordingly:

def my_function(*kids):
​ print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

Output:
The youngest child is Linus

Keyword Arguments:
You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

def my_function(child3, child2, child1):


​ print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

Arbitrary Keyword Arguments, **kwargs:


If you do not know how many keyword arguments that will be passed into your function, add
two asterisk: ** before the parameter name in the function definition.

This way the function will receive a dictionary of arguments, and can access the items
accordingly:

def my_function(**kid):

​ print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")


Summary Table: Difference Between *args and **kwargs

Feature *args **kwargs

Type of arguments Non-keyword Keyword (named) args


passed (positional) args

Data type inside Tuple Dictionary


function

Function definition def func(*args): def func(**kwargs):


syntax

How to call the func(1, 2, 3) func(a=1, b=2)


function

Number of Any number of Any number of keyword pairs


arguments positional values

Purpose Pass a variable-length Pass a variable-length dictionary of


list of values key-value pairs
Default Parameter Value:

The following example shows how to use a default parameter value.

If we call the function without argument, it uses the default value:

def my_function(country="Norway"):
print("I am from " + country)

my_function("Sweden") # Output: I am from Sweden


my_function("India") # Output: I am from India
my_function() # Output: I am from Norway (uses default value)
my_function("Brazil") # Output: I am from Brazil

Return Values:
To let a function return a value, use the return statement:
def my_function(x):
return 5 * x

print(my_function(3)) # Output: 15 (because 5 * 3 = 15)


print(my_function(5)) # Output: 25 (because 5 * 5 = 25)
print(my_function(9)) # Output: 45 (because 5 * 9 = 45)

3- Pass variable to function by reference(Mutable)

When we pass a variable to a function, we are not sending a copy of it, but rather a
reference to the same object in memory.

In pass by reference, the original variable (memory address) is passed to a function.


Changes made inside the function affect the original object outside.

Key Points:

●​ Works with mutable objects (e.g., list, dict, set).


●​ The function modifies the original object, not a copy.
●​ Changes persist after the function call.
ex1:
def add_item(mylist):
[Link](100)
data = [1, 2, 3]
add_item(data)

print(data) # ✅: [1, 2, 3, 100]

ex2:

def update_dict(info):
info["status"] = "active"

user = {"name": "Ali"}


update_dict(user)

print(user) # ✅ {'name': 'Ali', 'status': 'active'}

ex3:

def add_element(myset):
[Link]("new")

items = {"a", "b"}


add_element(items)

print(items) # ✅ {'a', 'b', 'new'}


ex4:
def modify_list(mylist):
mylist[0] = 999

data = [10, 20, 30]


modify_list(data)

print(data) # ✅ [999, 20, 30]

4- Pass by Value(immutable)

In pass by value, a copy of the original value is passed to a function. Changes made
inside the function do not affect the original variable outside.

Key Points:

●​ Works with immutable data types (e.g., int, float, str, bool, tuple).
●​ The function operates on a copy, not the original.
●​ Original value remains unchanged after the function call.

ex1:

def add_to_tuple(t):
t = t + (4, 5)
print("Inside function:", t)

my_tuple = (1, 2, 3)
add_to_tuple(my_tuple)
print("Outside function:", my_tuple)

Output:
Inside function: (1, 2, 3, 4, 5)
Outside function: (1, 2, 3)
ex2:

def modify_number(x):
x = x + 10
print("Inside function:", x)

num = 5
modify_number(num)
print("Outside function:", num)

Output:
Inside function: 15
Outside function: 5

You might also like