0% found this document useful (0 votes)
3 views40 pages

Python Module 2&3

The document discusses various programming paradigms in Python, focusing on imperative programming, which emphasizes sequential execution and explicit control flow. It covers structured, procedural, and object-oriented programming, as well as control structures like conditional statements and loops. Additionally, it highlights the advantages and disadvantages of imperative programming, variable scopes, recursion, and the importance of user-defined functions for code reusability and organization.

Uploaded by

Aditya S
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views40 pages

Python Module 2&3

The document discusses various programming paradigms in Python, focusing on imperative programming, which emphasizes sequential execution and explicit control flow. It covers structured, procedural, and object-oriented programming, as well as control structures like conditional statements and loops. Additionally, it highlights the advantages and disadvantages of imperative programming, variable scopes, recursion, and the importance of user-defined functions for code reusability and organization.

Uploaded by

Aditya S
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit 3-4-5

Python Imperative Programming


Python Programming Paradigms
In Python programming, two popular programming paradigms are available:
➢ Imperative and
➢ Declarative or Functional
Structured Programming
➢ Structured programming is a type of programming in which separate modules are used to develop a
program.
➢ Have several user-defined functions.

The elements supported by structured programming include:

Procedural Programming
➢ Procedural Programming can be defined as a programming model which is derived from
structured programming, based upon the concept of calling procedure.
➢ Procedures, also known as routines, subroutines or functions, simply consist of a series of
computational steps to be carried out.
➢ During a program's execution, any given procedure might be called at any point, including
by other procedures or itself.
Object-Oriented Programming

➢ Object-oriented programming is a type of programming in which data and functions are kept
together in a class.
➢ The concepts included in object-oriented programming are:
Imperative programming: where programs are written as a sequence of explicit, step-
by-step commands that modify the program's state.
This style gives the programmer fine control over execution flow using statements like
variable assignments, loops, and conditional logic.

Python supports imperative programming through variables, assignments, control


structures, functions, and statements executed step by step.

Declarative programming: The tasks defined in the imperative paradigm can sometimes
be solved with a more declarative or functional approach, which focuses on what the
result should be, rather than how to compute it step-by-step.
Key Characteristics of Imperative Programming

1. Sequential Execution – Instructions are executed one after another in a defined


order.
2. State Changes – Variables represent memory locations, and their values can be
changed during program execution.
3. Explicit Control Flow – The programmer controls execution using loops,
conditional statements, and function calls.
4. Assignment Statements – Values are assigned to variables using assignment
operators.
Imperative Programming in Python

➢ Python supports imperative programming through constructs such as variables,


assignment statements, conditional statements (if, if-else), loops (for, while), and
functions.
➢ A Python program typically consists of a series of statements executed sequentially
unless the flow is altered using control structures.

Example of an Imperative Python Program


x=5
y = 10
sum = x + y
print(sum)
Advantages of Imperative Programming

•Imperative programming depends on defined instructions to achieve the final result from the
program. Therefore, code can be easy to understand and straightforward.

•Order of performing operations is completely controlled by developer because of control flow in


program execution.

•Bugs can be easily traced because program is assembled from block of codes to perform smaller
tasks and based on step-by-step commands.

•Memory allocation and manipulation is directly linked in imperative programming. Therefore,


imperative programming has efficient utilization of machine memory.

Disadvantages of Imperative Programming


- Programs may become lengthy and complex for large problems
- Difficult to maintain if not properly structured
- High dependency on program state can lead to errors
Execution Control Structures

❑ Python's execution control structures, also known as control flow statements,


determine the order in which a program's code is executed.
❑ The normal flow of execution in Python is sequential.
❑ However, we can alter this flow by using control flow statements
❑ They are categorized into three primary types:
➢ conditional statements,
➢ loops, and
➢ control flow altering statements (branching/jumping)
❑Control flow statements like these let the programmer make decisions, repeat tasks,
and handle exceptions, making your code more dynamic and powerful.
Conditional Statements

➢ In Python, conditional statements are used to execute certain blocks of code only when
specific conditions are met.
➢ They control the flow of execution in a program

Types of Conditional Statements in Python

1. Python if Conditional Statement


2. Python if-else Conditional Statement
3. Python Nested if Conditional Statement
4. Python if-elif-else Conditional Statement
If Conditional Statement

➢ If statement is the simplest form of a conditional statement.


➢ It executes a block of code if the given condition is true
Syntax
The expression text[::-1] is used to reverse the string

1. Start from the beginning of the string,


2. Go up to the end,
3. Move in reverse order.
if else Statement

➢ In conditional if Statement the additional block of code is merged as else statement


which is performed when if condition is false.

Syntax
nested if-else
Nested if Statement

➢ if statement can also be checked inside other if statement.


➢ This conditional statement is called a nested if statement.
➢ This means inner if condition will only be checked if the outer if condition is
True.

Syntax
if-elif Statement
➢ The if-elif statement is a shortcut for chaining multiple if-else conditions.
➢ While using if-elif statement at the end else block is added which is performed if none of the
above if-elif statement is true.

Syntax
Comparison: if-else vs if-elif-else
Match-Case Statement

➢ match-case statement is Python's version of a switch-case found in other


languages.
➢ It allows us to match a variable's value against a set of patterns.
Python for Loops

➢ Python for loops are used for iterating over sequences like lists, tuples, strings and
ranges.
➢ A for loop allows you to apply the same operation to every item within the loop.
➢ Using a for loop avoids the need to manually manage the index.
➢ A for loop can iterate over any iterable object, such as a dictionary, list or custom
iterator.

Syntax
for Loop with Python range()

The break Statement

The break statement terminates the for loop immediately before it loops through all
the items.
while loop in Python
In Python, the while loop statement repeatedly executes a code block while a particular
condition is true.
With the break statement we can stop the loop even if the while condition is true

With the continue statement we can stop the current iteration, and continue with the next
Infinite while Loop

Here, the value of the condition is always True. Therefore, the body of the loop runs
infinite times until the memory is full.
Hiding redundancy and complexity in Python

Reduce repeated code and hide complex logic using


➢ Functions,
➢ Modules, and
➢ Abstractions

Benefits:
• Easier maintenance
• Improved readability
• Reduced errors
User-defined Functions
➢ User-defined functions (UDF) in Python are reusable blocks of code that a
programmer defines to perform specific tasks.
➢ They help in breaking down large programs into smaller, manageable parts, making
the code easier to understand, maintain, and debug.
➢ Unlike built-in functions provided by a programming language, UDFs allow for
customization and code reusability, improving program structure and efficiency.
➢ A function only runs when it is called.
➢ A function can return data as a result.
➢ A function helps avoiding code repetition.
➢ In Python, a function is defined using the def keyword, followed by a function name
and parentheses.
➢ To call a function, write its name followed by parentheses.
You can call the same function multiple times

Function Names

•A function name must start with a letter or underscore


•A function name can only contain letters, numbers, and underscores
•Function names are case-sensitive (myFunction and myfunction are different)

Valid function names


Types of Function Arguments
➢ Information can be passed into functions as arguments.
➢ Python supports various types of arguments that can be passed at the time
of the function call.

➢ The following example has a function with one argument (name).


➢ When the function is called, we pass along a first name, which is used
inside the function to print the full name:
Number of Arguments
➢ By default, a function must be called with the correct number of arguments.
➢ Meaning that if your function expects 2 arguments, you have to call the
function with 2 arguments, not more, and not less.
Testing the control statements

Testing control statements involves verifying that conditional (if/else, switch) and
looping (for, while, do-while) structures correctly manage program flow, execute
code blocks based on conditions, and handle iterations, using techniques like
condition testing and path coverage to find errors in logic, operators, or loop
boundaries, ensuring the program behaves as expected for various inputs

Key Testing Approaches

•Condition Testing: Focuses on logical conditions (e.g., E1 > E2, ~E1, (E1 & E2) |
(E2 & E3)), checking for incorrect operators or missing parentheses.
•Data Flow Testing: Ensures variables are defined and used correctly within
conditional branches.
•Loop Testing: Tests loop boundaries (initialization, termination),
increment/decrement, and conditions (e.g., zero iterations, one iteration, many
iterations).
•Control Flow Testing/Path Coverage: Develops test cases to execute all
possible execution paths (e.g., all branches in an if-else-if ladder)
What to Look For During Testing
•Correct Boolean Logic: Are conditions evaluating to TRUE/FALSE as
expected?.
•Branch Coverage: Does every if, else, case, break, and continue get tested?.
•Infinite Loops: Do while or for loops always terminate?.
•Correct Output: Does the program produce the right results for valid and invalid
inputs?
Lazy Evaluation

➢ An expression evaluates to a value.


➢ However, we can separate the type of evaluation of expressions into two types:

1. Eager evaluation
2. Lazy evaluation
Eager evaluation refers to those cases when Python evaluates an expression as soon as it
encounters it. Some examples of expressions that are evaluated eagerly:

•Generates a random integer between 1 and 10, including both 1 and 10.
•Each time you call it, it can produce a different integer, e.g., 3, 7, 1, 10, etc
➢ Lazy evaluation refers to cases when Python doesn’t work out the values of an
expression immediately.
➢ Instead, the values are returned at the point when they’re required in the program.
➢ Lazy evaluation can also be referred to as call-by-need.
➢ Saves memory (values are produced one at a time, not all at once)

•gen = my_generator() does NOT run the function yet


— the generator is just created (lazy behavior).
•next(gen) runs the function up to the first yield,
producing the first value.
•Each subsequent next(gen) call continues execution
from where it left off, computing values only when
needed.
Variable Scopes

➢ A variable scope specifies the region where we can access a variable.


➢ In Python, we can declare variables in three different scopes: local scope, global,
and nonlocal 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

➢ A variable created in the main body / defined and declared outside any function of
the Python code is a global variable and belongs to the global scope.
➢ A global variable can be accessed inside or outside of the function.
Python Nonlocal Variables

In Python, the nonlocal keyword is used within nested functions to indicate that
a variable is not local to the inner function, but rather belongs to an enclosing
function’s scope.
Working with Recursion

➢ Recursion is a programming technique where a function calls itself either directly


or indirectly to solve a problem by breaking it into smaller, simpler subproblems.
➢ In Python, recursion is especially useful for problems that can be divided into
identical smaller tasks, such as mathematical calculations, tree traversals or
divide-and-conquer algorithms.
➢ A recursive function is just like any other Python function except that it calls
itself in its body.

Key Rules
Base Case: The stopping condition that prevents infinite recursion.
Recursive Case: The part of the function where it calls itself with modified
parameters.
Factorial of n is defined as n * (n -1) * (n - 2) * ... * 1, for n = 0, factorial is 1.
Assignment:

1. Analyze the difference between recursion and iteration in Python programming with
examples, and identify situations where recursion should be avoided.
2. Analyze parameter passing in Python programming with suitable examples. Explain how
parameters are passed to functions and discuss the behavior of mutable and immutable
objects during parameter passing.

You might also like