[go: up one dir, main page]

0% found this document useful (0 votes)
4 views26 pages

King Uuuuuuu

The document outlines a comprehensive Python programming course, covering topics such as arithmetic operations, control structures, functions, data structures, file handling, error handling, and object-oriented programming. Each week includes lab exercises that provide practical coding examples and tasks for students to complete. The course is structured to progressively build programming skills through hands-on exercises.

Uploaded by

23pa1a0352
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)
4 views26 pages

King Uuuuuuu

The document outlines a comprehensive Python programming course, covering topics such as arithmetic operations, control structures, functions, data structures, file handling, error handling, and object-oriented programming. Each week includes lab exercises that provide practical coding examples and tasks for students to complete. The course is structured to progressively build programming skills through hands-on exercises.

Uploaded by

23pa1a0352
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/ 26

Week 1: Introduction to Python Programming

Lab Exercise 1.1: Arithmetic Operations

# Program to perform basic arithmetic operations

# Taking input from the user

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))

# Performing arithmetic operations

addition = num1 + num2

subtraction = num1 - num2

multiplication = num1 * num2

division = num1 / num2

# Displaying the results

print("Addition:", addition)

print("Subtraction:", subtraction)

print("Multiplication:", multiplication)

print("Division:", division)

Lab Exercise 1.2: Basic Input / Output Operations

# Program to take input from the user and display a message

# Taking input from the user

name = input("Enter your name: ")

age = int(input("Enter your age: "))

# Displaying the message

print(f"Hello, {name}! You are {age} years old.")


Week 2: Control Structures and Loops

Lab Exercise 2.1: Largest of Three Numbers

# Program to find the largest of three numbers

# Taking input from the user

num1 = float(input("Enter first number: "))

num2 = float(input("Enter second number: "))

num3 = float(input("Enter third number: "))

# Finding the largest number

if (num1 >= num2) and (num1 >= num3):

largest = num1

elif (num2 >= num1) and (num2 >= num3):

largest = num2

else:

largest = num3

# Displaying the result

print("The largest number is", largest)

Lab Exercise 2.2: Check the given number is even or odd

# Input from the user

number = int(input("Enter a number: "))

# Check if the number is even or odd

if number % 2 == 0:

print(f"{number} is an Even number.")

else:
print(f"{number} is an Odd number.")

Lab Exercise 2.3:check the given year is leap year

# Input from the user

year = int(input("Enter a year: "))

# Check if the year is a leap year

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):

print(f"{year} is a Leap year.")

else:

print(f"{year} is not a Leap year.")

Lab Exercise 2.4: Multiplication Table

# Program to display the multiplication table of a given number

# Taking input from the user

number = int(input("Enter a number: "))

# Displaying the multiplication table

for i in range(1, 11):

print(f"{number} x {i} = {number * i}")

Lab Exercise 2.5: Sum of digits in given number

# Input from the user

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

# Initialize sum variable

sum_of_digits = 0

# Loop to calculate the sum of digits

while num > 0:

digit = num % 10 # Get the last digit


sum_of_digits = sum_of_digits + digit # Add the digit to the sum

num = num // 10 # Remove the last digit

# Display the result

print("Sum of digits:", sum_of_digits)

Lab Exercise 2.6: Palindrome number

# Input from the user

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

# Store the original number to compare later

original_num = num

# Initialize a variable to store the reversed number

reversed_num = 0

# Loop to reverse the digits of the number

while num > 0:

digit = num % 10 # Extract the last digit

reversed_num = reversed_num * 10 + digit # Build the reversed number

num = num // 10 # Remove the last digit

# Check if the original number is equal to the reversed number

if original_num == reversed_num:

print(f"{original_num} is a Palindrome number.")

else:

print(f"{original_num} is not a Palindrome number.")

Lab Exercise 2.7:check the given number is prime or not

# Input from the user

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

# Check if the number is prime


if num > 1:

is_prime = True

# Check for factors from 2 to sqrt(num)

for i in range(2, int(num**0.5) + 1):

if num % i == 0:

is_prime = False

break

if is_prime:

print(f"{num} is a Prime number.")

else:

print(f"{num} is not a Prime number.")

else:

print(f"{num} is not a Prime number.") # Numbers less than 2 are not prime

Lab Exercise 2.8:Fibonacci number

# Input from the user

n = int(input("Enter the number of terms: "))

# First two terms of the Fibonacci sequence

a, b = 0, 1

count = 0

# Check if the number of terms is valid

if n <= 0:

print("Please enter a positive integer.")

elif n == 1:

print("Fibonacci sequence up to 1 term:")


print(a)

else:

print(f"Fibonacci sequence up to {n} terms:")

while count < n:

print(a, end=" ")

# Update values for the next term

next_term = a + b

a=b

b = next_term

count = count + 1

Week 3: Functions and Modular Programming

Lab Exercise 3.1: Factorial Calculation

# Program to calculate the factorial of a number using a function

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n-1)

# Taking input from the user

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

# Calculating and displaying the factorial

print(f"The factorial of {num} is {factorial(num)}")


Lab Exercise 3.2: Fibonacci Sequence

# Program to compute the Fibonacci sequence using recursive approach

# Recursive approach

def fibonacci_recursive(n):

if n <= 1:

return n

else:

return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)

# Taking input from the user

num = int(input("Enter the number of terms: "))

# Displaying the Fibonacci sequence

print("Fibonacci sequence (Recursive):", [fibonacci_recursive(i) for i in range(num)])

Lab Exercise 3.3: two different standard library modules

# Importing standard library modules

import math

import datetime

# Asking the user for a number

number = int(input("Enter a number: "))

# Using the math module to calculate the square root and factorial

sqrt_value = math.sqrt(number)

factorial_value = math.factorial(number)

print(f"The square root of {number} is {sqrt_value}")

print(f"The factorial of {number} is {factorial_value}")

# Using the datetime module to display the current date and time

current_datetime = datetime.datetime.now()
print(f"Current date and time: {current_datetime}")

Week 4: Data Structures (Lists, Tuples, Dictionaries)

Lab Exercise 4.1: List Operations

# Program to perform operations on a list

# Creating a list

numbers = [1, 2, 3, 4, 5]

# Adding an element to the list

numbers.append(6)

print("List after adding an element:", numbers)

# Removing an element from the list

numbers.remove(3)

print("List after removing an element:", numbers)

# Sorting the list

numbers.sort()

print("Sorted list:", numbers)

Lab Exercise 4.2: Frequency of Elements in a List

# Program to count the frequency of elements in a list

# Creating a list

elements = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

# Counting the frequency

frequency = {}

for item in elements:

if item in frequency:

frequency[item] = frequency[item] + 1
else:

frequency[item] = 1

# Displaying the frequency

print("Frequency of elements:", frequency)

Lab Exercise 4.3:List comprehension

# Original list of numbers

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Using list comprehension to create a new list of squares of even numbers

squares_of_evens = [x**2 for x in numbers if x % 2 == 0]

# Display the original list and the new list

print("Original list:", numbers)

print("Squares of even numbers:", squares_of_evens)

Lab Exercise 4.4: create, modify and iterate tuples

# Creating a tuple

my_tuple = (1, 2, 3, 4, 5)

print("Original tuple:", my_tuple)

# Modifying the tuple by creating a new one

# For example, let's add an element to the tuple

new_element = 6

modified_tuple = my_tuple + (new_element,)

print("Modified tuple:", modified_tuple)

# Iterating through the modified tuple

print("Iterating through the modified tuple:")

for item in modified_tuple:

print(item)
Week 5:Dictionaries and Sets

Lab Exercise 5.1:Create and manipulate dictionaries

# Creating a dictionary

my_dict = { "name": "Alice", "age": 30, "city": "New York"}

# Display the original dictionary

print("Original Dictionary:", my_dict)

# Adding a new key-value pair

my_dict["occupation"] = "Engineer"

print("\nAfter adding occupation:", my_dict)

# Updating an existing key-value pair

my_dict["age"] = 31

print("After updating age:", my_dict)

# Removing a key-value pair

removed_value = my_dict.pop("city")

print(f"\nAfter removing city (removed value: {removed_value}):", my_dict)

# Iterating through the dictionary

print("\nIterating through the dictionary:")

for key, value in my_dict.items():

print(f"{key}: {value}")

Lab Exercise 5.2: Dictionary comprehension

# Creating a dictionary using dictionary comprehension

# Mapping numbers to their squares for numbers 1 to 10

squares = {x: x**2 for x in range(1, 11)}

# Display the resulting dictionary

print("Dictionary of squares:")
print(squares)

Lab Exercise 5.3: create and perform operations on sets

# Creating a set

my_set = {1, 2, 3, 4, 5}

print("Original Set:", my_set)

# Adding an element to the set

my_set.add(6)

print("\nSet after adding 6:", my_set)

# Removing an element from the set

my_set.remove(3) # Using remove() will raise an error if the element is not found

print("Set after removing 3:", my_set)

# Performing set operations

another_set = {4, 5, 6, 7, 8}

# Union of two sets

union_set = my_set.union(another_set)

print("\nUnion of sets:", union_set)

# Intersection of two sets

intersection_set = my_set.intersection(another_set)

print("Intersection of sets:", intersection_set)

# Difference of two sets

difference_set = my_set.difference(another_set)

print("Difference of sets (my_set - another_set):", difference_set)

# Displaying the final state of the original set

print("\nFinal state of the original set:", my_set)

Week 6: Strings and File Handling


Lab Exercise 6.1: Longest Word in a Text File

# Program to find the longest word in a text file

# Opening the file

with open('C:\\Users\\Dell\\Desktop\\sample.txt', 'r') as file:

words = file.read().split()

# Finding the longest word

longest_word = max(words, key=len)

# Displaying the longest word

print("The longest word is:", longest_word)

Lab Exercise 6.2: Read and Write to Files

# Program to read a file line by line and write it to another file

# Opening the source file for reading

with open('C:\\Users\\Dell\\Desktop\\sample.txt', 'r') as source_file:

lines = source_file.readlines()

# Opening the destination file for writing

with open('C:\\Users\\Dell\\Desktop\\destination.txt', 'w') as destination_file:

for line in lines:

destination_file.write(line)

Week 7: Error handling and Exceptions

Lab Exercise 7.1: Program using try, except, else, and finally blocks

def divide_numbers(num1, num2):

try:

# Attempt to divide the two numbers

result = num1 / num2


except ZeroDivisionError:

# Handle the case where division by zero occurs

print("Error: Division by zero is not allowed.")

except TypeError:

# Handle the case where invalid types are provided

print("Error: Please provide numbers.")

else:

# If no exceptions were raised, this block will execute

print("The result of {} divided by {} is: {}".format(num1, num2, result))

finally:

# This block will execute no matter what

print("Execution of the divide_numbers function is complete.")

divide_numbers(num1, num2)

Example inputs

# Testing the function with different inputs

print("Test 1: Dividing 10 by 2")

divide_numbers(10, 2)

print("\nTest 2: Dividing 10 by 0")

divide_numbers(10, 0)

print("\nTest 3: Dividing 10 by a string")

divide_numbers(10, "a")

Lab Exercise 7.2: Handle specific exceptions

def divide_numbers(num1, num2):

try:

# Attempt to divide the two numbers


result = num1 / num2

except ZeroDivisionError:

# Handle the case where division by zero occurs

print("Error: Division by zero is not allowed.")

except TypeError:

# Handle the case where invalid types are provided

print("Error: Please provide valid numbers.")

except Exception as e:

# Catch any other exception and display the message

print(f"An unexpected error occurred: {e}")

else:

# If no exceptions were raised, this block will execute

print("The result of {} divided by {} is: {}".format(num1, num2, result))

finally:

# This block will execute no matter what

print("Execution of the divide_numbers function is complete.")

# Function to get user input and handle potential conversion errors

def get_number_input(prompt):

while True:

try:

# Get input from the user and convert it to a float

return float(input(prompt))

except ValueError:
# Handle the case where conversion to float fails

print("Error: Please enter a valid number.")

# Main program

print("Enter two numbers to divide:")

num1 = get_number_input("Enter the first number: ")

num2 = get_number_input("Enter the second number: ")

divide_numbers(num1, num2)

Sample inputs and outputs

a)Enter two numbers to divide:

Enter the first number: 10

Enter the second number: 2

The result of 10.0 divided by 2.0 is: 5.0

Execution of the divide_numbers function is complete.

b)Enter two numbers to divide:

Enter the first number: 10

Enter the second number: 0

Error: Division by zero is not allowed.

Execution of the divide_numbers function is complete.

c)Enter two numbers to divide:

Enter the first number: 10

Enter the second number: a

Error: Please enter a valid number.

Enter the second number: 5


The result of 10.0 divided by 5.0 is: 2.0

Execution of the divide_numbers function is complete.

Week 8: Object-Oriented Programming(OOP)

Lab Exercise 8.1: Class for Geometric Shapes

# Program to create a class for geometric shapes

class Shape:

def __init__(self, name):

self.name = name

def area(self):

pass

def perimeter(self):

pass

class Circle(Shape):

def __init__(self, radius):

super().__init__("Circle")

self.radius = radius

def area(self):

return 3.14 * self.radius * self.radius

def perimeter(self):

return 2 * 3.14 * self.radius

class Rectangle(Shape):

def __init__(self, length, width):


super().__init__("Rectangle")

self.length = length

self.width = width

def area(self):

return self.length * self.width

def perimeter(self):

return 2 * (self.length + self.width)

# Creating objects and displaying the area and perimeter

circle = Circle(5)

print(f"Area of {circle.name}: {circle.area()}")

print(f"Perimeter of {circle.name}: {circle.perimeter()}")

rectangle = Rectangle(4, 7)

print(f"Area of {rectangle.name}: {rectangle.area()}")

print(f"Perimeter of {rectangle.name}: {rectangle.perimeter()}")

Lab Exercise 8.2:Demonstrate inheritance

# Base class

class Vehicle:

def __init__(self, make, model, year):

self.make = make

self.model = model

self.year = year
def display_info(self):

return f"{self.year} {self.make} {self.model}"

# Derived class

class Car(Vehicle):

def __init__(self, make, model, year, doors):

# Calling the constructor of the base class

super().__init__(make, model, year)

self.doors = doors

def display_info(self):

# Extending the info method to include the number of doors

return f"{self.year} {self.make} {self.model} with {self.doors} doors"

# Main program

def main():

# Creating an instance of Vehicle

vehicle = Vehicle("Toyota", "Camry", 2020)

print(vehicle.display_info()) # Outputs: 2020 Toyota Camry

# Creating an instance of Car

car = Car("Honda", "Accord", 2021, 4)

print(car.display_info()) # Outputs: 2021 Honda Accord with 4 doors

if __name__ == "__main__":

main()
Week 9:Libraries and packages

Lab Exercise 9.1:

Write a program using libraries like NumPy and Pandas.

import numpy as np

import pandas as pd

# Create a NumPy array of random numbers

np.random.seed(0) # For reproducibility

data = np.random.randint(1, 100, size=(10, 3)) # 10 rows, 3 columns

# Display the NumPy array

print("NumPy Array:")

print(data)

# Convert the NumPy array to a Pandas DataFrame

columns = ['A', 'B', 'C']

df = pd.DataFrame(data, columns=columns)

# Display the DataFrame

print("\nPandas DataFrame:")

print(df)

# Calculate the mean of each column

mean_values = df.mean()

print("\nMean Values:")

print(mean_values)

# Add a new column with the sum of the existing columns

df['Sum'] = df['A'] + df['B'] + df['C']

print("\nDataFrame with Sum Column:")


print(df)

# Filter rows where the sum is greater than 150

filtered_df = df[df['Sum'] > 150]

print("\nFiltered DataFrame (Sum > 150):")

print(filtered_df)

output:

NumPy Array:

[[45 48 65]

[68 68 68]

[10 84 77]

[87 70 88]

[83 64 80]

[19 54 82]

[55 65 53]

[69 68 62]

[87 60 74]

[84 53 23]]

Pandas DataFrame:

A B C

0 45 48 65

1 68 68 68

2 10 84 77

3 87 70 88
4 83 64 80

5 19 54 82

6 55 65 53

7 69 68 62

8 87 60 74

9 84 53 23

Mean Values:

A 57.6

B 61.8

C 69.6

dtype: float64

DataFrame with Sum Column:

A B C Sum

3 87 70 88 245

4 83 64 80 227

5 19 54 82 155

8 87 60 74 221

Filtered DataFrame (Sum > 150):

A B C Sum

3 87 70 88 245

4 83 64 80 227

5 19 54 82 155

8 87 60 74 221

Lab Exercise 9.2: Packages


Create a package containing modules for mathematical operations (e.g., addition, subtraction,
multiplication, division).

Step 1: Create the Package Structure

Create the following directory structure for your package:

math_operations/

├── math_ops/

│ ├── __init__.py

│ ├── addition.py

│ ├── subtraction.py

│ ├── multiplication.py

│ └── division.py

└── setup.py

Step 2: Create the Modules

1. math_ops/addition.py

def add(a, b):


"""Return the sum of two numbers."""
return a + b

2. math_ops/subtraction.py
def subtract(a, b):
"""Return the difference of two numbers."""
return a - b
3. math_ops/multiplication.py
def multiply(a, b):
"""Return the product of two numbers."""
return a * b
4. math_ops/division.py
def divide(a, b):
"""Return the quotient of two numbers. Raise ValueError if dividing by zero."""
if b == 0:
raise ValueError("Cannot divide by zero.")
return a / b

5.math_ops/__init__.py
from .addition import add
from .subtraction import subtract
from .multiplication import multiply
from .division import divide

__all__ = ['add', 'subtract', 'multiply', 'divide']

Step 3: Create the setup.py File


setup.py

from setuptools import setup, find_packages

setup(
name='math_operations',
version='0.1',
packages=find_packages(),
description='A simple package for basic mathematical operations',
author='Your Name',
author_email='your.email@example.com',
)

Step 4: Install the Package

1. Open your terminal or command prompt.


2. Navigate to the directory containing the setup.py file.
3. Run the following command to install the package:

pip install .

Step 5: Using the Package

Create a new Python file (e.g., test_math_operations.py) to test the package:

test_math_operations.py

from math_ops import add, subtract, multiply, divide

# Test the operations

print("Addition: 5 + 3 =", add(5, 3))

print("Subtraction: 5 - 3 =", subtract(5, 3))

print("Multiplication: 5 * 3 =", multiply(5, 3))

print("Division: 5 / 2 =", divide(5, 2))


# Handling division by zero

try:

print("Division: 5 / 0 =", divide(5, 0))

except ValueError as e:

print(e)

Step 6: Run the Test Program

Run the test_math_operations.py file in your terminal:

python test_math_operations.py

Example Output

Addition: 5 + 3 = 8

Subtraction: 5 - 3 = 2

Multiplication: 5 * 3 = 15

Division: 5 / 2 = 2.5

Cannot divide by zero.

Week 10: Working with Data

Lab Exercise 10.1:

Write a Program Demonstrating Data Loading, Manipulation, and Visualization using Pandas,
Matplotlib, and Seaborn.

import pandas as pd

import matplotlib.pyplot as plt

# Step 1: Load the dataset (for this example, we'll create a simple dataset)

data = {

'Name': ['John', 'Anna', 'Peter', 'Linda', 'James'],


'Age': [28, 22, 35, 32, 30],

'Salary': [70000, 48000, 102000, 56000, 75000]

# Create a DataFrame

df = pd.DataFrame(data)

# Step 2: Data Manipulation

# - Calculate the average salary

average_salary = df['Salary'].mean()

print(f"Average Salary: {average_salary}")

# - Filter the employees who are older than 30

older_employees = df[df['Age'] > 30]

print("\nEmployees older than 30:")

print(older_employees)

# Step 3: Data Visualization

# Plot a bar chart for the salaries of employees

plt.figure(figsize=(8, 5))

plt.bar(df['Name'], df['Salary'], color='blue')

plt.title('Employee Salaries')

plt.xlabel('Employee Name')
plt.ylabel('Salary')

plt.show()

Example Output:

Average Salary: 70200.0

Employees older than 30:

Name Age Salary

2 Peter 35 102000

3 Linda 32 56000

5 James 30 75000

You might also like