Experiment Number: 01
Title / Aim:
To write a program to demonstrate Set functions and operations in Python.
Software Required:
● Software: Python (version 3.x or above)
● Editor / IDE: IDLE, VS Code, or Jupyter Notebook
● Operating System: Windows / Linux
Program:
# Program: Demonstrate Set Functions and Operations in Python
# Creating sets
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print("Set A:", A)
print("Set B:", B)
# Basic set operations
print("\nUnion of A and B:", [Link](B))
print("Intersection of A and B:", [Link](B))
print("Difference of A and B (A - B):", [Link](B))
print("Difference of B and A (B - A):", [Link](A))
print("Symmetric Difference of A and B:", A.symmetric_difference(B))
# Set functions
print("\nLength of Set A:", len(A))
print("Is 3 present in Set A?", 3 in A)
print("Is 9 present in Set B?", 9 in B)
# Add and remove elements
[Link](9)
print("\nAfter adding 9 to Set A:", A)
[Link](1)
print("After removing 1 from Set A:", A)
# Copy and clear functions
C = [Link]()
print("\nCopy of Set A:", C)
[Link]()
print("After clearing Set A:", A)
# Basic set operations
print("\nUnion of A and B:", [Link](B))
print("Intersection of A and B:", [Link](B))
print("Difference of A and B (A - B):", [Link](B))
print("Difference of B and A (B - A):", [Link](A))
print("Symmetric Difference of A and B:", A.symmetric_difference(B))
Python Programming Lab Manual
Subject: Python Programming Session: 2024-27
Code: CSE201 Semester: 2nd
Lab 1: Setting Up Python Environment
Aim
To install and configure the Python interpreter and set up an integrated
development environment (IDE) for writing and executing Python programs.
Software / Tools Required
● Python 3.x (latest version preferred)
● IDE/Text Editor:
a. IDLE (default Python IDE)
b. Visual Studio Code (VS Code)
c. Jupyter Notebook (optional)
● Operating System: Windows/Linux/macOS
● Internet connection (for downloading software)
Procedure:
Step 1. Visit the official Python website: [Link]
Step 2. Click on Downloads → Select your OS → Download Python installer
(latest stable version).
Step 3. Run the installer:
● Important: Check the 'Add Python to PATH' box.
● Click Install Now.
● Wait until setup completes and shows "Setup was successful."
Step 4: Verify the installation:
● Open Command Prompt / Terminal.
Type: python-- version
It should display the installed version (e.g., Python 3.12.1).
Step 5. Install VS Code (if not already):
● Visit [Link]
● Download and install.
Step 6. Open VS Code → Install Python extension (from Microsoft).
Step 7. Set up folder structure:
PythonLab/
└── Week1/
├── [Link]
└── [Link]
Conclusion
In this lab, I installed Python and VS Code on my system. I checked that Python
works using the terminal and wrote a small program to print a message. Now my
setup is ready for coding.
Lab 2: Executing Python Programs in Different Ways
Aim
To explore and practice different ways of writing and running Python code.
Using IDLE (Python’s built-in IDE)
● Open IDLE from the Start Menu.
● Click File → New File → Write code → Save as .py file.
● Click Run → Run Module or press F5.
print("Hello from IDLE!")
Using Command Line / Terminal
Navigate to the folder:
cd PythonLab/Week1
Run Python file:
python [Link]
Step 3.
Using VS Code
● Open VS Code → Open PythonLab/Week1
● Open file → Click the Run button at the top-right or press Ctrl+F5
Using Jupyter Notebook
Install:
pip install notebook
Run:
jupyter notebook
Create a new notebook and write:
print("Hello from Jupyter!")
Conclusion
Today I learned to run Python programs using IDLE, command prompt, VS Code,
and Jupyter. I understood that we can use any of these methods as needed. I liked
using VS Code the most.
Lab 3: Debugging Python Programs
Aim
To learn basic techniques for debugging Python programs and fixing common
errors.
Techniques Used
● Print statements for tracing.
● Try-except blocks for error handling.
● Breakpoints and step-through in VS Code.
Procedure:
Manual Debugging using print()
Write an incorrect code:
x=5
y=0
print("Before division")
print("Result:", x / y) # This causes ZeroDivisionError
print("After division")
Observe:
Before division
ZeroDivisionError: division by zero
Fix
x=5
y=0
print("Before division")
if y != 0:
print("Result:", x / y)
else:
print("Cannot divide by zero!")
print("After division")
2nd way: Try-Except Block
try:
print("Result:", x / y)
except ZeroDivisionError:
print("Error: Division by zero is not allowed!")
3rd way: VS Code Breakpoints
● Click to the left of the line numbers to set a breakpoint.
● Press F5 (Run with Debugging).
● Step through the code and inspect variable values.
Output
Conclusion
In this lab, I learned how to identify and correct errors using print statements,
try-except blocks, and breakpoints in VS Code. Now I know how to stop my
program from crashing and fix mistakes.
Lab 4:
a. Code, Execute, and Debug Programs That Use I/O Statements
Aim:
To write, execute, and debug Python programs that use:
● input() function to take user input
● print() function to display output
● output formatting using print()
Tools Required
● Python 3.x
● VS Code / IDLE / Terminal
Procedure
1. Use input() to accept data from the user (string by default).
2. Convert input to appropriate type if needed (e.g., int, float).
3. Use print() to display messages and results.
4. Apply simple output formatting (e.g., print(f""), .format()).
5. Run and debug the program to ensure no syntax or logic errors.
(a) Use input/output statements
name = input("Enter your name: ")
print("Hello", name)
Output:
Enter your name: Ankit
Hello Ankit
(b) Evaluate expressions and display formatted output
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
sum_ab = a + b
# Using format()
print("The sum of {} and {} is {}".format(a, b, sum_ab))
# Using f-string
print(f"The sum of {a} and {b} is {sum_ab}")
Output:
Enter first number: 10
Enter second number: 20
The sum of 10 and 20 is 30
The sum of 10 and 20 is 30
(c) Input float and print with 2 decimal places
price = float(input("Enter the price: "))
print("Price entered: {:.2f}".format(price))
Output :
Enter the price: 99.4567
Price entered: 99.46
Conclusion:
In this lab, I practiced taking input using input() and displaying output using print()
with formatting options. I debugged small syntax mistakes and understood how
Python handles input and output.
Lab 4:
b. Code, Execute, and Debug Programs That Evaluate Expressions and
Display Formatted Output
Aim:
To write, execute, and debug Python programs that:
● Evaluate arithmetic, relational, logical, and bitwise expressions
● Display results using formatted output
Tools Required
● Python 3.x
● VS Code / IDLE
Procedure
1. Accept input using input() (and typecast as needed).
2. Write and evaluate different types of expressions (arithmetic, comparison,
logical, bitwise).
3. Display the results using print() with format() or f-string.
4. Run and debug any syntax or logic errors.
Code + Output
1. Arithmetic expression and formatted output
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = (a + b) * 2 / 3
print("The evaluated result is {:.2f}".format(result))
print(f"The evaluated result is {result:.2f}")
Output:
Enter first number: 6
Enter second number: 3
The evaluated result is 6.00
The evaluated result is 6.00
2. Comparison and logical expressions
x = int(input("Enter x: "))
y = int(input("Enter y: "))
greater = x > y
both_positive = (x > 0) and (y > 0)
print(f"Is x greater than y?: {greater}")
print(f"Are both numbers positive?: {both_positive}")
Output
Enter x: 7
Enter y: 5
Is x greater than y?: True
Are both numbers positive?: True
Bitwise expression
m = 5 # 0101
n = 3 # 0011
print(f"Bitwise AND of {m} & {n} = {m & n}")
print(f"Bitwise OR of {m} | {n} = {m | n}")
Output
Bitwise AND of 5 & 3 = 1
Bitwise OR of 5 | 3 = 7
Conclusion:
In this lab, I evaluated different expressions (arithmetic, comparison, logical, and
bitwise) and displayed the results using formatted output. I understood how
formatting improves the readability of output.
Lab 4:
C. Code, Execute, and Debug Programs That Evaluate Expressions to
Examine Operator Precedence
Aim:
To write, execute, and debug Python programs that:
● Evaluate expressions with different operators
● Understand how Python applies operator precedence
● Display results to verify the precedence
Tools
● Python 3.x
● VS Code / IDLE
Procedure
1. Accept numeric input using input() (typecast as needed).
2. Write expressions mixing operators (arithmetic, logical, bitwise).
3. Predict and verify results based on operator precedence rules.
4. Display results using formatted output.
Code + Output
Arithmetic operator precedence
a = int(input("Enter value for a: "))
b = int(input("Enter value for b: "))
c = int(input("Enter value for c: "))
result1 = a + b * c
result2 = (a + b) * c
print(f"a + b * c = {result1}") # * has higher precedence
print(f"(a + b) * c = {result2}") # parentheses change precedence
Output
Enter value for a: 2
Enter value for b: 3
Enter value for c: 4
a + b * c = 14
(a + b) * c = 20
Mixed precedence
x=5
y=2
z=3
result = x + y > z * 2
print(f"x + y > z * 2 = {result}")
Output:
x + y > z * 2 = True
# because (x + y) = 7 and (z * 2) = 6 => 7 > 6 => True
Bitwise + arithmetic precedence
m=4
n=1
result = m + n << 1 # << has lower precedence than +
print(f"m + n << 1 = {result}")
Output :
m + n << 1 = 10
# (m + n) = 5, 5 << 1 = 10
Conclusion :
In this lab, I evaluated expressions containing different operators and verified
Python’s operator precedence. I understood how parentheses can change
precedence and affect results.
Lab 5: Identify and Resolve Syntactic and Semantic Issues in the Given Code
Snippet
Aim
To identify and resolve syntactic (syntax mistakes) and semantic (logic mistakes)
issues in Python code that uses input/output, data types, operators, and expressions.
Tools
● Python 3.x
● VS Code / IDLE
Procedure
1. Carefully read the given faulty code.
2. Identify syntax errors (e.g., missing colons, wrong brackets, indentation).
3. Identify semantic errors (e.g., wrong operator use, wrong logic).
4. Correct the errors and test the code.
Code + Output:
Syntax error (missing colon, wrong indent)
a = int(input("Enter a number"))
if a > 0
print("Positive number")
else
print("Non-positive number")
Fixed code
a = int(input("Enter a number: "))
if a > 0:
print("Positive number")
else:
print("Non-positive number")
Semantic error (wrong operator precedence)
x=2
y=3
result = x + y * 2
print("Result is:", result)
Output:
Result is: 10
3: Type mismatch error
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
print("Sum is:", num1 + num2)
Output:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("Sum is:", num1 + num2)
Conclusion
In this lab, I learned how to spot and correct syntax errors like missing colons,
wrong indentation, and wrong input type. I also corrected semantic errors like
operator precedence and type mismatches. This helped me improve my debugging
skills.
Lab 6: Identify, Code, Execute, and Debug Programs Using Conditional
Statements
Aim
To write, execute, and debug Python programs using:
● if statement
● multiway branching (if-elif-else)
Tools
● Python 3.x
● VS Code / IDLE
Procedure
1. Take input from the user.
2. Write conditions using if, if-else, and if-elif-else.
3. Display messages based on conditions.
4. Debug and correct errors if any occur during execution.
Output
Example 1: Simple if-else
num = int(input("Enter a number: "))
if num > 0:
print("Positive number")
else:
print("Zero or negative number")
Output:
Enter a number: 5
Positive number
Example 2: Multiway branching
marks = int(input("Enter your marks: "))
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: D")
Output:
Enter your marks: 85
Grade: B
Conclusion
In this lab, I wrote programs using conditional statements. I applied if, if-else, and
if-elif-else to handle decision-making in Python programs and debug small
mistakes.
Lab 7: Identify and Resolve Syntactic and Semantic Issues in Conditional
Code
Aim
To identify and fix syntax and logic errors in Python code using conditional
statements.
Tools
● Python 3.x
● VS Code / IDLE
Procedure
1. Review the faulty code provided.
2. Find syntax errors (e.g. missing colon, indentation).
3. Find logic errors (wrong conditions).
4. Correct the code and run it.
Code + Output:
Incorrect code:
n = int(input("Enter number"))
if n > 0
print("Positive")
else
print("Not positive")
Correct:
n = int(input("Enter number: "))
if n > 0:
print("Positive")
else:
print("Not positive")
Example 2 (semantic error)
score = 85
if score > 90:
print("Grade A")
elif score > 75:
print("Grade B")
elif score > 60:
print("Grade C")
else:
print("Grade D")
Correct:
if score >= 90:
print("Grade A")
elif score >= 75:
print("Grade B")
elif score >= 60:
print("Grade C")
else:
print("Grade D")
Conclusion:
In this lab, I identified syntax errors like missing colons and logic errors in
conditions. I fixed the code to get correct output for different cases using
conditional statements.
Lab 8: Code, Execute, and Debug Programs Using Loops
Aim
To write, execute, and debug Python programs using loops (while for), range,
nested loops, and controlling loop execution using break, continue, and pass.
Tools
● Python 3.x
● VS Code / IDLE
Procedure
1. Write programs using for and while loops.
2. Use conditions, nesting, and control statements (break, continue, pass).
3. Run and debug the programs for different inputs.
Code + Output
While loop
Program:
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
For loop with range
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Nested loop + if
for i in range(1, 4):
for j in range(1, 4):
print(i, "*", j, "=", i * j)
Output:
1*1=1
1*2=2
1*3=3
2*1=2
2*2=4
2*3=6
3*1=3
3*2=6
3*3=9
Break, continue, pass
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
for i in range(1, 6):
if i == 4:
break
print(i)
Output:
1
2
3
for i in range(3):
pass # does nothing
print("Pass statement executed")
Output:
Pass statement executed
Conclusion:
In this lab, I practised while loops, nested loops, and controlling loops using break,
continue, and pass. I debugged small mistakes and understood how loops work for
repetitive tasks.
Lab 9: Code, Execute and Debug Programs Using Loops and Conditional
Statements
Aim
To write, execute, and debug Python programs using:
● while loop and for loop
● conditional statements (if, if-else, if-elif-else) inside loops
● loop control statements (break, continue, pass)
Tools
● Python 3.x
● VS Code / IDLE
Procedure
1. Accept input from the user using input().
2. Use loops to repeat execution (e.g., for, while).
3. Apply conditions within loops using if, if-else, etc.
4. Debug and execute the code.
5. Display the output properly.
Code + Output
1. Loop with if-else
for i in range(1, 6):
if i % 2 == 0:
print(f"{i} is Even")
else:
print(f"{i} is Odd")
Output
1 is Odd
2 is Even
3 is Odd
4 is Even
5 is Odd
2: While loop with condition and break
count = 1
while count <= 10:
if count == 6:
break
print("Counting:", count)
count += 1
Output:
Counting: 1
Counting: 2
Counting: 3
Counting: 4
Counting: 5
3: Nested loop with condition (multiplication table)
for i in range(1, 4):
for j in range(1, 4):
if i == j:
print(f"{i} x {j} = {i*j} (Diagonal)")
else:
print(f"{i} x {j} = {i*j}")
4: Using continue to skip iteration
for i in range(1, 6):
if i == 3:
continue
print("Number:", i)
Output:
Number: 1
Number: 2
Number: 4
Number: 5
Conclusion:
In this lab, I wrote programs using loops (for, while) and applied conditional
statements (if-else) inside loops. I also used loop control statements like
break and continue to control execution flow and understood their effect
during debugging.
Lab 10:
Aim
To identify and correct syntactic (writing mistakes) and semantic (logic errors)
issues in loop-based Python code.
Tools
● Python 3.x
● VS Code / IDLE
Procedure
1. Read the given incorrect loop code.
2. Identify syntax errors (e.g., missing colon, wrong indentation).
3. Identify semantic errors (e.g., wrong condition).
4. Fix errors and re-run the program to get the correct output.
Code + Output
Syntax error: missing colon
i=1
while i <= 5
print(i)
i += 1
SyntaxError: expected ':'
Correct code :
i=1
while i <= 5:
print(i)
i += 1
Semantic error: wrong condition causing infinite loop
i=1
while i <= 5:
print(i)
# i += 1 # forgot to increment
Correct code :
i=1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
Conclusion :
In this lab, I identified and corrected syntax errors, such as missing colons, and
semantic errors, including missing increments in loops. I debugged and ran the
program correctly. This helped improve my understanding of loop structures and
logic.
Lab 11:
Aim
To write, execute, and debug Python programs to perform:
● Set operations (union, intersection, difference, etc.)
● Set comprehension
Tools
● Python 3.x
● VS Code / IDLE
Procedure
1. Declare sets and perform operations like union, intersection, and difference.
2. Write set comprehension to generate sets using conditions.
3. Run and debug if any error occurs.
Code + Output
Set operations
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print("Union:", A | B)
print("Intersection:", A & B)
print("Difference A-B:", A - B)
print("Difference B-A:", B - A)
Output:
Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Difference A-B: {1, 2}
Difference B-A: {5, 6}
Set comprehension
squares = {x*x for x in range(1, 6)}
print("Squares set:", squares)
Output:
Squares set: {1, 4, 9, 16, 25}
Conclusion
In this lab, I learned how to declare sets and apply operations like union,
intersection, and difference. I also created sets using comprehension. I debugged
small mistakes and got correct results
Lab 12:
Aim
To write, execute, and debug Python programs to perform:
● Basic tuple operations
● Indexing and slicing
Tools
● Python 3.x
● VS Code / IDLE
Procedure
1. Declare tuples and perform basic operations like length, repetition, and
concatenation.
2. Access tuple elements using indexing.
3. Slice tuples and display results.
Code + Output
Tuple basic operations
t = (10, 20, 30, 40, 50)
print("Length:", len(t))
print("Repetition:", t * 2)
print("Concatenation:", t + (60, 70))
Output:
Length: 5
Repetition: (10, 20, 30, 40, 50, 10, 20, 30, 40, 50)
Concatenation: (10, 20, 30, 40, 50, 60, 70)
Indexing and slicing
print("First element:", t[0])
print("Last element:", t[-1])
print("Slice [1:4]:", t[1:4])
Output:
First element: 10
Last element: 50
Slice [1:4]: (20, 30, 40)
Conclusion
In this lab, I performed tuple operations like length, repetition, and concatenation. I
accessed tuple elements using indexing and slicing. I also fixed small errors in
indexing and got the correct results.
Lab 13:
Aim
To identify and fix syntactic and semantic errors in set and tuple programs.
Tools
● Python 3.x
● VS Code / IDLE
Procedure
1. Check the given code for syntax or logic mistakes.
2. Fix errors and re-run code.
Code + Output
Set syntax error (wrong brackets)
A = [1, 2, 3]
B = {2, 3, 4}
print("Union:", A | B)
Error: List doesn’t support |
Correct code:
A = {1, 2, 3}
B = {2, 3, 4}
print("Union:", A | B)
Tuple semantic error (wrong index)
t = (1, 2, 3)
print(t[3]) # IndexError
Correct code :
t = (1, 2, 3)
print(t[2])
Output: 3
Conclusion:
In this lab, I found syntax and logic mistakes in set and tuple programs. I corrected
bracket errors and incorrect index usage, ensuring the programs ran correctly.
Lab 14:
Aim
To write, execute, and debug Python programs that perform:
● Basic operations on lists
● Indexing and slicing
● List comprehension
Tools
● Python 3.x
● VS Code / IDLE
Procedure
1. Declare and initialize lists.
2. Perform basic operations like append, remove, length, and concatenation.
3. Access elements using indexing and slicing.
4. Apply list comprehension to generate new lists.
5. Run and debug the code if errors occur.
Code + Output :
Basic operations on list
my_list = [10, 20, 30, 40]
my_list.append(50)
print("After append:", my_list)
my_list.remove(20)
print("After remove:", my_list)
print("Length:", len(my_list))
new_list = my_list + [60, 70]
print("Concatenated list:", new_list)
Output:
After append: [10, 20, 30, 40, 50]
After remove: [10, 30, 40, 50]
Length: 4
Concatenated list: [10, 30, 40, 50, 60, 70]
Indexing and slicing
print("First element:", my_list[0])
print("Last element:", my_list[-1])
print("Slice [1:3]:", my_list[1:3])
Output:
First element: 10
Last element: 50
Slice [1:3]: [30, 40]
List comprehension
squares = [x*x for x in range(1, 6)]
print("Squares:", squares)
Output:
Squares: [1, 4, 9, 16, 25]
Conclusion
In this lab, I performed basic list operations like append, remove, length, and
concatenation. I accessed elements using indexing and slicing, and used list
comprehension to create a list of squares. I debugged my code and got the correct
output.
Lab 15:
Aim
To identify and fix syntactic (writing mistakes) and semantic (logic errors) issues
in list-related Python code.
Tools
● Python 3.x
● VS Code / IDLE
Procedure
1. Read the given incorrect code carefully.
2. Identify syntax issues like wrong brackets or missing colons.
3. Identify semantic mistakes like wrong index usage or logic error.
4. Fix and re-run the code.
Code + Output
Syntax error (wrong brackets)
my_list = (1, 2, 3, 4) # used tuple instead of list
my_list.append(5)
print(my_list)
Correct Code:
my_list = [1, 2, 3, 4]
my_list.append(5)
print(my_list)
Output:
[1, 2, 3, 4, 5]
Semantic error (wrong index)
my_list = [10, 20, 30]
print(my_list[3]) # IndexError
Correct code:
print(my_list[2])
Output: 30
Conclusion:
In this lab, I identified syntax errors, such as incorrect brackets (e.g., tuple vs. list),
and semantic errors, including using the wrong index numbers. I corrected these
errors and successfully ran the code.