Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Session 18

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Python

Functions
Session-18
Functions
What are functions and when do we use it?

When we have a bunch of code that we require many times in the program, instead of writing it
N number of times, we can define (write) a function once. Whenever we need to execute that
block of code, we can simply call (execute) that function.
Simple functions
Defining a simple function

A function is defined with the keyword def followed by the name of the function. This is followed by the
parenthesis, which will contain the function arguments (we will learn about this later).

Inside the function you can write the lines of code that you want to execute when you execute the function.
Make sure the lines of code inside the function are equally indented.

The function can be ended with a return statement which will tell the function which values to output after
the function is executed. The return keyword will also exit/end the function.

def name_of_the_function(): #in this line we are defining the name of the function

code # in this region we write the program of what this function will do

code

return final_value # in this line we write the output of the function


Calling a simple function
To call a function, you have to mention the name of the function followed by the parenthesis.

name_of_the_function()

Example:

In this example, we are creating a function called sum(), which will add 2 numbers a *and *b. Here we
are hardcoding a and b values. We will see how we can change this later.

def sum(): #function defined using def keyword

a=5 #lines of code that will be executed when calling the function

b=4

add=a+b

return add #the add value will be returned by the function after it is done executing
Simple functions
Defining a simple function

A function is defined with the keyword def followed by the name of the function. This is followed by the
parenthesis, which will contain the function arguments (we will learn about this later).

Inside the function you can write the lines of code that you want to execute when you execute the function.
Make sure the lines of code inside the function are equally indented.

The function can be ended with a return statement which will tell the function which values to output after
the function is executed. The return keyword will also exit/end the function.

def name_of_the_function(): #in this line we are defining the name of the function

code # in this region we write the program of what this function will do

code

return final_value # in this line we write the output of the function


Functions with arguments

In the above example we have the same a and b adding, everytime we call the function. If we
want to call a function and give a different set of values to execute on, we have to use
arguments

Defining a function with arguments


This follows the same structure as a normal function, except that we can now add temporary
variables (called arguments) inside the parenthesis. These variables will be those whose values
you want to change in the program. (For example, in the sum problem, we would want a and b to
change.) You can use these temporary variables inside your function to do all kinds of
operations.

Also note that these temporary variables are not available outside your function.

def name_of_the_function(argument1, argument2):


code
code
return final_value
Calling a function with arguments
To call a function with arguments, you HAVE to mention the values of all the arguments inside the
parenthesis (we will learn how to avoid this later).

You can just mention the values of the corresponding arguments of the function in the same order as the
function definition.

name_of_the_function(value1, value2)

Incase you don’t know the order or want to use a different order, you can specify the argument name along
with the value

name_of_the_function( argument2 = value2, argument1 = value1 )


def sum(num1, num2): # here arguments num1 and num2 are given
add=num1+num2 # we use these arguments to do operations inside the function
return add
value=sum(1,5)
print(value)

value=sum(7,2)
print(value)

value=sum(100,65)
print(value)
6
9
165
value=sum() #function is called and its value is stored in variable assigned
print(value)
value=sum()
print(value)
value=sum()
print(value)
9
9
9

Every time you run the function, the output will remain the same.
Functions with default arguments

Sometimes certain arguments in the function will have the same value and might change only
occasionally. As such, it doesnt make sense to mention the same value in every function call. Or
sometimes you might want to use a certain default value incase the user doesnt know the value.
For such cases we have something called a default argument.

Defining a function with default arguments


This follows the same structure as a function with arguments, except that certain arguments
inside the function defination will have values assigned to them. Note that default arguments
should always come last in the function defination

def name_of_the_function(argument1, argument2=default_value):


code
code
return final_value
Calling a function with default arguments

In this case, the function call should always have the value specified for
argument1, but its not necessary to mention the value for argument2. If the value
of argument2 is passed in the function call, then that value willbe used, else if the
argument2 value is not specified in the function call, then the default_value will be
used

name_of_the_function(value1)
In this case,

argument1=value1

argument2=default_value

name_of_the_function(value1, value2)
In this case,

argument1=value1

argument2=value2
def sum(num1, num2=6): # here argument num2 is given a default value of 6
add=num1+num2
return add

value=sum(1,5) #when we provide a value for the 2nd argument, the default value is
not considered
print(value)

value=sum(7) # here the 2nd argument is not provided hence its default value will
be considered
print(value)

6
13
Lambda functions
Lambda functions is a special kind of function which has no name, it can take many arguments but has
only one statement.

Example:
x = lambda a,b : a+b #here a and b are arguments and x is the function
print(x(5,6)) #to call the function we use the variable x and pass a and b as arguments

11

Where are functions used?


Functions are used almost everywhere in the apps and games that you use. If you have any action occur
a number of times in the software, you should put it in a function

For example, when you play any action game, everytime a character gets hit with a bullet, it loses
health. Considering how many times a character gets hit in a game, it will be cumbersome to write the
same code to reduce health again and again. Hence a function will be defined in a game on what needs
to be done when someone gets hit. Everytime someone gets hit, this function will be called.
# function to multiply two numbers

def multiply(x,y):
product = x * y
return product

# Main Program

first = int(input("Enter first number:"))


second = int(input("Enter second number:"))

print("Addition :" , add(first,second))


print("Subtraction :" , subtract(first,second))
print("Multiplication :" , multiply(first , second))
In class exercise
● Chirag, Yugank, and Chris decide to create a python program together. But they are not able to
understand how they are going to divide the whole program among them. Also, they are confused with
the combination process of the program as well. We can divide a big program into smaller parts known
as functions. To explain the same thing to three students, write a python program and create different
functions to add, subtract, and multiply two numbers.

● Sahil is wondering whether we can use the same concept of functions in creating simple and
compound interest calculators. He is trying to create it but is unable to return the answers from the
functions. Help him in doing the same.

● Nidhi is writing a long program. She needs a function that can check whether a given number is a
perfect square or not. To help Nidhi, write a program in python and create a function that checks
whether the given number is a perfect square or not.
Homework question

Nidhi is creating a program in python for her school project. In between the program, she is converting
numerical numbers into word format again and again. Then she realizes that she needs a function that can
convert a number into word format with hyphens between each word. ( for example 57 = five-seven ). To help
Nidhi create a function toWord() that can do the same thing.
Hint: Use for loop and use if-elif-else condition
Sample run:
>> toWord(89)
>> eight-nine
>> toWord(398)
>> three-nine-eight
Thank you

End of session 18

You might also like