0% found this document useful (0 votes)
9 views

Functions Exercise

The document discusses Python functions including defining, calling, passing arguments to, and returning values from functions. Functions allow code reuse and organization. Arguments can be passed to functions and functions can return values.

Uploaded by

jincy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Functions Exercise

The document discusses Python functions including defining, calling, passing arguments to, and returning values from functions. Functions allow code reuse and organization. Arguments can be passed to functions and functions can return values.

Uploaded by

jincy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Python Functions

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

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

Example

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

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

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

my_function()
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.

The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:

Example
def my_function(fname):
print(fname + " Refsnes")

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

Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.

From a function's perspective:

A parameter is the variable listed inside the parentheses in the function


definition.

An argument is the value that is sent to the function when it is called.


Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the function
with 2 arguments, not more, and not less.

Example
This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil", "Refsnes")

If you try to call the function with 1 or 3 arguments, you will get an error:

Example
This function expects 2 arguments, but gets only 1:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil")
The return Statement
We return a value from the function using the return statement.

# function definition
def find_square(num):
result = num * num
return result

# function call
square = find_square(3)

print('Square:', square)

Output

Square: 9

In the above example, we have created a function named find_square() . The


function accepts a number and returns the square of the number.

Note: The return statement also denotes that the function has ended. Any
code after return is not executed.
Types of Python Function Arguments
Python supports various types of arguments that can be passed at the time of the
function call. In Python, we have the following 4 types of function arguments.
 Default argument
 Keyword arguments (named arguments)
 Positional arguments
 Arbitrary arguments (variable-length arguments *args and
**kwargs)

Let’s discuss each type in detail.

Default Arguments
A default argument is a parameter that assumes a default value if a value is not provided
in the function call for that argument. The following example illustrates Default
arguments.
Example 1

# Python program to demonstrate

# default arguments

def myFun(x, y=50):

print("x: ", x)

print("y: ", y)

# Driver code (We call myFun() with only

# argument)

myFun(10)

Output:
x: 10
y: 50

Example 2

# Python code to demonstrate the use of default arguments


# defining a function
def function( n1, n2 = 20 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)

# Calling the function and passing only one argument


print( "Passing only one argument" )
function(30)

# Now giving two arguments to the function


print( "Passing two arguments" )
function(50,30)

Example 3

# Function definition is here


def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )

Keyword Arguments
The idea is to allow the caller to specify the argument name with values so that the
caller does not need to remember the order of parameters.
Example 1

# Python program to demonstrate Keyword Arguments

def student(firstname, lastname):

print(firstname, lastname)

# Keyword arguments

student(firstname='John', lastname='David')

student(lastname='David', firstname='John')

Output:
John David
David John

Example 2

# Function definition is here


def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return

# Now you can call printinfo function


# by positional arguments
printinfo ("Naveen", 29)

# by keyword arguments

printinfo(name="miki", age = 30)


Example 3

def div(numerator, denominator):


return numerator/denominator

print(div(numerator=10, denominator=5)) # 2.0


print(div(denominator=5, numerator=10)) # 2.0

Example 4:

def fruits(a, b, p):


print('We have', a+ ',', b+ ' and', p+ ' at our store.')

fruits('apple', 'banana', 'pineapple')

For the above program, we can use Keyword argument as follows –

# Arguments in order
fruits(a = 'apple', b = 'banana', p = 'pineapple')

# Arguments out of order


fruits(b = 'banana', p = 'pineapple', a = 'apple')

# 2 positional, 1 keyword argument


fruits('apple', b = 'banana', p = 'pineapple')

Output –

We have apple, banana and pineapple at our store.

All the above keyword argument methods will fetch the same output.

Note – However, we must remember that the keyword arguments must


always come after the positional arguments. There will be issues if a
positional argument is used after the keyword arguments.
Positional Arguments
We used the Position argument during the function call so that the first argument (or
value) is assigned to name and the second argument (or value) is assigned to age.
By changing the position, or if you forget the order of the positions, the values can be
used in the wrong places, as shown in the Case-2 example below, where 27 is assigned
to the name and Suraj is assigned to the age.

def nameAge(name, age):

print("Hi, I am", name)

print("My age is ", age)

# You will get correct output because

# argument is given in order

print("Case-1:")

nameAge("Suraj", 27)

# You will get incorrect output because

# argument is not in order

print("\nCase-2:")

nameAge(27, "Suraj")

Output:
Case-1:
Hi, I am Suraj
My age is 27
Case-2:
Hi, I am 27
My age is Suraj

Arbitrary Keyword Arguments


In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable
number of arguments to a function using special symbols. There are two special
symbols:

 *args in Python (Non-Keyword Arguments)


 **kwargs in Python (Keyword Arguments)

Using*argsand**kwargsin Functions
We can handle an arbitrary number of arguments using special symbols *args and **kwargs.

*args in Functions
As the name suggests, sometimes the programmer does not know the
number of arguments to be passed into the function. In such cases,
Python arbitrary arguments are used. In this, we use the asterisk (*) to
denote this method before the parameter in the function. This is also
called as Python *args.

The arguments are collected into a tuple, which can be accessed


within the function.

Python *args allows a function to accept any number of positional


arguments i.e. arguments which are non-keyword arguments, variable-
length argument list.

Remember ‘args’ is just a notation. We can use any other argument


name instead of it.

Example 1 –

# Program to add and display sum of n number of integer


def add(*num):
sum = 0;
for n in num:
sum = sum + n;
print("Sum:", sum)

add(3,4,5,6,7)
add(1,2,3,5,6,7,8)

Output –

Sum: 25
Sum: 32

In the above program, the programmer does not know in advance the
number of passing arguments in the function. Hence we have used the
Arbitrary arguments method. The *num accepts all the parameters
passed in the function add() and computes summation for all the values.

Python *args can also print data of various types which is passed into
the function. For example, Information related to a person such as a
Name, Sex, Age, City, Mobile number, etc.

Example 2 –

def Person(*args):
print(args)
Person('Sean', 'Male', 38, 'London', 9375821987)

Output –

('Sean', 'Male', 38, 'London', 9375821987)

Example 3:
Python program to illustrate *args with a first extra argument

def myFun(arg1, *argv):


print("First argument :", arg1)
for arg in argv:
print("Next argument through *argv :", arg)

myFun('Hello', 'Welcome', 'to', 'CodeIsFun')

Example 4:

# sum of numbers
def add(*args):
s=0
for x in args:
s=s+x
return s
result = add(10,20,30,40)
print (result)

result = add(1,2,3)
print (result)

*kwargs in Functions

Using **kwargs allows the function to accept any number of keyword arguments.
The `**kwargs` syntax allows us to pass a variable number of keyword arguments to

a function.

The arguments are collected into a dictionary, which can be accessed within

the function.

Let’s see an example:

Example 1::
def greet(**kwargs):

for key, value in kwargs.items():

print(f"{key}: {value}")

greet(name="Alice", age=25, city="New York")

In this example, the `greet` function accepts any number of keyword arguments

using the `**kwargs` syntax. The arguments `”name”: “Alice”,` `”age”: 25`, and

`”city”: “New York”` are collected into a dictionary `kwargs.` We then iterate over the

dictionary and print each key-value pair.

Example 2:
# function to print keyword arguments
def greet(**words):
for key, value in words.items():
print(f"{key}: {value}")

# pass any number of keyword arguments


greet(name="John", greeting="Hello")
Python Library Functions

Python provides some built-in functions that can be directly used in our
program.

We don't need to create the function, we just need to call them.

Some Python library functions are:

1. print() - prints the string inside the quotation marks


2. sqrt() - returns the square root of a number
3. pow() - returns the power of a number
These library functions are defined inside the module. And to use them, we
must include the module inside our program.

For example, sqrt() is defined inside the math module.

import math

# sqrt computes the square root


square_root = math.sqrt(4)

print("Square Root of 4 is",square_root)

# pow() comptes the power


power = pow(2, 3)

print("2 to the power 3 is",power)

You might also like