0% found this document useful (0 votes)
2 views12 pages

Python Record

Uploaded by

v62017469
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)
2 views12 pages

Python Record

Uploaded by

v62017469
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

EXPERIMENT-1

1. Write a Python program that performs the following tasks:

 Manipulate a string to reverse its characters and count the occurrence of a


specific substring.
 Create a list of integers and perform sorting and slicing operations.
 Define a tuple of mixed data types and unpack its elements into variables.
 Implement a set to remove duplicates from a list of integers and perform
set operations (union, intersection).
 Use a dictionary to store student grades and calculate the average grade.

# --- Part 1. String Manipulation ---


text = "learning python is fun, learning is life"
reversed_text = text[::-1]
substring_count = [Link]("learning")

# ----------------------------------------

# --- Part 2. List Operations ---


numbers = [42, 7, 13, 89, 24, 5, 13]
[Link]() # Sorts the list in place
sliced_numbers = numbers[1:4]
# Gets elements from index 1 to 3

# ----------------------------------------

# --- Part 3. Tuple Unpacking ---


mixed_tuple = ("Alice", 25, "Data Science", 3.9)
name, age, major, gpa = mixed_tuple

# ----------------------------------------

# --- Part 4. Set Operations ---


duplicate_list = [1, 2, 2, 3, 4, 4, 5]
unique_set = set(duplicate_list) # Automatically removes duplicates
other_set = {4, 5, 6, 7, 8}

union_set = unique_set | other_set # All unique elements from both


intersection_set = unique_set & other_set # Elements present in both

# ----------------------------------------

# --- Part 5. Dictionary & Calculations ---


grades = {
"Alice": 85,
"Bob": 92,
"Charlie": 78,
"Diana": 95
}
average_grade = sum([Link]()) / len(grades)

# ----------------------------------------

# --- Displaying Results ---


print(f"Original String: {text}")
print(f"Reversed: {reversed_text}")
print(f"Occurrences of 'learning': {substring_count}\n")

print(f"Sorted List: {numbers}")


print(f"Sliced List (index 1 to 4): {sliced_numbers}\n")

print(f"Unpacked Tuple: {name} is {age} years old, studying {major}.\n")

print(f"Set without duplicates: {unique_set}")


print(f"Union: {union_set}")
print(f"Intersection: {intersection_set}\n")

print(f"Student Grades: {grades}")


print(f"Average Grade: {average_grade:.2f}")
EXPERIMENT-2

2. Write a Python program that demonstrates the following:


 Use control flow statements (if-else, loops) to iterate through a list and
perform conditional operations.
 Implement list comprehensions to generate a list of squared numbers from
1 to 10.
 Define a basic function to calculate factorial and use recursion.
 Create a lambda function to compute the square of a number

# Part 1: Control Flow with List Iteration

print("----- Control Flow with List -----")

numbers = [3, 7, 10, 15, 20, 25]

for num in numbers:


if num % 2 == 0:
print(num, "is Even")
else:
print(num, "is Odd")

# ----------------------------------------

# Part 2: List Comprehension (Squares from 1 to 10)

print("\n----- List Comprehension -----")

squares = [x**2 for x in range(1, 11)]


print("Squares from 1 to 10:", squares)

# ----------------------------------------

# Part 3: Recursive Function for Factorial

print("\n----- Recursion (Factorial) -----")

def factorial(n):
# Base condition
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

# Input from user


num = int(input("Enter a number to find factorial: "))
# Function call
result = factorial(num)
print("Factorial of", num, "is:", result)

# Part 4: lambda Function to compute square of a number

Square = lambda x: x*x


print(“square of the number using lambda function: “, Square(5))
3. Write a Python program that performs file handling and exceptions handling:
 Read data from a text file, count the number of lines, and print each line.
 Write data to a new text file and handle exceptions for file opening and
writing operations.
 Use try-except blocks to handle specific exceptions (e.g.,
FileNotFoundError, IOError).
 Implement file operations (open, read, write, close) using context
managers (with statement).
EXPERIMENT-3

# File names
input_file = "[Link]"
output_file = "[Link]"

# Part 1: Reading from file

print("----- Reading File -----")

try:
# Using context manager for safe file handling
with open(input_file, "r") as file:
lines = [Link]() # Read all lines

print("Total number of lines:", len(lines))


print("\nFile Content:")

for line in lines:


print([Link]()) # strip() removes newline characters

except FileNotFoundError:
print("Error: File not found. Please check the file name and path.")

except IOError:
print("Error: Problem occurred while reading the file.")

# -------------------------------

# Part 2: Writing to file

print("\n----- Writing File -----")

try:
with open(output_file, "w") as file:
[Link]("Python File Handling Program\n")
[Link]("Demonstration of read, write, and exception handling\n")
[Link]("Using context managers (with statement)\n")
[Link]("File handling is completed successfully.\n")
print("Data written successfully to", output_file)

except IOError:
print("Error: Problem occurred while writing to the file.")
EXPERIMENT-4

. Write a Python program that demonstrates OOP concepts:


 Define a class representing a Car with attributes (make, model, year) and
methods (accelerate, brake).
 Create instances of the Car class and invoke its methods to simulate driving
actions.
 Implement inheritance by creating a subclass (ElectricCar) that inherits
from the Car class and has additional methods (charge_battery).
 Use encapsulation to restrict access to certain attributes and methods of
the Car class

# Base Class
class Car:
# Constructor
def __init__(self, make, model, year):
[Link] = make
[Link] = model
[Link] = year

# Method to accelerate
def accelerate(self):
print([Link], [Link], "is accelerating.")

# Method to brake
def brake(self):
print([Link], [Link], "is braking.")

# Method to display car details


def display_info(self):
print("Car Details:", [Link], [Link], [Link])

# -------------------------------------------------
# Subclass using Inheritance
class ElectricCar(Car):
def __init__(self, make, model, year, battery_capacity):
# Call parent constructor
super().__init__(make, model, year)
self.battery_capacity = battery_capacity

# New method (specific to ElectricCar)


def charge_battery(self):
print([Link], [Link], "battery is charging...")

# Overriding parent method (optional demonstration)


def accelerate(self):
print([Link], [Link], "is accelerating silently (Electric Mode).")
# -------------------------------------------------
# Main Program

# Creating objects of Car class


car1 = Car("Toyota", "Corolla", 2020)
car2 = Car("Honda", "City", 2022)

# Using methods
print("----- Normal Car Simulation -----")
car1.display_info()
[Link]()
[Link]()

print()

car2.display_info()
[Link]()
[Link]()

# Creating object of ElectricCar class


ecar1 = ElectricCar("Tesla", "Model 3", 2023, "75 kWh")

print("\n----- Electric Car Simulation -----")


ecar1.display_info()
[Link]()
[Link]()
ecar1.charge_battery()
EXPERIMENT-5

5. Python Turtle Graphics – Drawing Shapes, Filling shapes

import turtle

# Screen setup
screen = [Link]()
[Link]("Turtle Graphics - Drawing Shapes")
[Link]("lightyellow")

# Turtle object
pen = [Link]()
[Link](3)
[Link](3)

# -----------------------------
# Draw Square
[Link]("blue", "lightblue")
pen.begin_fill()
for i in range(4):
[Link](100)
[Link](90)
pen.end_fill()

[Link]()
[Link](150, 0)
[Link]()

# -----------------------------
# Draw Triangle
[Link]("green", "lightgreen")
pen.begin_fill()
for i in range(3):
[Link](100)
[Link](120)
pen.end_fill()

[Link]()
[Link](-150, 0)
[Link]()

# -----------------------------
# Draw Circle
[Link]("red", "pink")
pen.begin_fill()
[Link](50)
pen.end_fill()

[Link]()
[Link](0, -150)
[Link]()

# -----------------------------
# Draw Rectangle
[Link]("purple", "violet")
pen.begin_fill()
for i in range(2):
[Link](150)
[Link](90)
[Link](80)
[Link](90)
pen.end_fill()

# Finish
[Link]()
[Link]()
EXPERIMENT-6

6. Games programing using Pygame

[Link]
}
import pygame
import random
import sys

# Initialize pygame
[Link]()

# Screen setup
WIDTH, HEIGHT = 800, 600
screen = [Link].set_mode((WIDTH, HEIGHT))
[Link].set_caption("Catch the Ball Game")

# Colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)

# Clock
clock = [Link]()

# Basket
basket_width = 100
basket_height = 20
basket_x = WIDTH // 2 - basket_width // 2
basket_y = HEIGHT - 50
basket_speed = 8

# Ball
ball_radius = 15
ball_x = [Link](ball_radius, WIDTH - ball_radius)
ball_y = 0
ball_speed = 5

# Score
score = 0
font = [Link]("arial", 30)
game_over_font = [Link]("arial", 60)

# Game loop
running = True
while running:
[Link](WHITE)
# Events
for event in [Link]():
if [Link] == [Link]:
running = False

# Key handling
keys = [Link].get_pressed()
if keys[pygame.K_LEFT] and basket_x > 0:
basket_x -= basket_speed
if keys[pygame.K_RIGHT] and basket_x < WIDTH - basket_width:
basket_x += basket_speed

# Ball movement
ball_y += ball_speed

# Collision detection
if (basket_y < ball_y + ball_radius < basket_y + basket_height and
basket_x < ball_x < basket_x + basket_width):
score += 1
ball_y = 0
ball_x = [Link](ball_radius, WIDTH - ball_radius)

# Missed ball → Game Over


if ball_y > HEIGHT:
game_over_text = game_over_font.render("GAME OVER", True, RED)
score_text = [Link](f"Score: {score}", True, BLACK)
[Link](game_over_text, (WIDTH//2 - 150, HEIGHT//2 - 50))
[Link](score_text, (WIDTH//2 - 60, HEIGHT//2 + 10))
[Link]()
[Link](3000)
break

# Draw ball
[Link](screen, RED, (ball_x, ball_y), ball_radius)

# Draw basket
[Link](screen, BLUE, (basket_x, basket_y, basket_width,
basket_height))

# Draw score
score_text = [Link](f"Score: {score}", True, BLACK)
[Link](score_text, (10, 10))

[Link]()
[Link](60)

[Link]()
[Link]()

You might also like