0% found this document useful (0 votes)
1 views29 pages

Python Programming 1-9

The document outlines various programming tasks and algorithms, including creating a simple calculator, using control flow tools, implementing loops, and utilizing data structures like stacks and queues. It also covers file operations, exception handling, and class-based programming in Python. Each section provides a structured approach to solving specific programming problems with example code snippets.
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)
1 views29 pages

Python Programming 1-9

The document outlines various programming tasks and algorithms, including creating a simple calculator, using control flow tools, implementing loops, and utilizing data structures like stacks and queues. It also covers file operations, exception handling, and class-based programming in Python. Each section provides a structured approach to solving specific programming problems with example code snippets.
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

1)Create a simple calculator to do all the arithmetic operators.

Aim:

To create a simple calculator to do all the arithmetic operations

Algorithm:

Step 1: start the program

Step 2: to create a calculator for that can be add,subtraction,multiply,divide.

Step 3: the user should have to select any one of the operation.

Step 4:here we use the input function to gather the user input.

Step 5: the user should enter the values for the two numbers.

Step 6: here we use the if statement to select the particular choices.

Step 7: else branch is used to display the value for invalid choices

Step 8: stop the program.

Program:

def add(P, Q):

# This function is used for adding two numbers

return P + Q

def subtract(P, Q):

# This function is used for subtracting two numbers

return P - Q

def multiply(P, Q):

# This function is used for multiplying two numbers

return P * Q

def divide(P, Q):

# This function is used for dividing two numbers

return P / Q
# Now we will take inputs from the user

print ("Please select the operation.")

print ("a. Add")

print ("b. Subtract")

print ("c. Multiply")

print ("d. Divide")

choice = input("Please enter choice (a/ b/ c/ d): ")

num_1 = int (input ("Please enter the first number: "))

num_2 = int (input ("Please enter the second number: "))

if choice == 'a':

print (num_1, " + ", num_2, " = ", add(num_1, num_2))

elif choice == 'b':

print (num_1, " - ", num_2, " = ", subtract(num_1, num_2))

elif choice == 'c':

print (num_1, " * ", num_2, " = ", multiply(num_1, num_2))

elif choice == 'd':

print (num_1, " / ", num_2, " = ", divide(num_1, num_2))

else:

print ("This is an invalid input")


Output:

Result:

Thus the above program has been executed successfully.


2) Write a program to use control flow tooks like it.

Aim:

To write a program to use control flow tools like if.

Algorithm:

Step 1 : start the program.

Step 2: we have to write a program to use control flow tools like if statement.

Step 3: use the input function to get the name,roll number,and marks in each subject.

Step 4: convert the input types to the appropriate datatypes using int() for numeric values.

Step 5: calculate total marks by adding all the subjects.

Step 6: use an if-else statement to check if the student has failed in any subject.

Step 7: use if-elif-else to determine the grade based on the total marks.

Step 8 :stop the program.

Program:

name=str(input("Enter the name of the Student :"))

roll=int(input("Enter the roll number :"))

tamil=int(input("Enter the mark of Tamil :"))

english=int(input("Enter the mark of English :"))

maths=int(input("Enter the mark of Maths :"))

science=int(input("Enter the mark of Science :"))

social=int(input("Enter the mark of Social :"))

print("***************************************************")

total=tamil+english+maths+science+social

print("**************************************************")

print("Name of the Student :",name)

print("Roll number of the student :",roll)


print(" ")

print("Mark in Tamil :",tamil)

print("Mark in English :",english)

print("Mark in Maths :",maths)

print("Mark in Science :",science)

print("Mark in Social :",social)

print(" ")

print("Total mark of the Student :",total)

print(" ")

if(tamil<30 or english<30 or maths<30 or science<30 or social<30 ):

print(" result you are Fail")

else:

print(" result you are Pass")

if(total>=450 and total<=500):

ptint("Grade of the student Grade A")

elif (total>=400 and total<=450):

print("Grade of the student Grade B")

elif (total>=350 and total<=400):

print("Grade of the student Grade C")

elif (total>=300 and total<=350):

print("Grade of the student Grade D")

elif (total>=250 and total<=300):

print("Grade of the student Grade E")

else:

print("Grade of the student N/A")

print("**************************************************")
Output:

Result:

Thus the above program has been executed successfully.


3) write a program to use for loop.

Aim:

To write a program to use for loop.

Algorithm:

Step 1: start the program.

Step 2: create a list to store the values one by one.

Step 3: using for loop we can get the value from specific range.

Step 4: Initialize counters for positive, negative, odd, even, zero, sum_positive, sum_negative.

Step 5:Use a loop to get values from the user and append them to the list ‘a’.

Step 6: using the module of the number we can verify whether the given value is odd or even.

Step 7: to find total calculate the sum of positive and sum of negative.

Program:

print("Enter the numbers. .............. ")

a=[] #creating Empty list. .... for using loop

num=int(input("Enter the number you needed :"))

positive=0

negative=0

odd=0

even=0

zero=0

sum_positive=0

sum_negative=0

for i in range(0,num):

value=int(input("Enter the value :"))

[Link](value)
for j in a:

if(j>0):

positive+=1

sum_positive+=j

elif(j<0):

negative+=1

sum_negative+=j

else:

zero+=1

for k in a:

if(k%2==0):

even+=1

else:

odd+=1

total=sum_positive-sum_negative

print("**********************************")

print("Total number you Entered :",num)

print("Total number of Positive :",positive)

print("Total number of nagative :",negative)

print("Total number of zero's :",zero)

print("Total number of odd :",odd)

print("Total number of Even :",even)

print("**********************************")

print("sum of Positive numbers :",sum_positive)

print("sum of negative numbers :",sum_negative)

print("**********************************")

print("sumof all numbers :",total)


print("**********************************")

Output:

Result:

Thus the above programhas been executed successfully.


4) a) Data structures use list as stack.

Aim:

To write a program use list as stack in data structures.

Algorithm:

Step 1: start the program

Step 2: define a class name ‘Queue’. Initialize an empty list ‘queue’ in the constructor.

Step 3:define a method ‘enqueue’ to add element to the [Link] user input for the number of
elements to be add.

Step 4:define a method dequeue to remove elements from the queue.

Step 5: Define a method “is_empty” to check if the queue is empty.

Step 6:define a method get_size to get the size of the queue.

Step 7:stop the program.

Program:

class Queue:

def init (self):

[Link] = []

def enqueue(self):

num=int(input("Enter the number of Element to add :"))

for i in range(num):

element=str(input(""))

[Link](element)

def dequeue(self):

if not self.is_empty():

name=str(input("Enter the Element name to remove "))


return [Link](name)

def show(self):

for i in [Link]:

print(i)

def is_empty(self):

return len([Link]) == 0

def get_size(self):

return len([Link])

# Usage:

q = Queue()

# Adding elements to the queue

[Link]()

[Link]()

[Link]()

# Checking if the queue is empty

print(q.is_empty()) # Output: False

# Getting the size of the queue

print(q.get_size()) # Output: 1

Output:
Result:

Thus the above program has been executed successfully.


4)b) Data structures use list as queue.

Aim:

To create a list as queue in data structures.

Algorithm:

Step 1: start the program.

Step 2: define a class named ‘queue’

Initialize an empty list ‘queue’ in the constructor using ‘ init ’.

Step 3: implement a method ‘is_empty’ to check if the queue is empty by comparing the queue list
to an empty list.

Step 4:implement enqueue to add an item to the end of the queue using an append method.

Step 5: dequeue method to remove and return the front element of the queue using pop(0)

Step 6:implement display method ‘display_queue’ method to display the current state.

Step 7: stop the program.

Program:

class Queue:

def _init_(self):

[Link] = []

def is_empty(self):

return [Link] == []

def enqueue(self, item):

[Link](item)

def dequeue(self):

if self.is_empty():

print("The queue is empty.")

else:

return [Link](0)

def display_queue(self):
return [Link]

# Example usage:

q = Queue()

# Add elements to the queue

[Link](1)

[Link](2)

[Link](3)

# Display the queue

print(q.display_queue()) # Output: [1, 2, 3]

# Remove and display elements from the queue

print([Link]()) # Output: 1

print([Link]()) # Output: 2

# Display the queue again

print(q.display_queue())

output:

Result:

Thus the above program has been executed successfully.


4. C)

Data Structures Tuple and Sequence


Aim:

To create a program tuple,sequence in data structures.

Algorithm:

Step 1: start the program.

Step 2: Initializes a tuple named ‘my_tuple’ with elements 1,2,3,4,and 5.

Step 3:prints the first and fifth elements of the tuple.

Step 4:then prints a slice of the tuple from index 1 to 3.

Step 5:prints the length (number of elements ) of the tuple.

Step 6: checks if the element 3 is present in the tuple.

Step 7:Iterates through each element In the tuple and prints them.

Step 8:Combines two tuples using the ‘+’ operatot.

Step 9: stop the program

Program:

Creating a tuple

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

# Accessing elements in a tuple

print(my_tuple[0]) # Output: 1

print(my_tuple[4]) # Output: 5

# Slicing a tuple

print(my_tuple[1:4]) # Output: (2, 3, 4)

# Length of a tuple

print(len(my_tuple)) # Output: 5

# Checking if an element is in a tuple


print(3 in my_tuple) # Output: True

# Iterating over a tuple

for element in my_tuple:

print(element)

# Tuple concatenation

even_tuple = (2, 4, 6)

odd_tuple = (1, 3, 5)

combined_tuple = even_tuple + odd_tuple

print(combined_tuple) # Output: (2, 4, 6, 1, 3, 5)

# Tuple repetition

repeated_tuple = (1, 2, 3) * 3

print(repeated_tuple) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)

output:

Result:

Thus the above program has been executed successfully.


5) Aim:

To write a program to create a new module for mathematical operations and use in your program.

Algorithm:

Step 1: start the program.

Step 2: here we use two files file one consists of math_module.py and [Link].

Step 3: math_module.py file defines basic math operations and [Link] imports and uses these
operations.

Step 4: it defines four mathematical operations add,subtract,multiply,divide. The divide functions


checks for division by zero and raises the valueerror in such cases.

Step 5: the try block executes the mathematical operations if any division by zero occurs it catches
the value error and prints an error message.

Step 6:stop the program.

Program:

File 1:

# math_module.py =>File name

def add(a, b):

return a + b

def subtract(a, b):

return a - b

def multiply(a, b):

return a * b

def divide(a, b):

if b == 0:

raise ValueError("Cannot divide by zero")

return a / b

file 2:

# [Link]

import math_module
try:

result = math_module.add(3, 5)

print(f"3 + 5 = {result}")

result = math_module.subtract(10, 3)

print(f"10 - 3 = {result}")

result = math_module.multiply(2, 4)

print(f"2 * 4 = {result}")

result = math_module.divide(9, 3)

print(f"9 / 3 = {result}")

except ValueError as ve:

print(ve)

output:

Result:

Thus the above program has been executed successfully.


Ex: 6 Write a program to read and write files ,create and delete directories.

Aim:

To write a program to read and write files, create and delete directories.

Algorithm:

Step 1: Start the program

Step 2: Import the necessary modules

Step 3: Define functions for file and directory operations

Step 4: write data to a file with [Link]

Step 5: Read data from a file

Step 6: Delete a file

Step 7: Delete a directory

Step 8: stop the program

Program :

import os #This import is used to create new Directory

# To create a new directory

name_directory=str(input("Enter the name of the Directory :"))

new_directory =name_directory

[Link](new_directory)

# write data to a file

with open([Link](new_directory, "[Link]"), "w") as f:

para=str(input( "Enter the paragraph :"))

[Link](para)

# read data from a file

with open([Link](new_directory, "[Link]"), "r") as f:

data = [Link]()

print("Data from file:", data)

n= str(input("Enter Y to Remove File :"))

if n=="y":
[Link]([Link](new_directory, "[Link]"))

k= str(input("Enter k to Remove Directory :"))

if k=="k":

[Link](new_directory)

output:

Result :

Thus the above program has been executed and verified successfully.
Ex: 7

Write a program with exception handling.

Aim:

To write a program with exception handling

Algorithm:

Step 1: start the program

Step 2: Define a class

Step 3: Identify potential errors

Step 4: Import exception classes

Step5: Enclose risky code in a Try Block

Step6: Use finally blocks for cleanup operations

Step7: Stop the program

Program:

class ValueTooSmallError(Exception):

def display(self):

print("Input Value is TOO Small................")

class ValuueTooLargeError(Exception):

def display(self):

print("Input Vale is Too Large..................")

min=50

max=100

while 1:

try:

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

if num<=max and num>=min:

print("Great you Sccceeded")

if(num<min):

raise ValueTooSmallError
elif (num>max):

raise ValuueTooLargeError

except ValueTooSmallError as s:

[Link]()

except ValuueTooLargeError as a:

[Link]()

output:

Result:

Thus the above program has been executed and verified successfully.
Ex: 8

Write a program using classes.

Aim:

To write a python program using classes

Algorithm:

Step1: Start the program

Step2: Define the laptop class

Step3: Create a library class

Step4: To create instances of the classes

Step5: The library class manages a list of laptops with methods to add laptop and display the
library’s contents.

Step6: stop the program

Program:

class laptop():

name=''

ssd=''

ram=''

ldisplay=''

price="RS 45000"

def __init__(self):

[Link]=str(input("Enter the Name of the laptop :"))

[Link]=str(input("Enter the Storage of the SSD :"))

[Link]=str(input("Enter the RAM of the laptop :"))

[Link]=str(input("Enter the Display size :"))

def display(self):

print('**********************************************')

print("Name of the laptop ",[Link])

print('SSD storage of the laptop ',[Link])

print('RAM of the laptop ',[Link])

print('Display size of the laptop ',[Link])


print('price of the laptop ',[Link])

print('**********************************************')

def search(self):

print('-----------------------------------------------')

a=input("Enter the name to find :")

temp=a

while(temp!="not"):

print('-----------------------------------------------')

if(temp=="price"):

print('price of the laptop ',[Link])

elif(temp=="ssd"):

print('SSD storage of the laptop ',[Link])

elif(temp=="display"):

print('Display size of the laptop ',[Link])

elif(temp=='ram'):

output :

Result:

Thus the above program has been executed and verified successfully.
9) Connect with MYSQL and create address book

Aim:

To write a python program to connect with MYSQL and create address book.

Program:

[Link] the program.

[Link] the choice from the user

[Link] the name and mobile num from the user and store it in a database

[Link] the user contact which was stored in the database

[Link] the contact

[Link] the program.

Program:

def display_contact():

print([Link]())

print("Name\t\tContact Number")

for key in contact:

print("{}\t\t{}".format(key,[Link](key)))

while True:

choice = int(input(" 1. Add new contact \n 2. Search contact \n [Link] contact\n 4. Edit contact
\n 5. Delete contact\n [Link]\n Enter your choice "))

if choice == 1:

name = input("enter the contact name ")

phone = input("enter the mobile number")

contact[name] = phone

elif choice == 2:

search_name = input("enter the contact name ")

if search_name in contact:

print(search_name,"'s contact number is ",contact[search_name])

else:

print("Name is not found in contact book")


elif choice == 3:

if not contact:

print("empty contact book")

else:

display_contact()

elif choice == 4:

edit_contact = input("Enter the contact to be edited ")

if edit_contact in contact:

phone = input("enter mobile number")

contact[edit_contact]=phone

print("contact updated")

display_contact()

else:

print("Name is not found in contact book")

elif choice == 5:

del_contact = input("Enter the contact to be deleted ")

if del_contact in contact:

confirm = input("Do you want to delete this contact y/n? ")

if confirm =='y' or confirm =='Y':

[Link](del_contact)

display_contact()

else:

print("Name is not found in contact book")

else:

break
output:

Result:

Thus the above program has been executed successfully.


Ex:10 Write a program using string handling and regular expressions.

Aim:

To write a python program using string handling and regular expressions.

Algorithm:

Step1: Start the program

Step2: Import the necessary modules ‘re’ for regular expressions

Step3: Define a function to extract email addresses using regular expressions.

Step4: To get the input text

Step5: Call the function and display the results.

Step6: Stop the program

You might also like