UNIT-II Functions: Functions, Built-in Functions, User Defined Functions, recursive functions, Scope of a Variable
Python and OOP: Defining Classes, Defining and calling functions passing arguments, Inheritance, polymorphism, Modules –
date time, math, Packages.
Exception Handling- Exception in python, Types of Exception, User-defined Exceptions.
Python Functions :Python Functions is a block of statements that return the specific task. The idea is to put
some commonly or repeatedly done tasks together and make a function so that instead of writing the same code
again and again for different inputs, we can do the function calls to reuse code contained in it over and over
again.
Some Benefits of Using Functions
Increase Code Readability
Increase Code Reusability
Python Function Declaration
The syntax to declare a function is:
Syntax of Python Function Declaration
Types of Functions in Python
Below are the different types of functions in Python:
Built-in library function: These are Standard functions in Python that are available to use.
User-defined function: We can create our own functions based on our requirements.
Creating a Function in Python
:We can define a function in Python, using the def keyword. We can add any type of functionalities and properties
to it as we require. By the following example, we can understand how to write a function in Python. In this way we
can create Python function definition by using def keyword.
# A simple Python function
def fun():
print("Welcome to GFG")
Built-in Functions in Python
Python has many built-in functions that are already defined and ready to use. These functions perform common
operations that are frequently used in programming. Here are some of the most commonly used built-in functions in
Python:
Function Name Description
print() Outputs a message to the console or standard output device.
input() Takes user input from the console or standard input device.
len() Returns the length of an object, such as a string, list, or tuple.
type() Returns the data type of an object.
range() Creates a sequence of numbers between the specified start and end points.
int() Converts an object to an integer data type.
float() Converts an object to a float data type.
str() Converts an object to a string data type.
bool() Converts an object to a boolean data type.
max() Returns the maximum value in a list or sequence.
min() Returns the minimum value in a list or sequence.
sum() Calculates the sum of a list or sequence.
sorted() Sorts a list or sequence in ascending order.
abs() Returns the absolute value of a number.
User-defined Functions in Python
User-defined functions are functions that the programmer creates to perform a specific task or set of tasks. Defining a
function allows you to reuse code and makes your code more modular and easier to read.
In Python, you can define a function using the def keyword, followed by the function name and any parameters it
requires in parentheses. The code block that makes up the function is indented beneath the def statement.
Here’s an example of a simple user-defined function in Python:
def greet(name):
print(f"Hello, {name}!")
In this example, the greet() function takes one parameter, name, to personalize the greeting. When the function is called, it will
print out a message to the console that greets the specified name.
To call a user-defined function, type its name followed by any required parameters in parentheses. Here’s an example:
greet("Alice")
This would output the following message to the screen:
Hello, Alice!
Copy code
User-defined functions can be as simple or as complex as you need them to be. They can include any number of statements,
control structures, and other functions and can return one or more values if necessary. When writing a function, it’s important to
choose a descriptive name that accurately reflects what the function does and to use clear, concise code that’s easy to read and
understand.
Recursive Functions in Python
Recursive functions in Python call themselves to perform a task repeatedly until a certain condition is met. Recursive functions can
be used to solve problems that can be broken down into smaller sub-problems that can be solved using the same approach.
Here’s an example of a simple recursive function in Python that calculates the factorial of a given number:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
In this example, the factorial() function takes an integer n as its parameter and returns the factorial of that number. The function
first checks if n equals 1, which is the base case. If n is not equal to 1, the function calls itself with n-1 as the argument and
multiplies the result by n. This process continues recursively until the base case is reached.
To call the factorial() function, pass an integer value as its argument. Here’s an example:
print(factorial(5))
Copy code
This would output the following result:
120
Recursive functions can be slower and use more memory than iterative solutions, so they may not be the best choice for large
problems. Additionally, recursive functions can be more difficult to debug and understand than iterative solutions, so using them
judiciously and only when they provide a clear advantage over other approaches is important.
Defining and calling functions passing arguments:
Calling a Function in Python
:After creating a function in Python we can call it by using the name of the functions Python followed by parenthesis
containing parameters of that particular function. Below is the example for calling def function Python.
1
# A simple Python function
def fun():
3
print("Welcome to GFG")
6
# Driver code to call a function
7
fun()
Output:
Welcome to GFG
Python Function with Parameters
If you have experience in C/C++ or Java then you must be thinking about the return type of the function and data
type of arguments. That is possible in Python as well (specifically for Python 3.5 and above).
Python Function Syntax with Parameters
def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression
The following example uses arguments and parameters that you will learn later in this article so you can come back
to it again if not understood.
def add(num1: int, num2: int) -> int:
"""Add two numbers"""
num3 = num1 + num2
return num3
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
Output:
The addition of 5 and 15 results 20.
scope of a variable :The scope of a variable alludes to where it can be accessed in a program. A variable's scope
depends on where it is announced and is confined to the piece in which it was defined. Program engineers understand
the contrast between local variables, limited to a particular block, and global variables, which can be accessed
throughout the complete program
Python Local variable:Local variables are those that are initialized within a function and are unique to that function. It cannot b
accessed outside of the function. Let’s look at how to make a local variable
def f():
# local variable
s = "I love Geeksforgeeks"
print(s)
# Driver code
f()
Output:I love Geeksforgeeks
If we will try to use this local variable outside the function then let’s see what will happen.
def f():
# local variable
s = "I love Geeksforgeeks"
print("Inside Function:", s)
# Driver code
f()
print(s)
NameError: name 's' is not defined
Python Global variables
Global variables are the ones that are defined and declared outside any function and are not specified to any
function. They can be used by any part of the program.
Example:
Python3
# This function uses global variable s
def f():
print(s)
# Global scope
s = "I love Geeksforgeeks"
f()
Output:
I love Geeksforgeeks
Python Classes : A class in Python is a user-defined template for creating objects. It bundles data and
functions together, making it easier to manage and use them. When we create a new class, we define a new type of
object. We can then create multiple instances of this object type.
Classes are created using class keyword. Attributes are variables defined inside the class and represent the
properties of the class. Attributes can be accessed using the dot . operator (e.g., MyClass.my_attribute).
A class is created with the keyword class and then writing the classname. The simplest form of class definition looks like
this:
class ClassName:
<statement-1>
.
.
<statement-N>
Class definitions, like function definitions (def statements) must be executed before they have any effect. (You
could conceivably place a class definition in a branch of an if statement, or inside a function.)
Example: class Student:
def init(self):
[Link]="hari" [Link]="CSE"
def display(self): print
[Link] print
[Link]
For example, If we „Student‟ class, we can write code in the class that specifies the attributes and actions performed by
[Link] that the keyword class is used to declare a class. After this, we should write the class name. So,
„Student‟ is our class name. Generally, a class name should start with a capital letter, hence „S‟ is a capital in„Student‟
,Inheritance:
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code reusability to the program
because we can use an existing class to create a new class instead of creating it from scratch.
In inheritance, the child class acquires the properties and can access all the data members and functions defined in the
parent class. A child class can also provide its specific implementation to the functions of the parent class. In this
section of the tutorial, we will discuss inheritance in detail.
In python, a derived class can inherit base class by just mentioning the base in the bracket after the derived class name.
Consider the following syntax to inherit a base class into the derived class.
Syntax
1. class derived-class(base class):
2. <class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the following syntax
Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
Example 1
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
[Link]()
[Link]()
Output:
dog barking
Animal Speaking
Polymorphism:
Polymorphism is a foundational concept in programming that allows entities like functions, methods or operators to behave
differently based on the type of data they are handling. Derived from Greek, the term literally means “many forms”.
Polymorphism refers to having multiple forms. Polymorphism is a programming term that refers to the use of the same function
name, but with different signatures, for multiple types.
Example of in-built polymorphic functions:
# Python program for demonstrating the in-built poly-morphic functions
# len() function is used for a string
print (len("Javatpoint"))
# len() function is used for a list
print (len([110, 210, 130, 321]))
Output:
10
4
Examples of user-defined polymorphic functions:
# here, is a simple Python function
# for demonstrating the Polymorphism
def add(p, q, r = 0):
return p + q + r
# Driver code
print (add(6, 23))
print (add(22, 31, 544))
Output:
29
597
date and time Module:
In Python, date and time are not data types of their own, but a module named DateTime in Python can be
imported to work with the date as well as time. Python Datetime module comes built into Python, so there is no
need to install it externally.
Python Datetime module supplies classes to work with date and time. These classes provide several functions to
deal with dates, times, and time intervals. Date and DateTime are an object in Python, so when you manipulate them,
you are manipulating objects and not strings or timestamps.
The DateTime module is categorized into 6 main classes –
date – An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in
effect. Its attributes are year, month, and day. you can refer to – Python DateTime – Date Class
time – An idealized time, independent of any particular day, assuming that every day has exactly 24*60*60
seconds. Its attributes are hour, minute, second, microsecond, and tzinfo. You can refer to – Python DateTime –
Time Class
date-time – It is a combination of date and time along with the attributes year, month, day, hour, minute, second,
microsecond, and tzinfo. You can refer to – Python DateTime – DateTime Class
timedelta – A duration expressing the difference between two date, time, or datetime instances to microsecond
resolution. You can refer to – Python DateTime – Timedelta Class
tzinfo – It provides time zone information objects. You can refer to – Python – [Link]()
timezone – A class that implements the tzinfo abstract base class as a fixed offset from the UTC (New in version
3.2).
Python Date Class
The date class is used to instantiate date objects in Python. When an object of this class is instantiated, it represents
a date in the format YYYY-MM-DD. The constructor of this class needs three mandatory arguments year, month, and
date.
Python Date class Syntax
class [Link](year, month, day)
The arguments must be in the following range –
MINYEAR <= year <= MAXYEAR
1 <= month <= 12
1 <= day <= number of days in the given month and year
Python math Module:
Python has a built-in math module. It is a standard module, so we do not need to install it separately. We only must
import it into the program we want to use. We can import the module, like any other module of Python, using import
math to implement the functions to perform mathematical operations.
Since the source code of this module is in the C language, it provides access to the functionalities of the underlying C
library. Here we have given some basic examples of the Math module in Python. The examples are written below -
# This program will show the calculation of square root using the math module
# importing the math module
import math
print([Link]( 9 ))
output: 3.0
This Python module does not accept complex data types. The more complicated equivalent is the cmath module.
We can, for example, calculate all trigonometric ratios for any given angle using the built-in functions in the math
module. We must provide angles in radians to these trigonometric functions (sin, cos, tan, etc.). However, we are
accustomed to measuring angles in terms of degrees. The math module provides two methods to convert angles from
radians to degrees and vice versa.
Ex:Here we give an example of a math module in Python for calculating the factorial of a number. The code is given
below -
import math
n=int(input())
print([Link](n))
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -
5
Exception Handling- Exception in python, Types of Exception, User-defined Exceptions:
When a Python program meets an error, it stops the execution of the rest of the program. An error in Python might be
either an error in the syntax of an expression or a Python exception. We will see what an exception is. Also, we will see
the difference between a syntax error and an exception in this tutorial. Following that, we will learn about trying and
except blocks and how to raise exceptions and make assertions. After that, we will see the Python exceptions list.
What is an Exception?
An exception in Python is an incident that happens while executing a program that causes the regular course of the
program's commands to be disrupted. When a Python code comes across a condition it can't handle, it raises an
exception. An object in Python that describes an error is called an exception.
When a Python code throws an exception, it has two options: handle the exception immediately or stop and quit.
In Python, we catch exceptions and handle them using try and except code blocks. The try clause contains the code
that can raise an exception, while the except clause contains the code lines that handle the exception. Let's see if we
can access the index from the array, which is more than the array's length, and handle the resulting exception.
# Python code to catch an exception and handle it using try and except code blocks
a = ["Python", "Exceptions", "try and except"]
try:
#looping through the elements of the array a, choosing a range that goes beyond the length of the array
for i in range( 4 ):
print( "The index and element from the array is", i, a[i] )
#if an error occurs in the try block, then except block will be executed by the Python interpreter
except:
print ("Index out of range")
Output:
The index and element from the array is 0 Python
The index and element from the array is 1 Exceptions
The index and element from the array is 2 try and except
Index out of range
If a condition does not meet our criteria but is correct according to the Python interpreter, we can intentionally raise an
exception using the raise keyword. We can use a customized exception in conjunction with the statement.
If we wish to use raise to generate an exception when a given condition happens, we may do so as follows:
Code
#Python code to show how to raise an exception in Python
num = [3, 4, 5, 7]
if len(num) > 3:
raise Exception( f"Length of the given list must be less than or equal to 3 but is {len(num)}" )
Output:
1num = [3, 4, 5, 7]
if len(num) > 3:
----> 3 raise Exception( f"Length of the given list must be less than or equal to 3 but is {len(num)}" )
Exception: Length of the given list must be less than or equal to 3 but is 4
Different types of exceptions in python:
In Python, there are several built-in Python exceptions that can be raised when an error occurs during the execution
of a program. Here are some of the most common types of exceptions in Python:
SyntaxError: This exception is raised when the interpreter encounters a syntax error in the code, such as a
misspelled keyword, a missing colon, or an unbalanced parenthesis.
TypeError: This exception is raised when an operation or function is applied to an object of the wrong type, such
as adding a string to an integer.
NameError: This exception is raised when a variable or function name is not found in the current scope.
IndexError: This exception is raised when an index is out of range for a list, tuple, or other sequence types.
KeyError: This exception is raised when a key is not found in a dictionary.
ValueError: This exception is raised when a function or method is called with an invalid argument or input, such
as trying to convert a string to an integer when the string does not represent a valid integer.
AttributeError: This exception is raised when an attribute or method is not found on an object, such as trying to
access a non-existent attribute of a class instance.
IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails due to an
input/output error.
ZeroDivisionError: This exception is raised when an attempt is made to divide a number by zero.
ImportError: This exception is raised when an import statement fails to find or load a module.
These are just a few examples of the many types of exceptions that can occur in Python.
User-Defined Exception in Python
Exceptions need to be derived from the Exception class, either directly or indirectly. Although not mandatory, most of
the exceptions are named as names that end in “Error” similar to the naming of the standard exceptions in
python. For example,
# A python program to create user-defined exception
# class MyError is derived from super class Exception
class MyError(Exception):
# Constructor or Initializer
def __init__(self, value):
[Link] = value
# __str__ is to print() the value
def __str__(self):
return(repr([Link]))
try:
raise(MyError(3*2))
# Value of Exception is stored in error
except MyError as error:
print('A New Exception occurred: ', [Link])
Output
A New Exception occurred: 6