0% found this document useful (0 votes)
8 views

module 3-6

Module 3 covers selection and iteration in Python, detailing conditional statements such as if, if-else, and elif for decision-making, along with loops including for and while for repetitive tasks. It also introduces loop control statements like break, continue, and pass, and provides practical examples and exercises for various programming scenarios. Additionally, the module discusses nested loops and sequence data types, including strings, lists, and tuples.

Uploaded by

joshuasuvymanuel
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)
8 views

module 3-6

Module 3 covers selection and iteration in Python, detailing conditional statements such as if, if-else, and elif for decision-making, along with loops including for and while for repetitive tasks. It also introduces loop control statements like break, continue, and pass, and provides practical examples and exercises for various programming scenarios. Additionally, the module discusses nested loops and sequence data types, including strings, lists, and tuples.

Uploaded by

joshuasuvymanuel
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
You are on page 1/ 50

MODULE 3

Selection and Iteration in Python


1. Selection in Python: Using Conditional Statements

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.

1.1 The if Statement (Single way selection)

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:

x = int(input("Enter a number : "))


if x > 5:
print(f"{x} is greater than 5")

1.2 The if-else Statement (Two way selection)

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:

x = int(input("Enter a number : "))

if x > 15:

print(f"{x} is greater than 15")

else:

print(f"{x} is not greater than 15")

1.3 The elif Statement (Multi way selection)

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:

# Input three numbers


a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
c = int(input("Enter the third number: "))

# Determine the largest number


if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c

# Output the largest number


print(f"The largest number is: {largest}")
2. Iteration in Python: Using Loops

The range() Function

The range() function generates a sequence of numbers, which is often used with for loops.
It takes three arguments: start, stop, and step.

 range(stop): Generates numbers from 0 to stop - 1.

Eg: range(5) : Generates numbers from 0 to 4.

 range(start, stop): Generates numbers from start to stop - 1.


 Eg: range(1,5) : Generates numbers from 1 to 4.

 range(start, stop, step): Generates numbers from start to stop - 1, with


increments defined by step.

Eg: range(1,10,2) : Generates numbers 1,3,5,7,9

range(10,2,-2) : Generates numbers 10,8,6,4 ( start = 10: The sequence starts at


10.  stop = 2: The sequence stops before reaching 2 (2 is not included).  step = -2: The
sequence decreases by 2 on each iteration.)

Loops allow you to repeat a block of code multiple times. Python provides two main types of
loops: for loop and while loop.

2.1 for Loop

The for loop iterates over a sequence or any iterable object. It repeats the loop body for each
item in the sequence.

Syntax:

for variable in sequence:


# Code to execute for each item in sequence

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)

# Loop from 1 to 9 with step 2


for i in range(1, 10, 2):
print(i)

2.3 while Loop

The while loop continues to execute as long as a specified condition is true.

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

3. Combining Selection and Iteration

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.

Example: Using if with for

print numbers from 1 to n that are divisible by 4 but not by 3.

n = int(input("Enter n: "))
for i in range(1, n + 1):
if i % 4 == 0 and i % 3 != 0 :
print(i)

Example: Using if with while

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.

Example with for loop:

for number in range(1, 10):


if number == 5:
break
print(number)

Output:

1
2
3
4

The loop stops as soon as number is equal to 5.

Example with while loop:

count = 0
while count < 10:
if count == 6:
break
print(count)
count = count + 1

Output:

0
1
2
3
4
5

Explanation: The while loop breaks when count reaches 6.


2. The continue Statement

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.

Example with for loop:

for number in range(1, 10):


if number == 5:
continue
print(number)

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.

3. The pass Statement

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:

for number in range(1, 10):


if number % 2 == 0:
pass # Even numbers are ignored for now
else:
print(number)

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.

number = int(input("Enter an integer: "))

if number % 2 == 0:

print("The number is even.")

else:

print("The number is odd.")

Q. Write a Python program to calculate the bus fare based on the distance travelled. The
fare structure is as follows:

 For the first 50 kilometres, the fare rate is ₹2 per kilometre.


 For each kilometre beyond 50, the rate is ₹1.5 per kilometre.

Example:

 If the distance travelled is 40 kilometres, the fare should be 40 × 2 = ₹80.


 If the distance travelled is 70 kilometres, the fare should be (50 × 2) + (20 × 1.5)
= ₹125

distance = float(input("Enter the distance travelled (in


kilometres): "))

# Calculate the fare

if distance <= 50:

fare = distance * 2

else:

fare = (50 * 2) + ((distance - 50) * 1.5)

print(f"The total fare is: ₹*fare:.2f+")


Q. Write a program to check the number is positive or not

# Input: integer number

num = int(input("Enter a number: "))

# Check if the number is positive, negative, or zero

if num > 0:

print(f"{num} is positive.")

elif num < 0:

print(f"{num} is negative.")

else:

print(f"{num} is neither positive nor negative.")

Q. Write program that checks voting eligibility based on age

age = int(input("Enter your age: "))

if age < 0:

print("Invalid age.")

elif age < 18:

print("Not eligible to vote.")

else:

print("Eligible to vote.")

Q. To determine the maximum of two numbers.

a=int(input("Enter the first number"))

b=int(input("Enter the second number"))

if a>b:

large=a

else:

large=b

print("The larger of",a,"and",b,"is",large)


Q. Write a program to check whether a year is a leap year or not.

Explanation:

 The program takes a year as input.


 It checks if the year is negative and prints an error message if it is.
 It uses the leap year rules:
o A year is a leap year if it is divisible by 4 but not divisible by 100, or it is
divisible by 400.
 The program outputs whether the year is a leap year or not.

year = int(input("Enter a year: "))

if year < 0:

print("Invalid year.")

elif (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):

print(f"{year} is a leap year.")

else:

print(f"{year} is not a leap year.")

Q. Write a program to print n whole numbers

n = int(input("Enter n: "))

print(f"The first {n} whole numbers are:")

for i in range(n):

print(i)

Q. Write a program to print n even numbers

n = int(input("Enter n: "))

print(f"The first {n} even numbers are:")

for i in range(1,n+1):

print(2 * i)

Q. Write a program to print sum of first n even numbers


n = int(input("Enter n: "))

sum = 0

for i in range(1,n+1):

sum = sum + 2*i

print(f"Sum of first {n} even numnebrs are {sum}")

Q. Write a program to find the factorial of a given number

n = int(input("Enter n : "))

fact = 1

for i in range(1,n+1):

fact = fact*i

print(f"factorial of {n} = {fact}")

OR

from math import factorial

n = int(input("Enter n : "))

fact = factorial(n)

print(f"Factorial of {n} = {fact}")

Q. Write a program to count the number of digits of a given number.

If number = 159 , Display -> number of digits = 3

If number = -23179 , Display -> number of digits = 5

LOGIC!

n = 159

count = 0

Is n non-zero ? Yes!

Then count = count +1 = 0+1 = 1 , n = n//10 = 159 // 10 = 15

Is n non-zero ? Yes!

Then count = count +1 = 1+1 = 2, n = n//10 = 15 // 10 = 1

Is n non-zero ? Yes!

Then count = count +1 = 2+1 = 3, n = n//10 = 1 // 10 = 0


Is n non-zero ? NO! Then Stop the Evaluation and Print count

num = int(input("Enter a number : "))

n = num

count = 0

num = abs(num)

while num > 0:

num = num // 10

count = count+1

print(f"The number {n} has {count} digits")

Q. Write a program to check the given number is Armstrong number or not.

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.

For example, 153 is an Armstrong number because 13 + 53 + 33 = 153

1634 is an Armstrong number because 14 + 64 + 34 + 44 = 1634

num = int(input("Enter a number: "))

n = num

count = 0

if num == 0:

count = 1

num = abs(num)

while num > 0:

num = num // 10

count = count + 1

sop = 0

num = n

while num > 0:


digit = num % 10

sop = sop + digit ** count

num = num // 10

if sop == n:

print(f"{n} is an Armstrong number.")

else:

print(f"{n} is not an Armstrong number.")

Q. Write a program to check the number is prime or not

number = int(input("Enter a number: "))

if number <= 1:

print(f"{number} is not a prime number.")

else:

for i in range(2, int(number**0.5) + 1):

if number % i == 0:

print(f"{number} is not a prime number.")

break

else:

print(f"{number} is a prime number.")

Q. Write a program to check the given number is a strong number


or not .

A strong number (also known as a Krishnamurthy number) is a


number whose sum of the factorials of its digits equals the
number itself. For example,

145

145 is a strong number because

1!+4!+5!=1+24+120=145
num = int(input("Enter a number: "))

sum_of_factorials = 0

temp = num

while temp > 0:

digit = temp % 10

factorial = 1

for i in range(1, digit + 1):

factorial *= i

sum_of_factorials += factorial

temp //= 10

if sum_of_factorials == num:

print(f"{num} is a strong number.")

else:

print(f"{num} is not a strong number.")


Nested Loops in Python

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.

Structure of a Nested Loop

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:

for outer_variable in outer_sequence:


# Code block for the outer loop
for inner_variable in inner_sequence:
# Code block for the inner loop
Example :

n = int(input("Enter Size = "))

for i in range(1,n+1): #Outer Loop

for j in range(i): #Inner Loop

print("*",end="")

print()

Output :

Enter Size = 7

**

***

****

*****

******

*******

Pattern: Triangle of numbers

n = int(input("Enter Size = "))

for i in range(1,n+1): #Outer Loop

for j in range(i): #Inner Loop

print(j,end = " ")


print()
Sequence Data Type

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.

Here are the main sequence data types in Python:

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])

The len() function calculates the number of characters in the string

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:

# Example of string traversal

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"

print(str1 + str2) # Output: TechTalkz

Repetition (*): The * operator repeats a string a specified number of times.

str = "Techtalkz"

print(str * 3) # Output: TechtalkzTechtalkzTechtalkz

String Slicing

In Python, string slicing allows you to extract parts of a string using the syntax
[start:end:step]:

1. Basic Slicing [n:m]: Extracts a substring starting from index n up to m-1.

text = "Hello, World!"


print(text[0:5]) # Output: Hello
print(text[7:12]) # Output: World

2. Omitting Start or End:


o If n is omitted, the slice starts from the beginning.
o If m is omitted, the slice goes to the end.

print(text[:5]) # Output: Hello


print(text[7:]) # Output: World!

3. Negative Indexing:
o Negative indices count from the end. text[-k:] returns the last k characters.

print(text[-6:]) # Output: World!

4. Full String [:]: Omitting both indices returns the entire string.

print(text[:]) # Output: Hello, World!


5. Step in Slicing [::step]: Specifies the interval between characters in the slice.

print(text[::2]) # Output: Hlo ol!

String Methods

Commonly used string methods in Python:

1. str.lower() – Converts all characters to lowercase.

str= “HELLO”
str.lower() # Output: "hello"

2. str.upper() – Converts all characters to uppercase.

str = “hello”
str.upper() # Output: "HELLO"

3. str.strip() – Removes leading and trailing whitespace.


4. str.replace(old, new) – Replaces all occurrences of old with new.

str = “Hello world!”


str.replace("world", "Python") # Output: "Hello Python"

5. str.find(substring) – Returns the index of the first occurrence of substring, or -


1 if not found.

str = “Hello world!”

str.find("e") # Output: 1

6. str.count(substring) – Counts occurrences of substring in the string.

str = “Hello world!”


str.count("o") # Output: 2

7. str.capitalize() – Capitalizes the first character of the string.

str = “hello world!”


str.capitalize() # Output: "Hello world!"

8. str.isdigit() – Checks if all characters in the string are digits.

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)

Ans: Dot it yourself !

2.

Ans: Try!

3.

Ans:

text = "Python rules!"

word_list = text.split()

print("List of words:", word_list)

upper_text = text.upper()
print("Uppercase string:", upper_text)

position = text.find("rules")

print("Position of 'rules':", position)

replaced_text = text.replace("!", "?")

print("Replaced string:", replaced_text)


Lists

1. Introduction to Lists

 A list is an ordered collection of data values.


 The values in a list are called elements or items.
 Lists are versatile; they can hold elements of different data types, unlike strings,
where each character must be a string.

2. Creating Lists

 To create a new list, enclose the elements in square brackets [].

my_list = [1, 2, 'hello', True]

3. Accessing List Elements and Traversal

 List indices work similarly to string indices. Use the subscript operator [ ] to access
elements.

my_list = [1, 2, 'hello', True]


my_list[0] # Access the first element
my_list[-1] # Access the last element

4. List Comprehension

 List comprehension allows creating a new list by applying an expression to each


element in an existing list.

1. squared = [x**2 for x in range(5)]

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

 + operator: Concatenates lists.

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]

 * operator: Repeats a list a specified number of times.

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

 The in operator checks for the presence of an element in a list.

List_1 = [2, 4, 6]
print(2 in list_1) # Output: True

7. List Slices

 Slices can be used to access sub-parts of a list, similar to slicing in strings.

my_list = [1,2,3,"a","b","c"]

sublist = my_list[1:3]

8. List Mutability

 Lists are mutable, allowing elements to be added, removed, or modified.

9. Using the Slice Operator for List Mutations

 Replacing elements: Use slices to replace elements in a list.

composite = [13, 17, 19, 23, 25]


composite[4:] = [29, 31] #output : [13, 17, 19, 23, 29, 31]

 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

 Removing elements: Set a slice to an empty list to remove elements.


composite = [3, 5, 7, 9]
composite[2:3] = []

10. Using del Keyword for Deletion

 The del keyword can delete elements or slices directly.

my_list = [“a”,1,3,45,56,”x”]
del my_list[2] # ['a', 1, 45, 56, 'x']

11. Common List Methods

 list.index(element): Returns the position of element.


 list.insert(position, element): Inserts element at position.
 list.append(element): Adds element at the end.
 list.extend(aList): Appends all elements from aList.
 list.remove(element): Removes element from L.
 list.pop(): Removes and returns the last element.
 list.sort(): Sorts the list.
 list.reverse(): Reverses the list.

13. Strings and Lists

 Converting strings to lists:

char_list = list("hello")

 Splitting a string into words:

words = "hello world".split()

14. List of Lists (Nested Lists)

 A list can contain other lists

Example 1:

list_1 = [1 , [“a” ,”b” ,”c”] , 7]

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]]

15. List Aliasing and Cloning

 Aliasing: Assigning a list to another variable creates a reference to the same list.

alias_list = original_list

 Cloning: Creating a copy using slicing [:].

cloned_list = original_list[:]

 Equality and Identity in Lists


o is checks identity (if two variables point to the same object).
o == checks structural equivalence (if two lists have the same elements).
Tuples in Python
A tuple is an ordered, immutable sequence of elements, similar to a list. Unlike lists, however, the
contents of a tuple cannot be modified once created. Tuples are often used for storing collections of
items that should remain constant throughout the program.

1. Characteristics of Tuples

 Immutable: The contents of a tuple cannot be changed (no addition, removal, or


modification of elements).

 Ordered: The elements in a tuple maintain their order.

 Heterogeneous: Tuples can contain elements of different data types.

 Indexed: Like lists, tuple elements can be accessed using their index.

Creating Tuples

Tuples can be created in the following ways:

1. Using parentheses:

# Tuple with multiple elements


t = ('apple', 'banana', 'cherry')
print(t) # Output: ('apple', 'banana', 'cherry')

# Tuple with different data types


mixed_tuple = ('python', 3.7, True)
print(mixed_tuple) # Output: ('python', 3.7, True)

2. Without parentheses (Optional):

t = 'a', 'b', 'c'


print(t) # Output: ('a', 'b', 'c')

3. Using the tuple() function:

# Convert a string to a tuple


t = tuple("hello")
print(t) # Output: ('h', 'e', 'l', 'l', 'o')

# Convert a list to a tuple


t = tuple([1, 2, 3])
print(t) # Output: (1, 2, 3)
4. Accessing Elements in Tuples

Tuple elements can be accessed using indexing and slicing:

t = ('p', 'y', ’t’, 'h', 'o', 'n')

# Access elements using indices


print(t[0]) # Output: 'p'
print(t[-1]) # Output: 'n'

# Access a range of elements (slicing)


print(t[1:4]) # Output: ('y', 't', 'h')

5. Tuple Operations

Many operations that work with lists also work with tuples:

a. Concatenation and Repetition:

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 = ('a', 'b', 'c')


print('a' in t) # Output: True
print('z' in t) # Output: False

c. Length and Count:

t = (1, 2, 2, 3, 4)

# Length of the tuple


print(len(t)) # Output: 5

# Count occurrences of an element


print(t.count(2)) # Output: 2

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

Arrays using NumPy

 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:

arr = np.array([1, 2, 3, 4])


print(arr)

Output:
[1 2 3 4]

 2D Array (Matrix):

mat = np.array([[1, 2], [3, 4]])


print(mat)

Output:
[[1 2]
[3 4]]

 Array Dimensions:

ndim is an attribute in numpy package to find the dimension of array

print(arr.ndim) # 1
print(mat.ndim) # 2

 Shape:

shape is an attribute in numpy package to find the shape of array


(number of rows and columns)

print(arr.shape) # (4,)
print(mat.shape) # (2, 2)

2. Accessing Array Elements

 Indexing and Slicing:


arr = np.array([10, 20, 30, 40, 50])
print(arr[2]) # 30
print(arr[1:4]) # [20 30 40]
print(arr[-1]) # 50

 2D Array Access:

mat = np.array([[1, 2, 3], [4, 5, 6]])


print(mat[0, 2]) # 3
print(mat[-1, -1]) # 6

3. Iterating Over Arrays

 1D Array:

for i in arr:
print(i, end=" ")

Output:
10 20 30 40 50

 2D Array:

for row in mat:


for elt in row:
print(elt, end=" ")

Output:

1 2 3 4 5 6

4. Changing Array Dimensions

 Reshape:

arr = np.array([1, 2, 3, 4, 5, 6])


print(arr.reshape(2, 3))

Output:

[[1 2 3]
[4 5 6]]

5. Matrix Operations
 Addition and Subtraction:

mat1 = np.array([[1, 2], [3, 4]])


mat2 = np.array([[5, 6], [7, 8]])
print(np.add(mat1, mat2)) # [[6 8] [10 12]]
print(np.subtract(mat1, mat2)) # [[-4 -4] [-4 -4]]

 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:

 Membership Tests: Quickly check if an element exists.


 Set Operations: Perform union, intersection, and difference.
 Uniqueness: Automatically removes duplicates.

Key Features of Sets

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.

1. Creating a Set and Accessing Elements

A set is created by enclosing the items in a pair of braces. { }

Example 1: Creating a set directly with elements

fruits = {"apple", "banana", "cherry"}


print(fruits)

Output: {'apple', 'banana', 'cherry'}

(order may vary according to the Python version)

Example 2: Creating a set from a list

numbers = set([1, 2, 3, 4, 4])


print(numbers)

Output: {1, 2, 3, 4} (duplicates removed)

Example 3: Accessing elements


Sets cannot be indexed. Instead, you use a loop to access elements.

vowels = {"a", "e", "i", "o", "u"}


for i in vowels:
print(i, end=" ")

Output: a e i o u (order may vary)


2. Adding and Removing Elements

Adding elements:

animals = {"cat", "dog"}


animals.add("rabbit")
print(animals)

Output: {'cat', 'dog', 'rabbit'}

Removing elements:

animals.remove("dog")
print(animals)

Output: {'rabbit', 'cat'}

Using discard (safe removal):

animals.discard("lion") # No error even if 'lion' is not in the set


print(animals)

Output: {'cat', 'rabbit'}

Clearing a set:

animals.clear()
print(animals)

Output: set()

3. Set Operations

 Union: Combines all elements.

A = {1, 2, 3}
B = {3, 4, 5}
print(A.union(B))

Output
{1, 2, 3, 4, 5}

 Intersection: Common elements.

print(A.intersection(B))

Output
{3}

 Difference: Elements in A but not in B.

print(A.difference(B))
Output
{1, 2}

print(B.difference(A))

Output
{4, 5}

 Symmetric Difference: Elements in either set but not in both.

print(A.symmetric_difference(B))

Output{1, 2, 4, 5}

Dictionary in Python

A dictionary is a collection which is ordered, changeable and do not allow


duplicates.

Dictionaries are used to store data values in key:value pairs.

Eg:

dict_1 = {1: 'Tech', 2: 'Talkz'}

student = {"name": "John", "age": 20, "grade": "A"}

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

Using get() method:

print(d_1.get(3)) # Output: Manzoor

print(d_1.get(4)) # Output: None

# Default value if the key doesn't exist


print(d_1.get(4, "Not found")) # Output: Not found
4. Adding and Modifying Entries

Adding a new key-value pair:

d_1[4] = "Ammu"
print(d_1)

Output: {1: 'Roy', 2: 'Ram', 3: 'Manzoor', 4: 'Ammu'}

Updating an existing value:

d_1[1] = "Parthiv Roy"


print(d_1)

Output: {1: 'Parthiv Roy', 2: 'Ram', 3: 'Manzoor', 4: 'Ammu'}

5. Removing Entries

Using del:

del d_1[1]
print(d_1)

Output: {2: 'Ram', 3: 'Manzoor', 4: 'Ammu'}

Using pop:

name = d_1.pop(2)
print(name) # Output: Ram
print(d_1)

Output:
Ram
{1: 'Parthiv_Roy', 3: 'Manzoor', 4: 'Ammu'}

Clearing all entries:

d_1.clear()
print(d_1)

Output: {}

6. Traversing a Dictionary

Iterating through keys:

person = {"name": "Alice", "age": 25, "city": "London"}


for i in person:
print(i)

Output:
name
age
city

Iterating through values:

for i in person.values():
print(value)

Output:
Alice
25
London

Iterating through key-value pairs:

for i,j in person.items():


print(f"{i}: {j}")

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:

 Simplifies understanding of the problem.


 Promotes step-by-step solution development.
 Makes debugging and testing easier.
 Encourages reuse of solutions for similar problems.

Example: Merge Sort

Merge Sort is a classic example of problem decomposition. It uses a divide-and-conquer


approach to sort an array.

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:

 Input: An unsorted array arr of size n.


 Process:
o Divide arr into two halves left and right.
o Recursively sort left and right.
o Merge left and right into a sorted array.
 Output: A sorted array.

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.

Motivation for Modularization:

 Enhances code readability and maintainability.


 Encourages code reuse.
 Simplifies collaborative development.
 Facilitates easier testing and debugging.
3. Demonstrating Modularization

Example 1: Merge Sort

In Merge Sort, modularization can be seen in its implementation:

 Module 1: Splitting the array into halves.


 Module 2: Recursively sorting the halves.
 Module 3: Merging sorted halves.

Each module performs a specific task and can be implemented and tested independently.

Example 2: Returning the Top Three Integers from a List

Given a list of integers arr with n ≥ 3, we want to find the top three largest numbers.

Algorithm:

1. Input: List of integers arr.


2. Decompose the Problem:
o Find the first largest number (max1).
o Find the second largest number (max2) in the remaining list.
o Find the third largest number (max3) in the rest of the list.
3. Output: [max1, max2, max3].

Modular Implementation:

 Module 1: Identify the largest number (max1) in the list.


 Module 2: Exclude max1 and identify the second largest number (max2).
 Module 3: Exclude max1 and max2 and identify the third largest number (max3).
Functions in Python

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.

Advantages of Using Functions

1. Code Reusability: Write once, use multiple times.


2. Modularity: Divides the program into logical sections.
3. Ease of Debugging: Problems can be isolated to specific functions.
4. Improved Readability: Focus on a single task within each function.

Structure of a Function

To define a function in Python:

1. Use the def keyword.


2. Follow it with the function name.
3. Add parentheses () which may include parameters.
4. End the header with a colon :
5. Indent the function body (block of statements).

Syntax

def function_name(parameters):

# Statements
return output

Function with no arguments and no return value

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

Function with arguments and no return value

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

Function with arguments and return value

square(8)
square(x)

64
Set of instructions

Example:

def square(x):

return x*x

result = square(8)

print(result)

Output:

64

Functions with multiple arguments :

def sum(x,y):

return x+y

a = int(input("Enter first number = "))

b = int(input("Enter the second number = "))

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

for i in range(1, n + 1):

result = result*i

return result

number = int(input("Enter a non-negative integer: "))

print(f"The factorial of {number} is: {factorial(number)}")

Q. Write a program to print a number pyramid like

12

123

1234

12345

….. using a user defined function

def pyramid(n):

for i in range(1,n+1):

for j in range(i):

print(j,end=" ")

print()

n = int(input("Enter the number of rows for the pyramid: "))

pyramid(n)
Q. Write a program to print median of set of numbers.

def accept(n):

numbers = []

for i in range(n):

num = int(input("Enter number : "))

numbers.append(num)

return numbers

def median(numbers):

numbers.sort()

n = len(numbers)

if n % 2 == 0:

median = (numbers[n // 2 - 1] + numbers[n // 2]) / 2

else:

median = numbers[n // 2]

return median

data = int(input("Enter the number of elements: "))

numbers = accept(data)

median = median(numbers)

print(f"The median is: {median}")


RECURSION

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.

Key Components of 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.

To avoid infinite recursion, here a base case is included:

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)

Stack During Execution


A stack in recursion is like a box that stores each function call.

For every recursive call, a new function frame is pushed onto the stack. Here’s how the stack
evolves:

Step Stack Action Taken


5 hello(1) print("Hello"), calls hello(0)
4 hello(2) print("Hello"), calls hello(1)
3 hello(3) print("Hello"), calls hello(2)
2 hello(4) print("Hello"), calls hello(3)
1 hello(5) print("Hello"), calls hello(4)

Recursion and the Stack

A stack in recursion is like a box that stores each function call.

 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

1. First Call: fun(3)


o
n = 3 → Not the base case.
o
Returns: 1 + fun(2).
2. Second Call: fun(2)
o n = 2 → Not the base case.
o Returns: 1 + fun(1).
3. Third Call: fun(1)
o n = 1 → Not the base case.
o Returns: 1 + fun(0).
4. Fourth Call: fun(0)
o n = 0 → Base case.
o Returns: 1
Returning from Recursive Calls

1. fun(0) (Base Case):


o Returns 1.
2. Returning to fun(1):
o fun(1) computes: 1 + fun(0) = 1 + 1 = 2.
o Returns 2.
3. Returning to fun(2):
o fun(2) computes: 1 + fun(1) = 1 + 2 = 3.
o Returns 3.
4. Returning to fun(3):
o fun(3) computes: 1 + fun(2) = 1 + 3 = 4.
o Returns 4.
Example:

Write a program to compute the factorial of a number using recursive method

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

n = int(input(“Enter a number : “))


print(factorial(4))

Call Stack:

1. First Call: factorial(4)


on = 4 → Not the base case.
oReturns: 4 * factorial(3).
2. Second Call: factorial(3)
o n = 3 → Not the base case.
o Returns: 3 * factorial(2).
3. Third Call: factorial(2)
o n = 2 → Not the base case.
o Returns: 2 * factorial(1).
4. Fourth Call: factorial(1)
o n = 1 → Not the base case.
o Returns: 1 * factorial(0).
5. Fifth Call: factorial(0)
o n = 0 → Base case.
o Returns: 1.

Returning from Recursive Calls

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:

The final result of factorial(4) is 24.

Q. Python program to generate the Fibonacci series of length n using recursion.

def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2) # Recursive formula

num_terms = int(input("Enter the number of terms: "))


for i in range(num_terms):
print(fibonacci(i), end=" ")

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)

n = int(input("Enter the position (n): "))

print(f"The {n}th Fibonacci number is: {fibonacci(n)}")

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.

Key Points to Understand Circularity:

1. Base Case is Missing or Incorrect:


o A recursive function must have a condition that stops further recursive calls. If this is
missing or incorrect, the recursion becomes circular.
2. Circular Calls Between Multiple Functions:
o Circularity can occur when two or more functions call each other in a cycle without a
termination condition.

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.

You might also like