Function-3 (1) Bghvynchbvhhhhhvvvbb. Bbb. V
Function-3 (1) Bghvynchbvhhhhhvvvbb. Bbb. V
Function-3 (1) Bghvynchbvhhhhhvvvbb. Bbb. V
FUCNTION
BUILT-IN MODULE
User Defined Functions - We can define our own functions while writing the program. A function defined to
achieve some task as per the programmer's requirement is called a user defined function.
Creating User Defined Function - A function definition begins with def (short for define). The syntax for
creating a user defined function is as follows:
The items enclosed in "( )" after function name are called parameters and they are optional.
Function header always ends with a colon (:).
Function name should be unique. Rules for naming identifiers also applies for function naming.
The statements outside the function indentation are not considered as part of the function.
An indented block of statements follows the function name and arguments which contains the body of the
function.
print("Welcome to Python")
Calling a Function in Python - After creating a function in Python we can call it by using the name of the
function with parenthesis.
Eg-1:
def fun():
print("Welcome to Python")
fun() #calling a function
Output:
Enter first number: 5
Enter second number: 6
The sum of 5 and 6 is 11
Parameter/ Parameterized Function - A parameter is the variable listed inside the parentheses in the
function definition.
Arguments - An argument is a value passed to the function during the function call which is received in
corresponding parameter defined in function header.
Syntax:
def function_name(parameter1, parameter2, ...):
statements
function_name(argument1, agrument2, …)
Output:
even
odd
Eg-2: Write a program using a user defined function that displays sum of first n natural numbers, where n is
passed as an argument.
def sumSquare(n):
sum = 0
for i in range(1,n):
sum = sum + i
print("The sum of first",n,"natural numbers is: ",sum)
num = int(input("Enter the value for n: "))
sumSquares(num)
Eg-3: Write a program using a user defined function calcFact() to calculate and display the factorial of a number
num passed as an argument.
def calcFact(num):
fact = 1
for i in range(num,0,-1):
fact = fact * i
print("Factorial of",num,"is",fact)
num = int(input("Enter the number: "))
calcFact(num)
Output:
Enter the number: 5
Factorial of 5 is 120
range() - returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and
stops before a specified number.
Syntax: range(start, stop, step)
Eg: Create a sequence of numbers from 3 to 19, but increment by 2 instead of 1:
x = range(3, 20, 2)
for n in x:
print(n)
output:
3
5
7
9
11
13
15
17
19
String as Parameters – We can pass string values as an argument. The arguments passed are of numeric type
only.
Eg-4: Write a program using a user defined function that accepts the first name and lastname as
arguments, concatenate them to get full name.
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Maruti", "Suzuki")
Or
def my_function(fname, lname):
print(fname + " " + lname)
fname = input("Enter first name: ")
lname = input("Enter last name: ")
my_function(fname,lname)
Default Parameter - A default value is a value that is pre-decided and assigned to the parameter. If we call
the function without argument, it uses the default value.
Eg: def my_function(country = "India"):
print("I am from " + country)
my_function( )
Passing a List as an Argument - We can send any data types of argument to a function (string, number,
list, dictionary etc.), and it will be treated as the same data type inside the function.
Eg: def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Or
myMean(myList)
Functions Returning Value – A function may or may not return a value when called. The return statement
returns the values from the function.
Eg: def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
Or
Eg: Write a program using user defined function calcPow() that accepts base and exponent as arguments
and returns the value Baseexponent where Base and exponent are integers.
result = 1
return result
Output:
Keyword Arguments - Whenever we pass the arguments(or value) by their parameter names at the
time of calling the function, in which if we change the position of arguments then there will be no
change in the output.
On using keyword arguments we will get the correct output because the order of argument doesn’t
matter provided the logic of our code is correct.
Eg:
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
nameAge(name="Prince", age=20)
nameAge(age=20, name="Prince")
Output:
Hi, I am Prince
My age is 20
Hi, I am Prince
My age is 20
Positional-Only Arguments - whenever we pass the arguments in the order, we have defined function
parameters in which if we change the argument position then we may get the unexpected output. We
should use positional Arguments whenever we know the order of argument to be passed.
Eg-1:
. def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
nameAge("Prince", 20) #You will get correct output because argument is given in order
nameAge(20, "Prince") #You will get incorrect output because argument is not in order
output:
Hi, I am Prince
My age is 20
Hi, I am 20
My age is Prince
Eg-2:
def minus(a, b):
return a - b
a, b = 20, 10
result1 = minus(a, b)
print("Used Positional arguments:", result1)
# we will get incorrect output in result-2, because expected was (a-b) but we will be getting
(b-a) because of swapped position of value a and b
result2 = minus(b, a)
print("Used Positional arguments:", result2)
Output:
Used Positional arguments: 10
Used Positional arguments: -10
Scope of a variable - A variable is only available from inside the region it is created. This is
called scope. The location where we can find a variable and also access it if required is called
the scope of a variable. There are two types of scope in python –
Local Scope - Local variables are those that are initialized within a function and are unique to that
function. It cannot be accessed outside of the function.
Global Scope - Defined and declared outside any function and are not specified to any function.
They can be used by any part of the program.
Eg: x = 300
def myfunc():
print(x)
myfunc()
print(x)
Output: 300
Eg: The function will print the local x, and then the code will print the global x:
x = 300
def myfunc():
x = 200
print(x)
myfunc()
print(x)
output: 200
300
Eg: The global keyword makes the variable global. If you use the global keyword, the variable
belongs to the global scope.
def myfunc():
global x
x = 300
myfunc()
print(x)
Flow of execution - refers to the order in which statements, functions, and modules are executed in a
Python program. This flow impact the performance of code, and understanding. It can help us identify
and fix issues.
Program without functions - A basic python program is executed in a sequential manner that means
line by line.
Program with functions - When a python program is written through function, then the control is not
going to be executed line by line(sequentially).
Eg: if we write the same program in Python through function then the structure will be like this
1 -> Line 4 to Line 5
2 -> Line 6 to Line 1
3 -> Line 2 to Line 3
4 -> Line 6 to Line 7