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: Function is defined using the def keyword:
Calling a Function in Python : Function needs to be called if it has to be executed.
It is called by using the name of the functions followed by parenthesis containing
parameters of that particular function. Example for calling def function Python.
# A simple Python function
def fun():
print("Welcome to GFG")
fun()
Types of Functions in Python:
● Built-in library function: These are Standard functions in Python that are
available to use. Ex: len(), print()
● User-defined function: We can create our own functions based on our
requirements.
● Module defined functions: A module is a file containing definition of
functions, classes, variables, constants or any other Python object. Contents of this
file can be made available to any other program. Using the import keyword.
● Ex : import math print ("Square root of 100:", math.sqrt(100))
Types of Functions in Python based on Return type
● Void 🡪 No return statements
● Non-void 🡪 with return statements
def add2no(): def add2no():
a,b=3,6 a,b=3,6
print(f’sum is {a+b}’) print(f’sum is {a+b}’)
return a+b
add2no() answer = add2no()
Parameters: A parameter is the variable listed inside the parentheses in
the function definition or function header.
Arguments: An argument is the value that is sent to the function when it
is called.
Arbitrary Arguments, *args
If the number of arguments is not known then 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 f1(*kids):
print("The youngest child is " + kids[2])
f1("Ila", "Tom", "Linu")
output:The youngest child is Linu
Keyword Arguments : key = value This way the order of the arguments does not
matter.
def f1(a, c, b):
print("The youngest child is " + a)
f1(b = "ila", c = "Tom", a = "Linu")
Types of arguments
There may be several types of arguments which can be passed at the
time of function calling.
1. Positional arguments 2.Keyword arguments 3.Default arguments
1. Positional arguments
● Arguments are passed in the order of parameters. The order defined in
the order function declaration.
● Order of values cannot be changed to avoid the unexpected output.
Syntax :- FunctionName(value1,value2,value3,….)
2.Keyword arguments
● Parameter Names are used to pass the argument during the function
call.
● Order of parameter Names can be changed to pass the argument(or
values).
Syntax : – FunctionName(paramName=value,…)
3.Default arguments
● Default values indicate that the function argument will take that value if no
argument value is passed during the function call.
● The default value is assigned by using the assignment(=) operator of the form
keywordname=value.
Example 1
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
#Positional Arguments
nameAge("vasu", 23)
#Keywords Arguments
nameAge(name="Prince", age=20)
#or
nameAge(age=20, name="Prince")
Example 2
def simple_interest(p,t,r):
return (p*t*r)/100
p = float(input("Enter the principle amount? "))
r = float(input("Enter the rate of interest? "))
t = float(input("Enter the time in years? "))
print("Simple Interest: ",simple_interest(p,r,t))
Example 3
def printme(name,age=22):
print("My name is",name,"and age is",age)
printme(name = "john")
#the variable age is not passed into the function however
th e default value of age is considered in the function
printme(age = 10,name="David")
#the value of age is overwritten here, 10 will be pr inted as
age
Scope of Variable
• Scope of variable means the part of the program where the variable will be visible.
It means where we can use this variable.
• We can say that scope is the collection of variables and their values.
• Scope can of two types -
• Global (module) – All those names which are assigned at top level in module or
directly assigned in interpreter.
• Local (function) – Those variables which are assigned within a loop of function.
Using main() as a Function • Main function is not necessary in python.
Flow of execution in a function call:
● The execution of any program starts from the very first line and this
execution goes line by line.
● One statement is executed at a time.
● Function doesn’t change the flow of any program.
● Statements of function don't start executing until it is called.
● When function is called then the control is jumped into the body of
function.
● Then all the statements of the function get executed from top to bottom
one by one.
● And again the control returns to the place where it was called.
● And in this sequence the python program gets executed.
1. def power(b, p):
2. y = b ** p
3. return y
4.
5. def calcSquare(x):
6. a = power(x, 2)
7. return a
8.
9. n = 5
10. result = calcSquare(n)
11. print(result)
The flow of execution for the above program is as follows :
1 → 5 → 9 → 10 → 5 → 6 → 1 → 2 → 3 → 6 → 7 → 10 → 11
random Module
When we require numbers which are not known earlier e.g. captcha or any type of
serial numbers then we use random numbers from random module.
Functions in random -
1. randrange (): This method always returns any integer between given lower and upper
limit to this method. the default lower value is zero (0) and upper value is one(1).
2. random (): This generates floating values between 0 and 1. it does not require any
argument.
3. randint (): This method takes 2 parameters a,b in which first one is lower and second
is upper limit. This may return any number between these two numbers including
both limits. This method is very useful for guessing applications.
4. uniform (): This method returns any floating-point number between two given
numbers.
Scope refers to part(s) of program within which a name is legal and accessible.
When we access a variable from within a program or function, Python follows name
resolution rule, also known as LEGB rule. When Python encounters a name (variable
or function), it first searches the local scope (L), then the enclosing scope (E), then the
global scope (G), and finally the built-in scope (B).
Difference between Local and Global variable:
Local scope — Variables defined within a specific block of code, such as a function or a
loop, have local scope. They are only accessible within the block in which they are
defined.
Global scope — Variables defined outside of any specific block of code, typically at the
top level of a program or module, have global scope. They are accessible from anywhere
within the program, including inside functions.
To access a global variable inside a function, even if the function has a variable with the
same name, we can use the global keyword to declare that we want to use the global
variable instead of creating a new local variable. The syntax is
global<variable name>
For example:
def state1():
global tigers
tigers = 15
print(tigers)
tigers = 95
print(tigers)
state1()
print(tigers)
In the above example, tigers is a global variable. To use it inside the function state1 we
have used global keyword to declare that we want to use the global variable instead of
creating a new local variable.
Note Mutability/Immutability of Arguments/Parameters and function call notes were given in class.
—---------------------------------------------------X—----------------------------X—------------