module 3-6
module 3-6
Python offers various conditional statements to control the flow of a program based on
conditions. The main constructs for selection are if, if-else, and elif statements.
The if statement allows you to execute a block of code only if a particular condition is true.
Syntax:
if condition:
# Code to execute if condition is true
Example:
The if-else statement adds an alternative path, executing one block of code if the condition
is true, and another if the condition is false.
Syntax:
if condition:
# Code if condition is true
else:
# Code if condition is false
Example:
if x > 15:
else:
The elif (else if) statement allows you to check multiple conditions sequentially. As soon as
one condition is true, the corresponding block of code executes, and the remaining conditions
are skipped.
Syntax:
if condition1:
# Code if condition1 is true
elif condition2:
# Code if condition2 is true
else:
# Code if neither condition1 nor condition2 is true
Example:
The range() function generates a sequence of numbers, which is often used with for loops.
It takes three arguments: start, stop, and step.
Loops allow you to repeat a block of code multiple times. Python provides two main types of
loops: for loop and while loop.
The for loop iterates over a sequence or any iterable object. It repeats the loop body for each
item in the sequence.
Syntax:
Examples:
# Loop from 0 to 4
for i in range(5):
print(i)
# Loop from 2 to 5
for i in range(2, 6):
print(i)
Be cautious with while loops, as they can lead to infinite loops if the condition never
becomes false.
Syntax:
while condition:
# Code to execute as long as condition is true
Example:
count = 0
while count < 5:
print(f"Count: {count}")
count = count+1
Combining selection and iteration enables powerful control structures. For example, you
might use an if-else statement within a for or while loop to make decisions for each
iteration.
n = int(input("Enter n: "))
for i in range(1, n + 1):
if i % 4 == 0 and i % 3 != 0 :
print(i)
n = int(input("Enter n: "))
i = 1
while i<=100:
if i % 4 == 0 and i % 3 != 0 :
print(i)
i = i+1
Loop Control Statements in Python
1. The break Statement
The break statement is used to terminate a loop prematurely, regardless of the loop's original
condition. When break is encountered, the control is immediately transferred to the first
statement after the loop.
Use Case: When you want to stop looping as soon as a certain condition is met.
Output:
1
2
3
4
count = 0
while count < 10:
if count == 6:
break
print(count)
count = count + 1
Output:
0
1
2
3
4
5
The continue statement skips the current iteration of a loop and continues with the next
iteration. It doesn't stop the loop but moves the execution back to the loop's condition check.
Use Case: When you want to skip some specific items in a loop but continue with the others.
Output:
1
2
3
4
6
7
8
9
Explanation: The loop skips the iteration when number is 5 but continues with the next
numbers.
The pass statement does nothing; it’s a placeholder used when a statement is syntactically
required but no action is needed. It’s often used during the development phase, allowing you
to implement the logic later.
Use Case: When you have a loop or a conditional block where no action is needed yet.
Example:
Output:
1
3
5
7
9
Explanation: The loop ignores even numbers and only prints odd numbers.
Q. Write a python program to check if the input number is odd or even.
if number % 2 == 0:
else:
Q. Write a Python program to calculate the bus fare based on the distance travelled. The
fare structure is as follows:
Example:
fare = distance * 2
else:
if num > 0:
print(f"{num} is positive.")
print(f"{num} is negative.")
else:
if age < 0:
print("Invalid age.")
else:
print("Eligible to vote.")
if a>b:
large=a
else:
large=b
Explanation:
if year < 0:
print("Invalid year.")
else:
n = int(input("Enter n: "))
for i in range(n):
print(i)
n = int(input("Enter n: "))
for i in range(1,n+1):
print(2 * i)
sum = 0
for i in range(1,n+1):
n = int(input("Enter n : "))
fact = 1
for i in range(1,n+1):
fact = fact*i
OR
n = int(input("Enter n : "))
fact = factorial(n)
LOGIC!
n = 159
count = 0
Is n non-zero ? Yes!
Is n non-zero ? Yes!
Is n non-zero ? Yes!
n = num
count = 0
num = abs(num)
num = num // 10
count = count+1
An Armstrong number is a number that is equal to the sum of its own digits, each raised to the
power of the number of digits.
n = num
count = 0
if num == 0:
count = 1
num = abs(num)
num = num // 10
count = count + 1
sop = 0
num = n
num = num // 10
if sop == n:
else:
if number <= 1:
else:
if number % i == 0:
break
else:
145
1!+4!+5!=1+24+120=145
num = int(input("Enter a number: "))
sum_of_factorials = 0
temp = num
digit = temp % 10
factorial = 1
factorial *= i
sum_of_factorials += factorial
temp //= 10
if sum_of_factorials == num:
else:
Nested loops are loops inside other loops. In Python, we often use nested loops when we need
to perform operations that require looping over multiple levels.
A nested loop means having one loop inside another loop. Each time the outer loop runs, the
inner loop will run to completion before returning to the next iteration of the outer loop.
Syntax:
print("*",end="")
print()
Output :
Enter Size = 7
**
***
****
*****
******
*******
In Python, sequence data types are types of data that store a collection of items in an ordered way.
The order means that each item has a specific position, which allows us to access each item by its
index (or position) in the sequence.
1. Strings
2. List
3. Tuple
Strings
A string is a sequence of characters. For example, "hello" is a string, where each character has a
position.
S = “Hello”
Positive Indexing
Positive indexing starts from the left (beginning) of the sequence and goes to the right. It begins at 0
for the first element and increases by 1 for each subsequent element.
Negative Indexing
Negative indexing starts from the right (end) of the sequence and goes to the left. It begins at -1 for
the last element and decreases by 1 as you move leftward.
To print a single character out of the string, we can use the subscript operator. The subscript operator
(also called bracket operator) is denoted by [ ].Mention the index whose character you want to print.
Example :
str="Thrissur"
print(str[0])
T
print(str[4])
print(str[-2])
Example
str = "Hello"
print(len(str)) # Output: 5
Traversing a string
To traverse a string in Python, you access each character one at a time, starting from the
beginning and moving towards the end. This process is called traversal. The for loop is useful
for this:
str = "Techtalkz"
for i in str:
print(i)
In this example:
The for loop goes through each character (i) in the string "Techtalkz".
Each character is printed on a new line, allowing you to see each character individually as
you traverse the string.
Concatenation and Repetition in Strings
In Python, the + and * operators are used for concatenation and repetition with strings:
Concatenation (+): The + operator joins two strings together without adding any space.
str1 = "Tech"
str2 = "Talkz"
str = "Techtalkz"
String Slicing
In Python, string slicing allows you to extract parts of a string using the syntax
[start:end:step]:
3. Negative Indexing:
o Negative indices count from the end. text[-k:] returns the last k characters.
4. Full String [:]: Omitting both indices returns the entire string.
String Methods
str= “HELLO”
str.lower() # Output: "hello"
str = “hello”
str.upper() # Output: "HELLO"
str.find("e") # Output: 1
str = “1234”
str.isdigit() # Output: True
9. str.split(delimiter) – Splits a string into a list of substrings based on delimiter.
University Questions:
1. Let the variable x be “dog” and the variable y be “cat”. Write the values returned by
the following operations: a)x*4+' '+4*y b) x*len(x+y)
2.
Ans: Try!
3.
Ans:
word_list = text.split()
upper_text = text.upper()
print("Uppercase string:", upper_text)
position = text.find("rules")
1. Introduction to Lists
2. Creating Lists
List indices work similarly to string indices. Use the subscript operator [ ] to access
elements.
4. List Comprehension
2. list_1 = [1,2,3,4,5,6,7,8,9,10]
selected_list = [x for x in list_1 if x % 2 == 0]
5. List Operations
list_a = [1, 2, 3]
list_b = ["a","b",77]
combined_list = list_a + list_b
print(combined_list) # Output: [1, 2, 3, 4, 5, 6]
list_a = [1, 2, 3]
repeated_list = list_a * 3
print(repeated_list) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
Relational operators (like >, <) compare lists lexicographically (i.e., element by
element).
list_x = [1, 2, 3]
list_y = [1, 2, 4]
print(list_x < list_y) # Output: True, because 3 < 4 in the first
# non-matching pair
list_a = [2, 3, 5]
list_b = [2, 3, 5, 7]
print(list_a < list_b) # Output: True, because list_a is shorter and
# identical in elements up to its length
list_c = [3, 4, 5]
list_d = [3, 2, 5]
print(list_c > list_d) # Output: True, because 4 > 2 in the second
# position
list_c = [3, 4, 5]
list_d = [3, 4, 5]
print(list_c == list_d) # True
6. Membership Operators
List_1 = [2, 4, 6]
print(2 in list_1) # Output: True
7. List Slices
my_list = [1,2,3,"a","b","c"]
sublist = my_list[1:3]
8. List Mutability
Inserting elements: The slice operator can insert elements at a specified position.
prime = [2, 3, 5, 7]
prime[4:4] = [11] #insert „11‟ at index 4
my_list = [“a”,1,3,45,56,”x”]
del my_list[2] # ['a', 1, 45, 56, 'x']
char_list = list("hello")
Example 1:
a b c
1 0 1 2
7
0 1 2
Accessing elements:
list[0] = 1
list[1][0] = a
list[1][1] = b
list[1][2] = c
list[2] = 7
Example 2:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Aliasing: Assigning a list to another variable creates a reference to the same list.
alias_list = original_list
cloned_list = original_list[:]
1. Characteristics of Tuples
Indexed: Like lists, tuple elements can be accessed using their index.
Creating Tuples
1. Using parentheses:
5. Tuple Operations
Many operations that work with lists also work with tuples:
t1 = (1, 2, 3)
t2 = (4, 5)
# Concatenation
print(t1 + t2) # Output: (1, 2, 3, 4, 5)
# Repetition
print(t1 * 2) # Output: (1, 2, 3, 1, 2, 3)
b. Membership Testing:
t = (1, 2, 2, 3, 4)
6. Immutability of Tuples
Tuples are immutable, which means attempting to modify their contents will result in
an error:
t = (1, 2, 3)
t[0] = 10 # Error:'tuple' object does not support item assignment
NumPy and Arrays with Examples
NumPy: Stands for Numerical Python. Useful for advanced computations like linear
algebra, Fourier transforms, and random simulations.
Array: Homogeneous data collection.
Importing NumPy:
import numpy as np
1. Creating Arrays
1D Array:
Output:
[1 2 3 4]
2D Array (Matrix):
Output:
[[1 2]
[3 4]]
Array Dimensions:
print(arr.ndim) # 1
print(mat.ndim) # 2
Shape:
print(arr.shape) # (4,)
print(mat.shape) # (2, 2)
2D Array Access:
1D Array:
for i in arr:
print(i, end=" ")
Output:
10 20 30 40 50
2D Array:
Output:
1 2 3 4 5 6
Reshape:
Output:
[[1 2 3]
[4 5 6]]
5. Matrix Operations
Addition and Subtraction:
Matrix Multiplication:
print(np.matmul(mat1, mat2))
Output:
[[19 22]
[43 50]]
Transpose:
print(mat1.T)
Output:
[[1 3]
[2 4]]
Introduction to Sets and Dictionaries in Python
Sets
Sets are collections of unique elements, making them ideal for managing groups of items
where duplicates are not allowed. Sets are best suited for:
1. * Unordered Collection: Items have no defined order. (Version Python 3.7 onwards
dictionaries are ordered) Before version 3.7: Dictionaries in Python were unordered
collections
2. No Indexing: Elements can't be accessed using indices.
Adding elements:
Removing elements:
animals.remove("dog")
print(animals)
Clearing a set:
animals.clear()
print(animals)
Output: set()
3. Set Operations
A = {1, 2, 3}
B = {3, 4, 5}
print(A.union(B))
Output
{1, 2, 3, 4, 5}
print(A.intersection(B))
Output
{3}
print(A.difference(B))
Output
{1, 2}
print(B.difference(A))
Output
{4, 5}
print(A.symmetric_difference(B))
Output{1, 2, 4, 5}
Dictionary in Python
Eg:
Accessing Values
Using keys:
Eg:
d_1 = {1:"Roy" , 2:"Ram", 3: "Manzoor"}
print(d_1[1])
Output: Roy
print(d_1[2])
Output: Ram
d_1[4] = "Ammu"
print(d_1)
5. Removing Entries
Using del:
del d_1[1]
print(d_1)
Using pop:
name = d_1.pop(2)
print(name) # Output: Ram
print(d_1)
Output:
Ram
{1: 'Parthiv_Roy', 3: 'Manzoor', 4: 'Ammu'}
d_1.clear()
print(d_1)
Output: {}
6. Traversing a Dictionary
Output:
name
age
city
for i in person.values():
print(value)
Output:
Alice
25
London
Output:
name: Alice
age: 25
city: London
DECOMPOSITION AND MODULARIZATION
Introduction
Decomposition and modularization are strategies that break down complex problems into
manageable parts. These techniques allow us to focus on smaller, well-defined tasks, making
it easier to solve the original problem and maintain the solution.
1. Problem Decomposition
Definition:
Problem decomposition is the process of dividing a complex problem into smaller sub-
problems or components that can be solved independently or sequentially.
Advantages:
1. Divide: The array is divided into two halves recursively until each subarray has one
element.
2. Sort: Each sub-array is sorted individually.
3. Merge: The sorted sub-arrays are merged to produce a single sorted array.
Merge Sort Example:
Algorithm Outline:
2. Modularization
Definition:
Modularization is the process of organizing a system into separate modules that can be
developed, tested, and understood independently, but function together as a complete system.
Each module performs a specific task and can be implemented and tested independently.
Given a list of integers arr with n ≥ 3, we want to find the top three largest numbers.
Algorithm:
Modular Implementation:
Definition
A function in Python is a block of reusable code that performs a specific task. Functions are used to
break down programs into smaller, manageable, and modular parts, enhancing readability,
maintainability, and code reusability.
Structure of a Function
Syntax
def function_name(parameters):
# Statements
return output
A function with no arguments and no return value is a simple function that performs a task without
requiring any input from the user and does not send any output back to the caller.
Calling..… welcome()
welcome()
Set of instructions
Example:
def welcome():
print("Hello")
print("Welcome to TeckTalkz")
welcome()
Output:
Hello
Welcome to TeckTalkz
calling…
welcome(“Roy”)
welcome(name)
Set of instructions
Example:
def welcome(name):
print(f"Hello {name}")
print("Welcome to TeckTalkz")
welcome("Roy")
welcome("Varsha")
Output:
Hello Roy
Welcome to TeckTalkz
Hello Varsha
Welcome to TeckTalkz
square(8)
square(x)
64
Set of instructions
Example:
def square(x):
return x*x
result = square(8)
print(result)
Output:
64
def sum(x,y):
return x+y
result = sum(a,b)
print(f"Sum = {result}")
Q. Write a program to find the factorial using a user defined function
def factorial(n):
result = 1
result = result*i
return result
12
123
1234
12345
def pyramid(n):
for i in range(1,n+1):
for j in range(i):
print(j,end=" ")
print()
pyramid(n)
Q. Write a program to print median of set of numbers.
def accept(n):
numbers = []
for i in range(n):
numbers.append(num)
return numbers
def median(numbers):
numbers.sort()
n = len(numbers)
if n % 2 == 0:
else:
median = numbers[n // 2]
return median
numbers = accept(data)
median = median(numbers)
Definition
Recursion is a programming technique where a function calls itself to solve smaller instances of the
same problem. It continues until it reaches a base case, which is a condition that terminates the
recursive calls.
Consider a function:
def hello():
print("Hello ")
hello()
hello()
The code you provided is an example of infinite recursion, as the hello function repeatedly calls itself
without a base case to stop the recursion.
1. Base Case
o The condition under which the recursive function stops calling itself.
o Prevents infinite recursion and ensures the program terminates.
2. Recursive Case
o Defines how the problem is reduced into smaller sub
problems.
o The function calls itself with updated parameters to work toward the base
case.
def hello(count):
if count <= 0: # Base case to stop recursion
return
print("Hello")
hello(count - 1) # Recursive case with reduced problem size
hello(5)
For every recursive call, a new function frame is pushed onto the stack. Here’s how the stack
evolves:
When a function calls itself, the current state is pushed onto the stack.
When the base case is reached, calls are popped from the stack one by one as the
recursion unwinds
Example
def fun(n):
if n == 0:
return 1
else:
return 1+fun(n-1)
print(fun(3))
Call Stack :
Step-by-Step Execution
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
Call Stack:
1. Returning to factorial(1)
o
factorial(1) computes: 1 * factorial(0) = 1 * 1 = 1.
o
Returns: 1.
2. Returning to factorial(2)
o factorial(2) computes: 2 * factorial(1) = 2 * 1 = 2.
o Returns: 2.
3. Returning to factorial(3)
o factorial(3) computes: 3 * factorial(2) = 3 * 2 = 6.
o Returns: 6.
4. Returning to factorial(4)
o factorial(4) computes: 4 * factorial(3) = 4 * 6 = 24.
o Returns: 24.
Final Output:
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2) # Recursive formula
Q. Python program to find the n-th Fibonacci number using a recursive approach
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
Circularity in Recursion
Definition:
Circularity in recursion occurs when a recursive function does not have a clear base case or
when the function's logic creates an infinite loop of function calls. This leads to a situation
where the recursion never terminates, causing a stack overflow error.
Consider a function:
def hello():
print("Hello ")
hello()
hello()
The code you provided is an example of infinite recursion, as the hello function repeatedly calls itself
without a base case to stop the recursion.