Python Unit 1
Python Unit 1
1 Fundamentals of Python
◀ Index ▶
Sr.No. Contents Page No.
1 Introduction 4-5
● 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)
● 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)
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.
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.
Example Program:
name = “Chetan”
_rollNo = 25
print(name, _rollNo)
3. Literals:
Literals are constant values used directly in the program.
Types of Literals:
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
1. Numbers:
Numbers are used to represent numeric values. They are mainly
used in mathematical calculations, measurements, and data
analysis.
Example: a = 10
b = -25
c=0
Example: x = 3.14
y = -0.5
z = 2.0
Example: c1 = 2 + 3j
c2 = 5 - 4j
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”
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.
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”}
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
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:
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
Index Item
0 lion
1 tiger
2 cow
3 elephant
4 zebra
2) Delete “zebra”:
animals.remove(“zebra”)
print(“After deleting zebra:”, animals)
5) Add “horse”:
animals.append(“horse”)
print(“After adding horse:”, animals)
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
Output:
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.
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:
print(“\nSecond Matrix:”)
for r in matrix2:
print(r)
Sample Input/Output :
Second Matrix:
[5, 6]
[7, 8]
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.
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:
Code:
student = {
“name”: “Ravi”,
“age”: 20,
“course”: “BCA”,
“roll_no”: 101,
“city”: “Pune”
}
Code:
# Input string from user
s = input(“Enter a 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.
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.
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: “))
Explanation:
1. Create an empty set
- user_set = set() initializes an empty set.
Example:
--Input: n = 6
--Elements: a, 5, B, c, 5, D
Output:
Definition:
x = 15
if x > 10:
print(“Greater than 10”) # block 1
else:
print(“10 or less”) # block 2
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)
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”)
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”)
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 :
loops lecture :
Introduction to Loops
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
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.
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.
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
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
Output:
1
2
3
Loop completed successfully
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.
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.
Output:
apple
banana
cherry
Output:
0 apple
1 banana
2 cherry
Example dictionary:
student = {“name”: “Om”, “age”: 21, “branch”: “MCA”}
Keys only:
Output:
name
age
branch
Values only:
Output:
Om
21
MCA
Keys and values together:
Output:
name : Om
age : 21
branch : MCA
# 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
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]
Key points:
- Efficient and readable
- Can replace a normal for loop
# 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
# 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}
# 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 :
# Program
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:-
# Programs
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