Python Programming Experiment List
(BCC302 / BCC402)
EXP 1: Basics of Python
Write a program to demonstrate basic variable declarations and data types (int, float, bool,
string).
Use operators (+, -, *, /, %, //, **) and print results.
EXP 2: Control Flow Statements
Implement a Python program using if, elif, and else statements.
Write a program to check whether a number is prime or not using loops and conditionals.
EXP 3: Loops and Iterations
Program using for and while loops to print patterns (e.g., pyramid, number patterns).
Use break, continue, and pass statements effectively in loops.
EXP 4: Working with Strings
Write programs to perform string slicing, concatenation, comparison, and in-built functions
like .upper(), .find(), .replace().
EXP 5: List Operations
Create, access, slice, and modify lists.
Use in-built functions like append(), extend(), remove(), sort().
EXP 6: Tuple and Dictionary Operations
Demonstrate tuple creation and immutability.
Perform basic dictionary operations: add, remove, update key-value pairs.
EXP 7: User-defined Functions
Write functions with parameters and return values.
Use default and keyword arguments. Demonstrate *args and **kwargs.
EXP 8: File Handling
Read from and write to text files using read(), readline(), write(), and writelines().
Use with statement for file operations and seek() to manipulate the file pointer.
EXP 9: Working with Python Packages
Use NumPy to perform array operations.
Use Pandas to read .csv files and perform basic data analysis (mean, max, min).
Use Matplotlib to plot simple graphs.
EXP 10: GUI Programming with Tkinter
Create a basic GUI window using Tkinter.
Add widgets like Label, Button, Entry; handle basic events (e.g., button click).
EXP 11: Mini Project / Integration Task
Develop a small application integrating file handling, functions, and a GUI (e.g., student
record system, calculator, simple text editor).
EXP 1: Basics of Python
Write a program to demonstrate basic variable declarations and data types (int, float, bool,
string).
Use operators (+, -, *, /, %, //, **) and print results.
# Variable Declarations and Data Types
int_var = 10 # Integer
float_var = 3.14 # Float
bool_var = True # Boolean
string_var = "Hello, Python" # String
# Displaying the variables and their types
print("Integer:", int_var, "| Type:", type(int_var))
print("Float:", float_var, "| Type:", type(float_var))
print("Boolean:", bool_var, "| Type:", type(bool_var))
print("String:", string_var, "| Type:", type(string_var))
# Basic Arithmetic Operators
a = 20
b=7
print("\nArithmetic Operations:")
print("a + b =", a + b)
print("a - b =", a - b)
print("a * b =", a * b)
print("a / b =", a / b)
print("a % b =", a % b)
print("a // b =", a // b)
print("a ** b =", a ** b)
# Comparison Operators
print("\nComparison Operations:")
print("a == b:", a == b)
print("a != b:", a != b)
print("a > b:", a > b)
print("a < b:", a < b)
print("a >= b:", a >= b)
print("a <= b:", a <= b)
Output-
Integer: 10 | Type: <class 'int'>
Float: 3.14 | Type: <class 'float'>
Boolean: True | Type: <class 'bool'>
String: Hello, Python | Type: <class 'str'>
Arithmetic Operations:
a + b = 27
a - b = 13
a * b = 140
a / b = 2.857142857142857
a%b=6
a // b = 2
a ** b = 1280000000
Comparison Operations:
a == b: False
a != b: True
a > b: True
a < b: False
a >= b: True
a <= b: False
EXP 2: Control Flow Statements
Implement a Python program using if, elif, and else statements.
Write a program to check whether a number is prime or not using loops and conditionals.
# Program to demonstrate if, elif, and else
marks = int(input("Enter your marks: "))
if marks >= 90:
print("Grade: A+")
elif marks >= 75:
print("Grade: A")
elif marks >= 60:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
else:
print("Grade: F (Fail)")
# Program to check if a number is prime
num = int(input("Enter a number: "))
if num <= 1:
print(num, "is not a prime number")
else:
is_prime = True
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
Sample Output
Input:
Enter a number: 7
Output:
7 is a prime number
Input:
Enter your marks: 78
Output:
Grade: A
EXP 3: Loops and Iterations
Program using for and while loops to print patterns (e.g., pyramid, number patterns).
Use break, continue, and pass statements effectively in loops.
# Print a right-angled triangle pattern of stars
rows = 5
for i in range(1, rows + 1):
print('*' * i)
Output-
*
**
***
****
*****
# Print numbers from 1 to 5 using a while loop
i=1
while i <= 5:
print(i)
i += 1
Output
1
2
3
4
5
# Demonstrating break, continue, and pass
for i in range(1, 10):
if i == 3:
continue # Skip when i is 3
elif i == 7:
break # Stop the loop when i is 7
elif i == 5:
pass # Do nothing, just a placeholder
print("i =", i)
EXP 4: Working with Strings
Write programs to perform string slicing, concatenation, comparison, and in-built functions
like .upper(), .find(), .replace().
# Define two strings
string1 = "Hello"
string2 = "World"
# Display original strings
print("Original Strings:")
print("String 1:", string1)
print("String 2:", string2)
# 1. String Slicing
print("\n1. String Slicing:")
print("First 3 characters of String 1:", string1[:3])
print("Last 2 characters of String 2:", string2[-2:])
# 2. String Concatenation
print("\n2. String Concatenation:")
concatenated = string1 + " " + string2
print("Concatenated String:", concatenated)
# 3. String Comparison
print("\n3. String Comparison:")
if string1 == string2:
print("String 1 and String 2 are equal.")
else:
print("String 1 and String 2 are not equal.")
# 4. Using in-built string functions
# a. .upper()
print("\n4a. Using .upper():")
print("String 1 in uppercase:", string1.upper())
# b. .find()
print("\n4b. Using .find():")
position = concatenated.find("World")
print("Position of 'World' in concatenated string:", position)
# c. .replace()
print("\n4c. Using .replace():")
replaced_string = concatenated.replace("World", "Python")
print("After replacing 'World' with 'Python':", replaced_string)
Original Strings:
String 1: Hello
String 2: World
1. String Slicing:
First 3 characters of String 1: Hel
Last 2 characters of String 2: ld
2. String Concatenation:
Concatenated String: Hello World
3. String Comparison:
String 1 and String 2 are not equal.
4a. Using .upper():
String 1 in uppercase: HELLO
4b. Using .find():
Position of 'World' in concatenated string: 6
4c. Using .replace():
After replacing 'World' with 'Python': Hello Python
EXP 5: List Operations
Create, access, slice, and modify lists.
Use in-built functions like append(), extend(), remove(), sort().
# 1. Create a List
my_list = [10, 20, 30, 40, 50]
print("Original List:", my_list)
# 2. Access Elements
print("\n2. Access Elements:")
print("First Element:", my_list[0])
print("Last Element:", my_list[-1])
# 3. Slice the List
print("\n3. Slice the List:")
print("Elements from index 1 to 3:", my_list[1:4])
# 4. Modify the List
print("\n4. Modify the List:")
my_list[2] = 35
print("After modifying index 2:", my_list)
# 5. In-built Functions
# a. append()
print("\n5a. append():")
my_list.append(60)
print("After appending 60:", my_list)
# b. extend()
print("\n5b. extend():")
my_list.extend([70, 80])
print("After extending with [70, 80]:", my_list)
# c. remove()
print("\n5c. remove():")
my_list.remove(20)
print("After removing 20:", my_list)
# d. sort()
print("\n5d. sort():")
my_list.sort()
print("After sorting the list:", my_list)
Original List: [10, 20, 30, 40, 50]
2. Access Elements:
First Element: 10
Last Element: 50
3. Slice the List:
Elements from index 1 to 3: [20, 30, 40]
4. Modify the List:
After modifying index 2: [10, 20, 35, 40, 50]
5a. append():
After appending 60: [10, 20, 35, 40, 50, 60]
5b. extend():
After extending with [70, 80]: [10, 20, 35, 40, 50, 60, 70, 80]
5c. remove():
After removing 20: [10, 35, 40, 50, 60, 70, 80]
5d. sort():
After sorting the list: [10, 35, 40, 50, 60, 70, 80]
EXP 6: Tuple and Dictionary Operations
Demonstrate tuple creation and immutability.
Perform basic dictionary operations: add, remove, update key-value pairs.
# 1. Tuple Creation
my_tuple = (1, 2, 3, 4, 5)
print("1. Tuple Creation:")
print("Original Tuple:", my_tuple)
# 2. Tuple Immutability
print("\n2. Tuple Immutability:")
try:
my_tuple[1] = 10
except TypeError as e:
print("Error: Tuples are immutable -", e)
# 3. Dictionary Creation
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
print("\n3. Dictionary Creation:")
print("Original Dictionary:", my_dict)
# 4. Add Key-Value Pair
print("\n4. Add Key-Value Pair:")
my_dict["country"] = "USA"
print("After adding 'country':", my_dict)
# 5. Update Value
print("\n5. Update Value:")
my_dict["age"] = 26
print("After updating 'age':", my_dict)
# 6. Remove Key-Value Pair
print("\n6. Remove Key-Value Pair:")
removed_value = my_dict.pop("city")
print(f"Removed 'city' (value was '{removed_value}'), updated dictionary:", my_dict)
1. Tuple Creation:
Original Tuple: (1, 2, 3, 4, 5)
2. Tuple Immutability:
Error: Tuples are immutable - 'tuple' object does not support item assignment
3. Dictionary Creation:
Original Dictionary: {'name': 'Alice', 'age': 25, 'city': 'New York'}
4. Add Key-Value Pair:
After adding 'country': {'name': 'Alice', 'age': 25, 'city': 'New York', 'country': 'USA'}
5. Update Value:
After updating 'age': {'name': 'Alice', 'age': 26, 'city': 'New York', 'country': 'USA'}
6. Remove Key-Value Pair:
Removed 'city' (value was 'New York'), updated dictionary: {'name': 'Alice', 'age': 26, 'country':
'USA'}
EXP 7: User-defined Functions
Write functions with parameters and return values.
Use default and keyword arguments. Demonstrate *args and **kwargs.
# 1. Function with parameters and return value
def add(a, b):
return a + b
print("1. Function with Parameters and Return Value:")
result = add(5, 3)
print("add(5, 3) =", result)
# 2. Function with default arguments
def greet(name="User"):
print(f"Hello, {name}!")
print("\n2. Function with Default Argument:")
greet()
greet("Alice")
# 3. Function with keyword arguments
def introduce(name, age, city):
print(f"{name} is {age} years old and lives in {city}.")
print("\n3. Function with Keyword Arguments:")
introduce(age=25, name="Bob", city="Delhi")
# 4. Function with *args (variable-length positional arguments)
def sum_all(*args):
print("Arguments received:", args)
return sum(args)
print("\n4. Function with *args:")
total = sum_all(1, 2, 3, 4, 5)
print("Sum =", total)
1. Function with Parameters and Return Value:
add(5, 3) = 8
2. Function with Default Argument:
Hello, User!
Hello, Alice!
3. Function with Keyword Arguments:
Bob is 25 years old and lives in Delhi.
4. Function with *args:
Arguments received: (1, 2, 3, 4, 5)
Sum = 15
5. Function with **kwargs:
Keyword Arguments received: {'name': 'Charlie', 'age': 30, 'city': 'Mumbai'}
name: Charlie
age: 30
city: Mumbai
EXP 8: File Handling
Read from and write to text files using read(), readline(), write(), and writelines().
Use with statement for file operations and seek() to manipulate the file pointer.
# Sample text to write
lines = ["Hello, this is line 1.\n", "This is line 2.\n", "And this is line 3.\n"]
# 1. Writing to a file using write() and writelines()
with open("sample.txt", "w") as file:
file.write("First line written using write().\n")
file.writelines(lines)
print("File written successfully.")
# 2. Reading from the file using read()
print("\n2. Reading the entire file content using read():")
with open("sample.txt", "r") as file:
content = file.read()
print(content)
# 3. Reading line-by-line using readline()
print("3. Reading line-by-line using readline():")
with open("sample.txt", "r") as file:
print(file.readline().strip()) # First line
print(file.readline().strip()) # Second line
# 4. Using seek() to move the file pointer
print("\n4. Using seek() to rewind and read again:")
with open("sample.txt", "r") as file:
file.seek(0) # Move pointer to beginning
print("After seek(0):", file.readline().strip())
# 5. Using with statement ensures file is auto-closed
print("\n5. File was automatically closed after using 'with' block.")
File written successfully.
2. Reading the entire file content using read():
First line written using write().
Hello, this is line 1.
This is line 2.
And this is line 3.
3. Reading line-by-line using readline():
First line written using write().
Hello, this is line 1.
4. Using seek() to rewind and read again:
After seek(0): First line written using write().
5. File was automatically closed after using 'with' block.
EXP 9: Working with Python Packages
Use NumPy to perform array operations.
Use Pandas to read .csv files and perform basic data analysis (mean, max, min).
Use Matplotlib to plot simple graphs.
1. NumPy – Array Operations
import numpy as np
print("1. NumPy Array Operations:")
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([10, 20, 30, 40, 50])
print("Array 1:", arr1)
print("Array 2:", arr2)
print("Sum:", arr1 + arr2)
print("Product:", arr1 * arr2)
print("Mean of Array 1:", np.mean(arr1))
print("Max of Array 2:", np.max(arr2))
2. Pandas – CSV Reading & Analysis
Name,Math,Science,English
Alice,85,90,80
Bob,78,88,82
Charlie,92,85,87
import pandas as pd
print("\n2. Pandas - Reading CSV and Basic Analysis:")
df = pd.read_csv("data.csv")
print("\nData from CSV:")
print(df)
print("\nMean Marks:")
print(df[["Math", "Science", "English"]].mean())
print("\nMaximum Marks:")
print(df[["Math", "Science", "English"]].max())
print("\nMinimum Marks:")
print(df[["Math", "Science", "English"]].min())
Matplotlib – Plotting a Simple Graph
import matplotlib.pyplot as plt
print("\n3. Matplotlib - Plotting a Graph:")
# Sample data for plotting
students = df["Name"]
math_marks = df["Math"]
plt.figure(figsize=(6, 4))
plt.bar(students, math_marks, color='skyblue')
plt.title("Math Marks of Students")
plt.xlabel("Student Name")
plt.ylabel("Marks")
plt.grid(True)
plt.tight_layout()
plt.show()
Expected Output:
NumPy: Prints array math, mean, and max
Pandas: Displays data from data.csv, and shows mean, max, min
Matplotlib: Displays a bar chart of math marks
EXP 10: GUI Programming with Tkinter
Create a basic GUI window using Tkinter.
Add widgets like Label, Button, Entry; handle basic events (e.g., button click).
import tkinter as tk
from tkinter import messagebox
# Function to be called on button click
def greet_user():
name = entry.get()
if name:
messagebox.showinfo("Greeting", f"Hello, {name}!")
else:
messagebox.showwarning("Input Error", "Please enter your name.")
# Create main window
window = tk.Tk()
window.title("Greeting App")
window.geometry("300x200") # width x height
# Add a Label widget
label = tk.Label(window, text="Enter your name:")
label.pack(pady=10)
# Add an Entry widget
entry = tk.Entry(window, width=25)
entry.pack(pady=5)
# Add a Button widget
button = tk.Button(window, text="Greet", command=greet_user)
button.pack(pady=20)
# Start the GUI event loop
window.mainloop()
output
Displays a window titled "Greeting App"
Lets the user type their name in an entry field
When the "Greet" button is clicked:
o A pop-up greets the user by name using messagebox
o If no name is entered, it shows a warning