Chapter-2
Python Control Structures,
Functions and OOP
Contents
✔ Control Structures and Functions:
✔ Conditional Branching
✔ Looping
✔ Exception Handling
✔ Custom Functions
✔ Python Library Modules
• random,
• Math
• Time
• Os
• shutil
• Sys
• Glob
• re
• statistics
• creating a custom module
Control Structures
• A program should have the ability to skip over certain instructions,
return back to them later, repeat them, or simply pick one of the
multiple instructions to run.
• This is what Python programmers refer to as “flow control” or,
alternately, “control flow.
• Decision-making statements are used in programming languages to
control how programs are executed.
Types of Control Structures
• Control flow refers to the sequence a program will follow during its
execution.
• Conditions, loops, and calling functions significantly influence how a
Python program is controlled.
There are three types of control structures in Python:
Sequential - The default working of a program
Selection - This structure is used for making decisions by checking
conditions and branching
Repetition - This structure is used for looping, i.e., repeatedly executing
a certain piece of a code block.
Sequential control structures
• Sequential statements are a set of statements whose execution process
happens in a sequence.
• The problem with sequential statements is that if the logic has broken in
any one of the lines, then the complete source code execution will
break.
Selection/Decision Control Statements
• The statements used in selection control structures are also referred to as
branching statements or, as their fundamental role is to make decisions,
decision control statements.
• A program can test many conditions using these selection statements, and
depending on whether the given condition is true or not, it can execute
different code blocks.
There can be many forms of decision control structures. Here are some most
commonly used control structures:
• Only if
• if-else
• The nested if
• The complete if-elif-else
Simple if
• If statements in Python are called control flow statements. The selection
statements assist us in running a certain piece of code, but only in certain
circumstances. There is only one condition to test in a basic if statement.
Syntax
if <conditional expression> :
The code block to be executed if the condition is True
• All the statements written indented after the if statement will run if the
condition giver after the if the keyword is True.
• Python uses these types of indentations to identify a code block of a
particular control flow statement.
• The specified control structure will alter the flow of only those indented
statements.
Simple if
Simple if example
If else
• The if-else statement evaluates the condition and will execute the body
of if ,if the test condition is True, but if the condition is False, then the
body of else is executed.
Output:
n is odd
Nested if
• Nested if statements are an if statement inside another if statement.
OUTPUT:
a value is big
If elif else
• The if-elif-else statement is used to conditionally execute a statement
or a block of statements.
Output
x is greater than y
Repetition
• A repetition statement is used to repeat a group(block) of
programming instructions.
In Python, we generally have two loops/repetitive statements:
• for loop
• while loop
for loop
• A for loop is used to iterate over a sequence that is either a list, tuple,
dictionary, or a set.
• We can execute a set of statements once for each item in a list, tuple,
or dictionary.
Output
1st example
1
2
3
2nd example
0
1
2
3
4
While loop
• In Python, while loops are used to execute a block of statements
repeatedly until a given condition is satisfied.
• Then, the expression is checked again and, if it is still true, the body is
executed again.
• This continues until the expression becomes false.
While loop
Output
0 1 2 3 4 End
Exception Handling
• 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.
• 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
Exceptions versus Syntax Errors
• When the interpreter identifies a statement that has an error, syntax
errors occur.
The arrow in the output shows
where the interpreter
encountered a syntactic error.
There was one unclosed
bracket in this case. Close it
and rerun the program
Exceptions versus Syntax Errors
We encountered an exception error after
executing this code. When syntactically valid
Python code produces an error, this is the kind
of error that arises. The output's last line
specified the name of the exception error code
encountered. Instead of displaying just
"exception error", Python displays information
about the sort of exception error that occurred.
It was a NameError in this situation. Python
includes several built-in exceptions. However,
Python offers the facility to construct custom
exceptions.
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.
Different types of exceptions in python:
• 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.
Advantages of Exception Handling:
• Improved program reliability: By handling exceptions properly, you can
prevent your program from crashing or producing incorrect results due to
unexpected errors or input.
• Simplified error handling: Exception handling allows you to separate error
handling code from the main program logic, making it easier to read and
maintain your code.
• Cleaner code: With exception handling, you can avoid using complex
conditional statements to check for errors, leading to cleaner and more
readable code.
• Easier debugging: When an exception is raised, the Python interpreter
prints a traceback that shows the exact location where the exception
occurred, making it easier to debug your code.
Disadvantages of Exception Handling:
• Performance overhead: Exception handling can be slower than using
conditional statements to check for errors, as the interpreter has to
perform additional work to catch and handle the exception.
• Increased code complexity: Exception handling can make your code
more complex, especially if you have to handle multiple types of
exceptions or implement complex error handling logic.
• Possible security risks: Improperly handled exceptions can
potentially reveal sensitive information or create security
vulnerabilities in your code, so it’s important to handle exceptions
carefully and avoid exposing too much information about your
program.
Python Exception Hierarchy
Exceptions
Control flow
Try & Except
There is an exception so only except clause will run.
Finally
Python provides a keyword finally, which is always executed after the try and except blocks. The final block always
executes after the normal termination of the try block or after the try block terminates due to some exceptions
Custom Functions in Python
• All the functions that are written by any of us come under the category of
user-defined functions. Below are the steps for writing user-defined
functions in Python.
• In Python, a def keyword is used to declare user-defined functions.
• An indented block of statements follows the function name and arguments
which contains the body of the function.
Syntax
def function_name():
statements…..
Python Parameterized Function
• The function may take arguments(s) also called parameters as input
within the opening and closing parentheses, just after the function
name followed by a colon
Syntax
def function_name(argument1, argument2, ...):
statements….
Python 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.
Python 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.
Python Variable Length Arguments
• We can have both normal and keyword variable numbers of
arguments.
• The special syntax *args in function definitions in Python is used to
pass a variable number of arguments to a function. It is used to pass a
non-keyworded, variable-length argument list.
• The special syntax **kwargs in function definitions in Python is used
to pass a keyworded, variable-length argument list. We use the name
kwargs with the double star. The reason is that the double star allows
us to pass through keyword arguments (and any number of them).
Example
Disadvantages of Custom Functions
• Performance overhead: User-defined functions may introduce a slight
performance overhead compared to inbuilt functions, as they add an
extra layer of function calls.
• Potential for errors: Errors in logic or implementation can lead to
bugs and unexpected behavior.
• Maintenance: Custom functions require maintenance and
documentation, especially in larger projects.
• Redundancy: If not designed properly, user-defined functions can
lead to redundant or duplicated code.
Python Library Modules
• Libraries in Python are collections of modules and packages that
provide pre-written code to perform various tasks. They help simplify
coding by providing reusable functions and classes for specific
functionalities, such as data analysis, machine learning, web
development, and more.
• Python has a vast number of libraries, with over 300,000 packages
available in the Python Package Index (PyPI). This number continues
to grow as the Python community develops new libraries for various
applications.
Python Library Modules
• A Python module is a file containing Python definitions and
statements. A module can define functions, classes, and variables. A
module can also include runnable code.
• Grouping related code into a module makes the code easier to
understand and use. It also makes the code logically organized.
Random Module
• Python Random module generates random numbers in Python. These
are pseudo-random numbers means they are not truly random.
• This module can be used to perform random actions such as
generating random numbers, printing random a value for a list or
string, etc. It is an in-built function in Python.
Examples
random vs Randint in Python
• random(): This function from the random module returns a random
floating-point number between 0.0 and 1.0. It’s used when you need
a uniform distribution of floating-point values.
• randint(a, b): This function returns a random integer between the
specified integers a and b (inclusive). It’s useful when you need a
random integer within a specific range.
Functions in random module:
randint() random() uniform() randrange() choice() sample()
shuffle()
math module
• Math Module is an in-built Python library made to simplify
mathematical tasks in Python.
• It consists of various mathematical constants and functions that can
be used after importing the math module.
Constants in Math Module
The Python math module provides various values of various constants
like pi, and tau. We can easily write their values with these constants.
The constants provided by the math module are :
• Euler’s Number
• Pi
• Tau
• Infinity
• Not a Number (NaN)
Constants in Math Module
Euler’s Number
• The math.e constant returns the Euler’s number: 2.71828182846.\
Syntax:
math.e
Pi
Numeric Functions in Math Module
• Finding the ceiling and the floor value
• Finding sine, cosine, and tangent
Time Module
What is epoch?
The epoch is the point where the time starts and is platform-dependent. On
Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00
(UTC), and leap seconds are not counted towards the time in seconds since
the epoch. To check what the epoch is on a given platform we can use
[Link](0).
Note
The time before the epoch can still be represented in seconds but it will be
negative. For example, 31 December 1969 will be represented as -86400
seconds.
Time Module
Getting current time in seconds since epoch
[Link]() methods return the current time in seconds since epoch. It
returns a floating-point number.
Getting time string from seconds
[Link]() function returns a 24 character time string but takes seconds
as argument and computes time till mentioned seconds. If no argument is
passed, time is calculated till the present.
Time Module
Delaying Execution of Programs
Execution can be delayed using [Link]() method. This method is
used to halt the program execution for the time specified in the
arguments.
os module
• The OS module in Python provides functions for interacting with the operating
system. OS comes under Python’s standard utility modules. This module provides
a portable way of using operating system-dependent functionality.
• The *os* and *[Link]* modules include many functions to interact with the file
system.
Python-OS-Module Functions
• Handling the Current Working Directory
• Creating a Directory
• Listing out Files and Directories with Python
• Deleting Directory or Files using Python
os module
Getting the Current working directory
• To get the location of the current working directory [Link]() is used.
Changing the Current working directory
To change the current working directory(CWD) [Link]() method is used. This method changes the CWD to a
specified path. It only takes a single argument as a new directory path.
The code checks and displays the current working directory (CWD) twice: before and after changing the
directory up one level using [Link]('../').
Shutil Module
• Shutil module offers high-level operation on a file like a copy, create, and remote
operation on the file. It comes under Python’s standard utility modules.
• This module helps in automating the process of copying and removal of files and
directories.
Copying Files to another directory
[Link]() method in Python is used to copy the content of the source file
to the destination file or directory. It also preserves the file’s permission mode
but other metadata of the file like the file’s creation and modification times is
not preserved.
The source must represent a file but the destination can be a file or a
directory. If the destination is a directory then the file will be copied into the
destination using the base filename from the source. Also, the destination
must be writable. If the destination is a file and already exists then it will be
replaced with the source file otherwise a new file will be created.
Shutil Module
Syntax
[Link](source, destination, *, follow_symlinks = True)
Parameter:
source: A string representing the path of the source file.
destination: A string representing the path of the destination file or directory.
follow_symlinks (optional) : The default value of this parameter is True. If it is
False and source represents a symbolic link then destination will be created
as a symbolic link.
Return Type: This method returns a string which represents the path of newly
created file.
Shutil Module
Sys Module
• The sys module in Python provides various functions and variables
that are used to manipulate different parts of the Python runtime
environment. It allows operating on the interpreter as it provides
access to the variables and functions that interact strongly with the
interpreter.
Input and Output using Python Sys
The sys modules provide variables for better control over input or output. We can even redirect
the input and output to other devices. This can be done using three variables –
• stdin
• stdout
• Stderr
stdin: It can be used to get input from the command line directly. It is used for
standard input. It internally calls the input() method. It, also, automatically adds ‘\n’
after each sentence.
stdout: A built-in file object that is analogous to the interpreter’s standard output
stream in Python. stdout is used to display output directly to the screen console.
Output can be of any form, it can be output from a print statement, an expression
statement, and even a prompt direct for input. By default, streams are in text mode.
In fact, wherever a print function is called within the code, it is first written to
[Link] and then finally on to the screen.
stderr: Whenever an exception occurs in Python it is written to [Link].
Command Line Arguments
• Command-line arguments are those which are passed during the calling of the
program along with the calling statement. To achieve this using the sys module,
the sys module provides a variable called [Link]. It’s main purpose are:
• It is a list of command-line arguments.
• len([Link]) provides the number of command-line arguments.
• [Link][0] is the name of the current Python script.
Statistics module
Regular Expression (RegEx) in Python
• A Regular Expression or RegEx is a special sequence of characters that
uses a search pattern to find a string or set of strings.
• It can detect the presence or absence of a text by matching it with a
particular pattern and also can split a pattern into one or more
sub-patterns.
Creating a Custom Python Module
• To create a custom module in Python, all you have to do is create a
new Python file. Let’s see this with the help of an example. Create a
Python file named [Link] with the three functions:
print_text(), find_log(), and find_exp(). Since a module is just another
Python file, you can define anything inside a Python module, like
classes, methods, data structures and more.
Creating a Custom Python Module
To use a custom Python module, your Python interpreter should be
able to access the Python file containing your custom module. There
are three locations where you can save your Python file containing your
custom module so that it is accessible by the Python interpreter.
• Within the same directory as the Python file accessing the modules
• Within another directory which has to be added in the path of your
Python interpreter
• Within one of the default paths for your Python interpreter.
Importing Custom Modules within the Same
Directory
• Create another file called [Link] within the same directory where you
created your [Link] file.
• To import a custom module, you can use the import statement followed by
your module name. This syntax is similar to importing default or installed
Python modules. The script below imports the newmodule module which is
created by the [Link] file stored in the same directory as the
[Link] file. It’s important to mention that to import a module, you only
have to specify the module name, without the “.py” extension.
• Next, the script calls the three functions defined inside our newmodule
module. One way to call a function from another module is to specify the
module name, followed by the dot “.” operator, and the function name
Importing Custom Modules within the Same
Directory
Importing Custom Modules from a Different
Path
Let’s save the above file in a different direct. We’re going to use “C:\Datasets”
here.
Now, if you want to import the newmodule2 module in your Python
application, you will have to append the path of the module to the list of paths
accessible to your Python interpreter. The [Link] list contains the list of
these paths.