0% found this document useful (0 votes)
48 views57 pages

Python Unit 1

The document provides a comprehensive overview of Python fundamentals, including its features, data types, control flow, and common operations. It contains structured content with examples and exercises related to lists, sets, dictionaries, and comprehensions, aimed at enhancing programming skills. Additionally, it outlines previous year questions to aid in exam preparation.
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)
48 views57 pages

Python Unit 1

The document provides a comprehensive overview of Python fundamentals, including its features, data types, control flow, and common operations. It contains structured content with examples and exercises related to lists, sets, dictionaries, and comprehensions, aimed at enhancing programming skills. Additionally, it outlines previous year questions to aid in exam preparation.
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/ 57

UNIT

1 Fundamentals of Python
◀ Index ▶
Sr.No. Contents Page No.

1 Introduction 4-5

2 Keywords, Identifiers, Literals, Operators 6-8

3 Data Types- Number, Strings, Lists, Tuples, 9-30


Dictionaries, Sets

4 Understanding Python blocks 31-34

5 Control flow- if, else, elif 35-38

6 Loops- while, for, continue, break 39-42

7 Loop manipulation using pass, continue, break 43-44


and else

8 For loop using ranges, string, list and dictionaries 46-51

9 Programming using Python conditional and


loops block

10 Comprehensions on List, Tuple, Dictionaries 52-56

Click on the page number to directly jump to that page.


Previous Year Question

1.3 Data Types- Number, Strings, Lists, Tuples, Dictionaries, Sets

● Write a Python code for list.


i) create a list of animal consisting of following animals-lion, tiger, cow,
elephant, zebra.
ii) delete zebra from the list.
iii) print all alternate element from the given list
iv) sort the list in descending order.
v) add horse to the list. (APRIL 2025)

● Write a Python program to create a set by accepting n elements


(0-9 or A-Z or a-z) input from the user.
i) display the set elements and length of the set
ii) count number of digits, lowercase letters, uppercase letters in a set.
(APRIL 2025)

● Write a Python program to add two matrices using list. accept elements for
the matrices from the user. (APRIL 2025)

● Create a dictionary containing any 5 elements in the form of key, value pair,
and write python code to perform the following operations on it.
i) To display all the keys.
ii) To add new key value pair.
iii) To delete specific element from the dictionary.
iv) To modify value of a particular key. (NOV 2024)

● Write a program which swap every odd - even position character in the
string (e.g.Input: ‘abcdef’ out put: ‘badcfe’) (NOV 2024)

● d) Write a program to create a set by accepting n elements (0-9 or A-Z


or a-z) input from the user.
i) Display the set elements
ii) Length of set
iii) Count number of digits, lowercase letters, upper case letters in a set.
(NOV 2024)

1.10 Comprehensions on List, Tuple, Dictionaries

● Write a program to create the separate list of digits from the original list
which contains digits & alphabets using list comprehensions.
(Input list = [‘a’, ‘b’, 2,43, ‘Hi’, 900, ‘xyz’], Output list = [2, 43, 900])
(APRIL 2025)

● Write a program to create the separate list by taking the first letter of each
word from the original string using list comprehension.
Input list : [‘Ajay’, ‘Vijay’, ‘Ganesh’, ‘Paresh’, ‘Mahesh’]
Out put list : [‘A’, ‘V’, ‘G’, ‘P’, ‘M’] (NOV 2024)

TopicWise nalysis of Previous Year Questions

April 2025
- List operations (create, delete, alternate elements, sort, add)
- Set operations (input, display, length, count digits/letters)
- Matrix addition using lists
- List comprehension (filter digits)

Nov 2024
- Dictionary operations (display keys, add, delete, modify)
- String manipulation (swap odd-even characters)
- Set operations (same as April 2025, slightly repeated)
- List comprehension (first letter of words)
◀️ Introduction ▶️

1. What is Python?
Python is a high-level, interpreted, general-purpose programming
language. It was developed by Guido van Rossum in 1991.
Python became very popular because of its simplicity and
readability, making it suitable for beginners as well as advanced
users.

Definition:
Python is an interpreted, object-oriented, dynamically typed, and
high-level programming language with built-in data structures.

2. Why Python?
Simple syntax → easy to learn and understand.
Interpreted → no need to compile separately; program runs line by
line.
Cross-platform → runs on Windows, Linux, MacOS.
Open-source → free to use, with huge community support.
Extensive libraries → for machine learning, data science, web
development, networking, etc.

3. Features of Python :
- Easy to Learn and Use
- Syntax is very close to English language.
- Interpreted Language
- Python code is executed line by line using the Python
interpreter.
- Dynamically Typed No need to declare data type explicitly.

Example:
x = 10 # integer
x = “Hello” # string
- Object-Oriented
- Supports class and object concepts.
Portable: Python programs can run on different platforms without
changes.
Extensible: Can use code from other languages like C/C++.
- Large Standard Library:Provides modules for math, string, file
handling, networking, etc.

4. Python Execution Model :

Steps to run a Python program :


- Write program in a .py file.
- Use Python interpreter (python filename.py) to execute.
- Errors (if any) are displayed immediately.

5. First Python Program :

print(“Hello, MCA Students”)

Output : Hello, MCA Students

Exam-Expected Questions For Above Topic


Q1. Explain features of Python.
Q2. Why is Python called interpreted and portable language?
Q3. Write a program to print “Welcome to Python”.
◀️ Keywords, Identifiers, Literals, Operators ▶️

1. Keywords :
Keywords are reserved words that have predefined meaning in
Python.
They cannot be used as identifiers (variable names).
Python has 35+ keywords (may increase with new versions).

Examples:
if, else, while, for, import, return, class, def, try, break, continue,
True, False, None

Code Example:
if True:
print(“This is keyword example”)

2. Identifiers:
Identifiers are names given to variables, functions, classes,
objects, etc.
Rules for identifiers:
Must begin with a letter (a–z, A–Z) or underscore (_).
Cannot start with a digit.
Can contain letters, digits, and underscores.
Case-sensitive (Name and name are different).
Cannot be a keyword.

Valid Identifiers: studentName, _count, total_1


Invalid Identifiers: 1name, for, total$

Example Program:
name = “Chetan”
_rollNo = 25
print(name, _rollNo)
3. Literals:
Literals are constant values used directly in the program.

Types of Literals:

String Literals → “Hello”, ‘Python’


Numeric Literals → 10 (int), 3.14 (float), 2+3j (complex)
Boolean Literals → True, False
Special Literal → None
Collection Literals →
List: [1,2,3]
Tuple: (1,2,3)
Dictionary: {‘a’:1, ‘b’:2}
Set: {1,2,3}

Example Program:
x = 10 # Integer literal
y = 3.14 # Float literal
z = “Python” # String literal
flag = True # Boolean literal
n = None # Special literal

4. Operators
Operators are symbols that perform operations on variables and
values.
Types of Operators in Python:

Arithmetic Operators → + - * / % // **
a, b = 5, 2
print(a+b, a-b, a*b, a/b, a% b, a//b, a**b)
# Output: 7 3 10 2.5 1 2 25

Relational/Comparison Operators → <, >, ==, !=, <=, >=


print(10 > 5) # True
Logical Operators → and, or, not
print(True and False) # False

Assignment Operators → =, +=, -=, *=, /=


x=5
x += 3 # x = 8

Bitwise Operators → &, |, ^, ~, <<, >>


print(5 & 3) # 1

Membership Operators → in, not in


print(“a” in “apple”) # True

Identity Operators → is, is not


a = [1,2,3]
b=a
print(a is b) # True

Exam-Expected Questions For Above Topic :


1. List all Python keywords.
2. Write a program to check whether a given string is a keyword
or not.
3. Show difference between == and is operators.
4. Write a program to count number of valid identifiers from a
given list
◀️ 3 Data Types ▶️

1. Numbers:
Numbers are used to represent numeric values. They are mainly
used in mathematical calculations, measurements, and data
analysis.

Python supports three main types of numbers:

(i) Integer (int):


- Whole numbers without decimal point.
- Can be positive, negative, or zero.
- No limit on size (Python automatically manages big integers).

Example: a = 10
b = -25
c=0

(ii) Floating Point (float):


- Numbers with decimal points.
- Used when precision is required.

Example: x = 3.14
y = -0.5
z = 2.0

(iii) Complex Numbers (complex):


- Numbers with real and imaginary parts.
- Written as a + bj, where a is real, b is imaginary.

Example: c1 = 2 + 3j
c2 = 5 - 4j

Common Number Methods :


abs(x) → absolute value
pow(x, y) → x raised to power y
round(x, n) → round number to n decimal places
int(), float(), complex() → type conversion

Uses of Numbers :
- Storing marks, salary, quantity
- Performing calculations
- Handling scientific data

2. Strings (str):
A string is a sequence of characters enclosed in single (‘ ‘) or
double (“ “) quotes.
Used to store text data (names, addresses, messages, etc.).

Key Points:
- Strings are immutable → once created, cannot be changed.
- Support indexing and slicing.
- Can include letters, numbers, symbols, and spaces.

Example : s = “Python”

Common String Methods:

len(s) → length of string


s.lower() / s.upper() → convert case
s.strip() → remove spaces
s.split() → split into list
s.replace(“old”,”new”) → replace text
s.find(“sub”) → find substring
s.isalpha() / s.isdigit() → check type

Uses of Strings:
- Display messages
- Store user input
- Manipulate text data (search, replace, format)
3. Lists (list)
- A list is an ordered collection of items enclosed in [ ].
- Lists are mutable → can be changed after creation.
Example: animals = [“lion”, “tiger”, “cow”]

Key Points:
- Can store mixed data types.
- Supports indexing, slicing, nesting.
- Useful for storing collections of data.

Common List Methods:


append(x) → add element
insert(i, x) → insert at index
remove(x) → remove element
pop(i) → remove element at index
sort() / reverse() → sort or reverse
count(x) → count occurrences
extend(list2) → add elements from another list

Uses of Lists:
- Store student names, marks, inventory
- Create dynamic collections
- Data processing in programs

4. Tuples (tuple):
A tuple is an ordered collection enclosed in ( ), but it is immutable
(cannot change after creation).
Example: t = (1, 2, 3, “Python”)

Key Points:
- Faster and memory efficient than lists
- Can store mixed data
- Supports indexing and slicing
Common Tuple Methods:
count(x) → number of times element appears
index(x) → find index of element

Uses of Tuples:
- Store fixed data (coordinates, dates, RGB values)
- Used as dictionary keys
- Protect data from modification

5. Dictionaries (dict):
- A dictionary is an unordered collection of key-value pairs
enclosed in { }.
- Keys must be unique, values can be repeated.
- Dictionaries are mutable.
Example: student = {“name”: “Ajay”, “age”: 21, “course”: “MCA”}

Common Dictionary Methods:


keys() → return all keys
values() → return all values
items() → return key-value pairs
get(key) → return value of key
update({key:value}) → update dictionary
pop(key) → remove item
clear() → remove all items

Uses of Dictionaries:
- Store related data (student records, phonebook)
- Fast lookup operations
- Store configurations

6. Sets (set):
A set is an unordered collection of unique items enclosed in { } or
created using set().
Example: s = {1, 2, 3, 4}
Key Points:
- Cannot contain duplicate elements
- Does not maintain order
- Useful for mathematical set operations

Common Set Methods:


add(x) → add element
remove(x) / discard(x) → remove element
union(set2) → combine sets
intersection(set2) → common elements
difference(set2) → elements in one not in other
clear() → remove all elements

Uses of Sets:
- Remove duplicates from list
- Perform set operations
- Membership testing (fast checking)
Q. Write a Python code for list.
i) create a list of animal consisting of following animals-lion, tiger,
cow, elephant, zebra.
ii) delete zebra from the list.
iii) print all alternate element from the given list
iv) sort the list in descending order.
v) add horse to the list. (APRIL 2025)

Ans:
Code:

# Step 1: Create a list of animals


animals = [“lion”, “tiger”, “cow”, “elephant”, “zebra”]
print(“Original List:”, animals)

# Step 2: Delete zebra from the list


animals.remove(“zebra”) # remove() deletes the first
matching value
print(“After deleting zebra:”, animals)

# Step 3: Print all alternate elements (0th, 2nd, 4th, ...)


print(“Alternate elements from list:”, animals[::2])

# Step 4: Sort the list in descending (Z → A)


animals.sort(reverse=True) # reverse=True means descending
order
print(“List in descending order:”, animals)

# Step 5: Add horse to the list


animals.append(“horse”) # append() adds an item at the
end
print(“After adding horse:”, animals)
Output:

Original List: [‘lion’, ‘tiger’, ‘cow’, ‘elephant’, ‘zebra’]


After deleting zebra: [‘lion’, ‘tiger’, ‘cow’, ‘elephant’]
Alternate elements from list: [‘lion’, ‘cow’]
List in descending order: [‘tiger’, ‘lion’, ‘elephant’, ‘cow’]
After adding horse: [‘tiger’, ‘lion’, ‘elephant’, ‘cow’, ‘horse’]

Detailed Explanation:

What is a list ?
- A list holds many values in one variable.
- Written inside square brackets [ ].
- Items are separated by commas.
- Lists are changeable (you can add, delete, or sort items).

Line-by-line understanding

1) Create the list:


animals = [“lion”, “tiger”, “cow”, “elephant”, “zebra”]
print(“Original List:”, animals)

- We made a list called animals.


- It has 5 animal names (each is a string).
- print(...) shows the whole list.

Index positions (for your understanding):

Index Item

0 lion

1 tiger

2 cow

3 elephant

4 zebra
2) Delete “zebra”:
animals.remove(“zebra”)
print(“After deleting zebra:”, animals)

remove(“zebra”) searches the list and deletes the first match.


After this, the list becomes: [‘lion’, ‘tiger’, ‘cow’, ‘elephant’].

3) Print alternate elements:

print(“Alternate elements from list:”, animals[::2])

animals[::2] is called slicing with a step of 2.


It picks items at positions 0, 2, 4, … (every second item).
From [‘lion’, ‘tiger’, ‘cow’, ‘elephant’], it returns [‘lion’, ‘cow’].

4) Sort in descending order (Z → A):


animals.sort(reverse=True)
print(“List in descending order:”, animals)

- .sort() arranges items in place (changes the same list).


- reverse=True means descending (Z to A).
- So [‘lion’, ‘tiger’, ‘cow’, ‘elephant’] becomes
- [‘tiger’, ‘lion’, ‘elephant’, ‘cow’].

5) Add “horse”:
animals.append(“horse”)
print(“After adding horse:”, animals)

- .append(“horse”) adds a new item at the end.


- Final list becomes: [‘tiger’, ‘lion’, ‘elephant’, ‘cow’, ‘horse’].
Q. Write a Python program to create a set by accepting n elements
(0-9 or A-Z or a-z) input from the user.
i) display the set elements and length of the set
ii) count number of digits, lowercase letters, uppercase letters in a
set.
(APRIL 2025)
Ans:

Python Program:

# Step 1: Accept elements from the user and store them in a set
n = int(input(“Enter how many elements you want to add: “))
my_set = set() # create an empty set

for i in range(n):
element = input(f”Enter element {i+1}: “)
my_set.add(element)
# add() puts new element in set

# Step 2: Display set elements and length


print(“\nSet elements:”, my_set)
print(“Length of set:”, len(my_set))
# Step 3: Count digits, lowercase and uppercase letters
digits = 0
lowercase = 0
uppercase = 0
for item in my_set:
if item.isdigit():
# check if element is a digit (0-9)
digits += 1
elif item.islower():
# check if element is lowercase (a-z)
lowercase += 1
elif item.isupper():
# check if element is uppercase (A-Z)
uppercase += 1
print(“\nCount of digits:”, digits)
print(“Count of lowercase letters:”, lowercase)
print(“Count of uppercase letters:”, uppercase)

Output:

Enter how many elements you want to add: 6


Enter element 1: A
Enter element 2: b
Enter element 3: 5
Enter element 4: c
Enter element 5: Z
Enter element 6: 5
Set elements: {‘5’, ‘c’, ‘A’, ‘b’, ‘Z’}
Length of set: 5
Count of digits: 1
Count of lowercase letters: 2
Count of uppercase letters: 2

Detailed Explanation:

1. Creating a Set:
- A set in Python is written inside { }.
- It only stores unique elements (duplicates are not allowed).
- Example: {1, 2, 2, 3} → becomes {1, 2, 3}.
- We used .add() method to insert elements one by one.

2. Displaying Set and Its Length:


print(my_set) shows all elements (order may change because sets
are unordered).
len(my_set) gives the total number of elements in the set.
3. Checking Each Element:

We used three functions:


.isdigit() → checks if character is 0-9.
.islower() → checks if character is a-z.
.isupper() → checks if character is A-Z.

Each time a match is found, the respective counter (digits,


lowercase, uppercase) increases by 1.

4. Example Working:
Input: A, b, 5, c, Z, 5
Set becomes: {‘5’, ‘c’, ‘A’, ‘b’, ‘Z’} (duplicate 5 removed).

- Length = 5
- Digits = 1 (5)
- Lowercase = 2 (b, c)
- Uppercase = 2 (A, Z)

Q. Write a Python program to add two matrices using list. accept
elements for the matrices from the user. (APRIL 2025)

Code:

# Step 1: Accept size of matrix (rows and columns)


rows = int(input(“Enter number of rows: “))
cols = int(input(“Enter number of columns: “))

# Step 2: Create first matrix by taking input from user


print(“Enter elements for first matrix:”)
matrix1 = []
for i in range(rows):
row = []
for j in range(cols):
element = int(input(f”Enter element at position
({i+1},{j+1}): “))
row.append(element)
matrix1.append(row)

# Step 3: Create second matrix by taking input from user


print(“Enter elements for second matrix:”)
matrix2 = []
for i in range(rows):
row = []
for j in range(cols):
element = int(input(f”Enter element at position
({i+1},{j+1}): “))
row.append(element)
matrix2.append(row)

# Step 4: Add two matrices


result = []
for i in range(rows):
row = []
for j in range(cols):
row.append(matrix1[i][j] + matrix2[i][j])
result.append(row)

# Step 5: Display the result


print(“\nFirst Matrix:”)
for r in matrix1:
print(r)

print(“\nSecond Matrix:”)
for r in matrix2:
print(r)

print(“\nResultant Matrix after Addition:”)


for r in result:
print(r)

Sample Input/Output :

Enter number of rows: 2


Enter number of columns: 2

Enter elements for first matrix:


Enter element at position (1,1): 1
Enter element at position (1,2): 2
Enter element at position (2,1): 3
Enter element at position (2,2): 4

Enter elements for second matrix:


Enter element at position (1,1): 5
Enter element at position (1,2): 6
Enter element at position (2,1): 7
Enter element at position (2,2): 8
First Matrix:
[1, 2]
[3, 4]

Second Matrix:
[5, 6]
[7, 8]

Resultant Matrix after Addition:


[6, 8]
[10, 12]

Explanation :
Matrix → A matrix is like a rectangular table of numbers (rows ×
columns).
Example (2×2 matrix):
[1, 2]
[3, 4]

Step 1 → We ask the user how many rows and columns the matrix
should have.
Step 2 & 3 → We use nested loops to take input for each element of
both matrices.
Outer loop → goes through rows.
Inner loop → goes through columns.
Step 4 (Addition) → To add two matrices, we add each element at
the same position.
Formula: result[i][j] = matrix1[i][j] + matrix2[i][j]
Example:
[1, 2] + [5, 6] = [6, 8]
[3, 4] [7, 8] [10, 12]
Step 5 → Finally, we print all matrices clearly.
Q. Create a dictionary containing any 5 elements in the form of key,
value pair, and write python code to perform the following
operations on it.

i) To display all the keys.


ii) To add new key value pair.
iii) To delete specific element from the dictionary.
iv) To modify value of a particular key. (NOV 2024)

Ans:-

Dictionary in Python
- A dictionary is a built-in data type in Python used to store data
in key-value pairs.
- Keys are unique identifiers.
- Values are the data associated with keys.
- Dictionaries are mutable, meaning we can add, remove, or
update items after creation.
- They are enclosed in curly braces { }.

Example:
student = {
“name”: “Ajay”,
“age”: 21,
“course”: “MCA”
}

Here:

“name”, “age”, “course” → keys


“Ajay”, 21, “MCA” → values
Solution:

Code:

# Step 1: Create a dictionary with 5 key-value pairs

student = {
“name”: “Ravi”,
“age”: 20,
“course”: “BCA”,
“roll_no”: 101,
“city”: “Pune”
}

# (i) Display all the keys


print(“All Keys in Dictionary:”)
print(student.keys()) # OR: for k in student: print(k)

# (ii) Add new key-value pair


student[“marks”] = 85
print(“\nAfter Adding New Key-Value Pair:”)
print(student)

# (iii) Delete a specific element from dictionary


del student[“city”]
print(“\nAfter Deleting ‘city’:”)
print(student)

# (iv) Modify value of a particular key


student[“age”] = 21
print(“\nAfter Modifying ‘age’:”)
print(student)
Output:

All Keys in Dictionary:


dict_keys([‘name’, ‘age’, ‘course’, ‘roll_no’, ‘city’])

After Adding New Key-Value Pair:


{‘name’: ‘Ravi’, ‘age’: 20, ‘course’: ‘BCA’, ‘roll_no’: 101, ‘city’: ‘Pune’,
‘marks’: 85}

After Deleting ‘city’:


{‘name’: ‘Ravi’, ‘age’: 20, ‘course’: ‘BCA’, ‘roll_no’: 101, ‘marks’: 85}

After Modifying ‘age’:


{‘name’: ‘Ravi’, ‘age’: 21, ‘course’: ‘BCA’, ‘roll_no’: 101, ‘marks’: 85}
Swapping Characters in a String

- A string in Python is a sequence of characters.


- Strings are immutable, which means we cannot directly change a
character.
- To swap characters, we usually convert the string into a list,
perform the swap, and then join the list back into a string.

Odd-even positions mean:


0-based indexing: index 0 → 1st character (even index in Python)
Swap 0th & 1st, 2nd & 3rd, 4th & 5th, and so on.

Code:
# Input string from user
s = input(“Enter a string: “)

# Convert string to list to allow swapping


s_list = list(s)

# Swap characters at odd-even positions


for i in range(0, len(s_list)-1, 2): # step 2
s_list[i], s_list[i+1] = s_list[i+1], s_list[i]

# Convert list back to string


swapped_string = ‘’.join(s_list)

# Display the output


print(“Swapped string:”, swapped_string)

Explanation:
- Convert string to list
- Strings are immutable, so we use a list for swapping.
- Loop through indices with step 2
- range(0, len(s_list)-1, 2) ensures we get pairs (0&1, 2&3, …).
- Swap characters :
s_list[i], s_list[i+1] = s_list[i+1], s_list[i] swaps each pair.

- Join list to form string :


‘’.join(s_list) converts the list back into a string.

Example:
Input: abcdef
Output: badcfe

Input: python
Output: ypthon
Q. Write a program to create a set by accepting n elements (0-9 or
A-Z or a-z) input from the user.

i) Display the set elements


ii) Length of set
iii) Count number of digits, lowercase letters, upper case
letters in a set.
(NOV 2024)

Ans:-

Sets in Python:
- A set is an unordered collection of unique elements.
- It does not allow duplicates, so if we try to add the same element
twice, it will only store it once.
- Sets are mutable, which means you can add or remove elements.
- Useful operations: add(), remove(), len(), union(), intersection(),
etc.

Code:
# Input: number of elements
n = int(input(“Enter number of elements: “))

# Initialize an empty set


user_set = set()

# Accept n elements from the user


for i in range(n):
element = input(“Enter element (0-9, A-Z, a-z): “)
user_set.add(element) # add element to set

# i) Display the set elements


print(“Set elements:”, user_set)
# ii) Display length of the set
print(“Length of set:”, len(user_set))

# iii) Count digits, lowercase, uppercase letters


digits = 0
lowercase = 0
uppercase = 0

for item in user_set:


if item.isdigit():
digits += 1
elif item.islower():
lowercase += 1
elif item.isupper():
uppercase += 1

print(“Number of digits:”, digits)


print(“Number of lowercase letters:”, lowercase)
print(“Number of uppercase letters:”, uppercase)

Explanation:
1. Create an empty set
- user_set = set() initializes an empty set.

2. Add elements to the set


- user_set.add(element) adds each input element.
- Duplicate elements are automatically ignored.

3. Display the set and its length


- print(user_set) shows all elements (order may vary).
- len(user_set) gives the total number of unique elements.

4. Count digits, lowercase, uppercase


- isdigit() checks if the character is a digit.
- islower() checks if it’s a lowercase letter.
- isupper() checks if it’s an uppercase letter.

Example:
--Input: n = 6
--Elements: a, 5, B, c, 5, D

Output:

Set elements: {‘5’, ‘a’, ‘B’, ‘c’, ‘D’}


Length of set: 5
Number of digits: 1
Number of lowercase letters: 2
Number of uppercase letters: 2
◀️ Understanding Python Blocks ▶️

Definition:

- In Python, a block is a group of logically connected statements


that are executed together.
- In other programming languages like C, C++ or Java, blocks are
defined using { }.
- But in Python, blocks are made using indentation (spaces or tabs
at the beginning of a line).
- Indentation shows which statements belong to the same block.
- Indentation tells the interpreter which statements belong
together.

Characteristics of Python Blocks:

Indentation-based → no curly braces.


Consistent indentation required → usually 4 spaces.
Used in → functions, loops, conditionals, classes.
Nested blocks allowed → block inside another block.
Improves readability → neat, clean, structured.

Where Blocks are Used in Python:

1. Conditional Statements (if, elif, else)

x = 15
if x > 10:
print(“Greater than 10”) # block 1
else:
print(“10 or less”) # block 2

2. Loops (for, while)


for i in range(3):
print(“Hello”) # loop block
print(“Outside Loop”)

3. Functions
def greet():
print(“Welcome Students”)
print(“Python is easy”)
greet()

4. Classes
class Student:
def __init__(self, name):
self.name = name
def show(self):
print(“Name:”, self.name)

5. Nested Blocks (Block inside block)


num = 7
if num > 0:
print(“Positive number”)
if num % 2 == 0:
print(“Even”)
else:
print(“Odd”)

Advantages of Blocks in Python :


- Improves code readability.
- No need for extra symbols → makes code clean.
- Helps in grouping related statements.
- Reduces chances of errors compared to {} mismatches.

Common Errors in Blocks :

1. Inconsistent indentation:
if True:
print(“Hello”)
print(“World”) # Error

2. Missing indentation:
if True:
print(“Hello”) # Error

Example Program:
def check_number(num):
if num > 0:
print(“Positive”)
if num % 2 == 0:
print(“Even”)
else:
print(“Odd”)
else:
print(“Negative or Zero”)

check_number(5)

Output:
Positive
Odd

Expected Questions :

Theory Questions:
1. Define Python blocks. How are they different from blocks in C/
C++?
2. Explain the importance of indentation in Python.
3. List uses of blocks in Python with examples.
4. What are nested blocks? Give example.
5. Explain errors caused by wrong indentation.
Practical Questions:
1. Write a Python program using if-else to check whether a number
is even or odd.
2. Write a Python program to display the table of a number using a
block inside a loop.
3. Write a program with nested blocks to check whether a number
is positive and divisible by 5.
◀️ Control Flow : if, else, elif ▶️

1. If Statement:
Purpose:
- The if statement is used to execute a block of code only when a
condition is true.
- If the condition is false, the block is skipped.

Syntax:
if condition:
# code to execute if condition is true

Key Point:
If the condition is false → code will not run.

Example:
num = 10
if num > 0:
print(“Number is Positive”)

Output: Number is Positive

2. If-Else Statement:

Purpose:
- To choose between two different code blocks.
- If condition is true → execute if block.
- If condition is false → execute else block.

Syntax:
if condition:
# code when condition is true
else:
# code when condition is false
Key Point:
One block will always execute.

Example:
num = 7
if num % 2 == 0:
print(“Even Number”)
else:
print(“Odd Number”)

Output: Odd Number

3. If-Elif-Else Statement:

Purpose:
- Used when there are multiple conditions to check.
- First if condition is checked.
- If false → next elif condition is checked.
- If none are true → else block runs.

Syntax:
if condition1:
# code if condition1 is true
elif condition2:
# code if condition2 is true
elif condition3:
# code if condition3 is true
else:
# code if none conditions are true

Key Point:
- Only one block executes — the first true condition.
- The else block is optional and works as a fallback.
Example:

marks = 72
if marks >= 90:
print(“Grade: A”)
elif marks >= 75:
print(“Grade: B”)
elif marks >= 50:
print(“Grade: C”)
else:
print(“Grade: Fail”)

Output: Grade: B

Solved Examples :

Q1. Check if a number is even or odd (if-else)

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


if num % 2 == 0:
print(“Even Number”)
else:
print(“Odd Number”)

Output (if input = 9): Odd Number

Q2. Display multiplication table using a block inside a loop


(if inside loop)

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


print(“Multiplication Table of”, num)
for i in range(1, 11):
print(num, “x”, i, “=”, num * i)
Output (if input = 5):
Multiplication Table of 5
5x1=5
5 x 2 = 10
...
5 x 10 = 50

Q3. Nested if: Check if number is positive and divisible by 5

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


if num > 0:
if num % 5 == 0:
print(“Number is Positive and Divisible by 5”)
else:
print(“Number is Positive but not Divisible by 5”)
else:
print(“Number is not Positive”)

Output (if input = 25):


Number is Positive and Divisible by 5
◀️ Loops : while, for, continue, break ▶️

loops lecture :

continue, break lecture :

Introduction to Loops

- In programming, there are situations where we need to execute a


set of instructions multiple times. Instead
of writing the same code again and again, we use loops.
- A loop is a control structure that allows a block of code to be
executed repeatedly, based on a condition.
- This helps in reducing redundancy, improving efficiency, and
making the program easier to understand and maintain.

Python mainly provides two types of loops:


1. while loop
2. for loop
- Inside loops, we can use break and continue to control the flow.

While Loop :
- Executes a block of code as long as the condition is True.
- Condition is checked before each iteration.

Syntax:
while condition:
# code block

Example:
i = 1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5

For Loop :
- Used for iterating over a sequence (list, tuple, string, or range).
- Executes the block once for each item in the sequence.

Syntax:
for variable in sequence:
# code block

Example:
for i in range(1, 6):
print(i)

Output:
1
2
3
4
5

Break Statement :
- The break statement is used to immediately terminate a loop,
regardless of whether the loop’s condition is
still true.
- Useful for stopping a loop early based on a specific condition.
Example 1: Exiting a for loop when a number exceeds 50
for i in range(1, 101):
if i > 50:
break
print(i, end=” “)

Output:
1 2 3 ... 49 50

Example 2: Terminating an infinite while loop when user enters “Q”

while True:
user_input = input(“Enter a letter (Q to quit): “)
if user_input.upper() == “Q”:
break
print(“You entered:”, user_input)

Sample Output:
Enter a letter (Q to quit): a
You entered: a
Enter a letter (Q to quit): Q

Continue Statement :
- The continue statement is used to skip the current iteration of a
loop and move to the next one.
- Code after continue in that iteration is not executed, but the loop
continues.

Example 1: Skipping specific numbers (2 and 4)


for i in range(1, 6):
if i == 2 or i == 4:
continue
print(i, end=” ”)
Output:
135

Example 2: Printing only even numbers from 1 to 10


for i in range(1, 11):
if i % 2 != 0:
continue
print(i, end=” ”)
Output:
2 4 6 8 10

Important conclusions
while loop → Runs until condition is False.
for loop → Iterates over a sequence.
break → Terminates the loop immediately.
continue → Skips current iteration, continues with the next.

Expected Exam Questions

1. Write a Python program to print numbers from 1 to 10 using a


while loop.
2. Write a program to print the multiplication table of a number
using a for loop.
3. Write a program to print numbers from 1 to 100, but stop when
the number exceeds 50 (use break).
4. Write a program to accept user input in a loop, but stop when
the input is “Q”.
5. Write a program to print only even numbers from 1 to 20 using
continue.
6. Write a program to skip printing numbers 5 and 10 from 1 to 15
using continue.
◀️ Loop Manipulation using pass and else ▶️

Introduction :
In Python, loops allow repeated execution of code. Sometimes, we
need special control inside loops. Python provides pass and else to
handle these cases efficiently.

1. pass Statement:
Purpose: pass is a placeholder that does nothing.
It is used when a statement is syntactically required, but you don’t
want to execute any code yet.
Helps in writing incomplete loops or functions without causing
syntax errors.

Syntax: pass

Example: Using pass in a loop

for i in range(1, 6):


if i == 3:
pass # placeholder, does nothing
else:
print(i)

Output:
1
2
4
5

Key Points:
pass does not affect loop execution.
It is commonly used as a temporary placeholder in loops or
functions.
2. else with Loops:
Purpose: Executes a block of code only if the loop finishes normally
(without a break).
Can be used with for and while loops.
Useful in situations like searching for an item in a loop—the else
executes if the item is not found.

Syntax:
for variable in sequence:
# loop code
else:
# executes if loop completes normally

Example 1: Loop completes normally

for i in range(1, 4):


print(i)
else:
print(“Loop completed successfully”)

Output:
1
2
3
Loop completed successfully

Example 2: Loop with break (else does not execute)

for i in range(1, 6):


if i == 3:
break
print(i)
else:
print(“Loop completed”)
# Skipped because loop was broken
Output:
1
2

Statement Purpose Effect in Loop

pass Placeholder Does nothing, avoids syn-


tax error

else Execute if loop Runs only if loop is not


finishes normally terminated by break

Expected Exam Questions


1. Write a Python program using pass inside a loop as a
placeholder.
2. Write a program using for-else to print “Not Found” if a specific
item is not in a list.
3. Explain the difference between pass and else with examples.
◀️ For loop using ranges, string, list and dictionaries ▶️

- A for loop in Python is used to repeat a block of code for each


item in a sequence.
- A sequence can be numbers, letters in a string, elements in a list,
or keys/values in a dictionary.
- Instead of writing the same code many times, the for loop
automatically goes through each item one by one
and executes the code.

1. For Loop Using range()


- The range() function generates a sequence of numbers. It is
commonly used when you want to repeat something a certain
number of times.
- You can also start from any number, end at any number, and even
choose the step to increase or decrease the numbers.
- It helps the for loop know how many times to run and which
numbers to use during each repetition..

Syntax:
range(stop) # 0 to stop-1
range(start, stop) # start to stop-1
range(start, stop, step) # start to stop-1 with step increment

Examples:
# Print numbers 0 to 4
for i in range(5):
print(i)

Output:
0
1
2
3
4
# Print odd numbers from 1 to 9
for i in range(1, 10, 2):
print(i)

Output:
1
3
5
7
9

Important Notes:
- range() does not include the stop value.
- Default start = 0, default step = 1.
- You can use it to control loops with numbers easily.

2. For Loop Using Strings


A string is a sequence of characters, like a word or sentence.
A for loop can go through each character one by one and perform
an action on it, such as printing or checking it.

Example:
word = “PYTHON”
for ch in word:
print(ch)

Output:
P
Y
T
H
O
N
Explanation for Beginners:
- The loop picks the first letter P and prints it.
- Then it moves to the next letter Y, and so on until the end.
- Useful for checking, counting, or modifying each character in a
string.

3. For Loop Using Lists


- A list is a collection of items stored in a specific order.
- The items can be numbers, text, or a mix of both.
- A for loop can go through each item in the list one by one to
perform an action on it, like printing or
modifying it.

Example: – Basic iteration :


fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
print(fruit)

Output:
apple
banana
cherry

Example – Using index with list:


for i in range(len(fruits)):
print(i, fruits[i])

Output:
0 apple
1 banana
2 cherry

Explanation for Beginners:


- len(fruits) gives the number of items in the list.
- range(len(fruits)) creates numbers from 0 to last index.
- fruits[i] gives the item at index i.

4. For Loop Using Dictionaries


- A dictionary stores information in pairs, called key → value.
- The key is like a name, and the value is the information for that
name.
- A for loop can go through the dictionary to access keys, values,
or both and work with them easily.

Example dictionary:
student = {“name”: “Om”, “age”: 21, “branch”: “MCA”}

You can loop through:

Keys only:

for key in student:


print(key)

Output:
name
age
branch

Values only:

for value in student.values():


print(value)

Output:
Om
21
MCA
Keys and values together:

for key, value in student.items():


print(key, “:”, value)

Output:
name : Om
age : 21
branch : MCA

Explanation for Beginners:

.keys() → looks at keys like name, age.


.values() → looks at values like Om, 21.
.items() → lets you use both key and value at the same time.

Sequence Type Example Sequence How For Loop


Works
Range range(1,6) Prints numbers 1,
2, 3, 4, 5
String “PYTHON” Prints each letter:
P, Y, T, H, O, N
List [“apple”,”banana”] Prints each item:
apple, banana
Dictionary {“a”:1,”b”:2} Prints keys, values,
or both key-value

Full Example Program

# Range
for i in range(1, 4):
print(“Range:”, i)
# String
for ch in “Hello”:
print(“Char:”, ch)

# List
numbers = [10, 20, 30]
for num in numbers:
print(“List:”, num)

# Dictionary
student = {“name”: “Om”, “age”: 21}
for key, value in student.items():
print(“Dict:”, key, “->”, value)

Output:
Range: 1
Range: 2
Range: 3
Char: H
Char: e
Char: l
Char: l
Char: o
List: 10
List: 20
List: 30
Dict: name -> Om
Dict: age -> 21

Expected Exam Questions :


1. Print all characters of a string using for.
2. Print all elements of a list with their index.
3. Print key-value pairs of a dictionary using for.
4. Print numbers from 10 to 1 using range().
◀️ Comprehensions on List, Tuple, Dictionaries ▶️

Comprehensions in Python are a concise way to create new


collections (lists, tuples, dictionaries) from existing ones. Instead of
using multiple lines with loops and conditions, you can do it in one
readable line.

1. List Comprehension :
Purpose: Create a new list from an existing iterable, optionally
applying a condition or transformation.

Syntax:
new_list = [expression for item in iterable if condition]

expression → the value to include in the new list (can be


transformed, e.g., x*2)
item → element from the iterable
iterable → the original list, string, or range
if condition → optional filter to include only certain elements

Key points:
- Efficient and readable
- Can replace a normal for loop

Example List Comprehension :

# Original list :
numbers = [1, 2, 3, 4, 5]
# Create a new list with squares of numbers
squares = [x**2 for x in numbers]
print(squares)

Output:
[1, 4, 9, 16, 25]

2. Tuple Comprehension
- Python does not have a direct tuple comprehension, but you can
use a generator expression and convert it to
a tuple.
- Generator expressions look like list comprehensions but use
parentheses () instead of square brackets [].

Syntax:
new_tuple = tuple(expression for item in iterable if condition)

Key points:
- Creates a tuple in one line
- Memory-efficient when using generator expression

Example Tuple Comprehension :

# Original list
numbers = [1, 2, 3, 4, 5]
# Create a tuple of squares
squares_tuple = tuple(x**2 for x in numbers)
print(squares_tuple)

Output:
(1, 4, 9, 16, 25)

3. Dictionary Comprehension
Purpose: Create dictionaries easily from iterables.
Syntax:
new_dict = {key_expression: value_expression for item in iterable if
condition}

key_expression → the key for each dictionary entry


value_expression → the value corresponding to the key
item → element from the iterable
if condition → optional filter
Key points:
- Can map values to keys directly
- Can include conditions for selective inclusion

Example Dictionary Comprehension

# Original list
numbers = [1, 2, 3, 4]
# Create dictionary with number as key and square as value
squares_dict = {x: x**2 for x in numbers}
print(squares_dict)

Output:
{1: 1, 2: 4, 3: 9, 4: 16}

Advantages of Comprehensions :

Concise code – reduces multiple lines into one


Readable – easy to understand at a glance
Efficient – faster than standard loops
Flexible – works with lists, tuples, dictionaries, strings, and sets
Q. Write a program to create the separate list of digits from the
original list which contains digits & alphabets using list
comprehensions.
(Input list = [‘a’, ‘b’, 2,43, ‘Hi’, 900, ‘xyz’], Output list = [2, 43, 900])

(APRIL 2025)
Ans:-

Step 1: Identify digits


We can use the isinstance() function to check if an item is an
integer (int).

Step 2: Apply list comprehension

# Program

original_list = [‘a’, ‘b’, 2, 43, ‘Hi’, 900, ‘xyz’]


# List comprehension to filter only integers
digits_list = [item for item in original_list if
isinstance(item, int)]
print(digits_list)

Output:
[2, 43, 900]

Explanation:
- for item in original_list → iterates through each element of the
list.
- if isinstance(item, int) → checks whether the element is an
integer.
- Only the elements that satisfy the condition are added to the new
list digits_list.
Q. Write a program to create the separate list by taking the first
letter of each word from the original string using list
comprehension.
Input list : [‘Ajay’, ‘Vijay’, ‘Ganesh’, ‘Paresh’, ‘Mahesh’]
Output list : [‘A’, ‘V’, ‘G’, ‘P’, ‘M’]
(NOV 2024)

Ans:-

Step 1: Iterate through each name


We will use a for loop inside list comprehension to go through each
element.

-Step 2: Extract the first character


Use name[0] to take the first letter of each string.

# Programs

names_list = [‘Ajay’, ‘Vijay’, ‘Ganesh’, ‘Paresh’, ‘Mahesh’]


# List comprehension to get first letters of each name
first_letters = [name[0] for name in names_list]
print(first_letters)

Output:
[‘A’, ‘V’, ‘G’, ‘P’, ‘M’]

Explanation:
1. for name in names_list → Iterates through each element (name) in
the list.
2. name[0] → Takes the first character of each name.
3. [name[0] ...] → Collects all first letters into a new list called first_
letters

You might also like