0% found this document useful (0 votes)
2 views

PYTHON MAIN PRGMs

The document outlines a series of programming tasks aimed at creating various Python applications, including a simple calculator, control flow tools, loops, data structures, file handling, exception handling, class usage, MySQL connection, and string handling with regular expressions. Each task includes a clear aim, procedure, and example code, demonstrating the implementation of fundamental programming concepts. The document concludes with successful execution results for each program.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

PYTHON MAIN PRGMs

The document outlines a series of programming tasks aimed at creating various Python applications, including a simple calculator, control flow tools, loops, data structures, file handling, exception handling, class usage, MySQL connection, and string handling with regular expressions. Each task includes a clear aim, procedure, and example code, demonstrating the implementation of fundamental programming concepts. The document concludes with successful execution results for each program.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

1.

CREATE A SIMPLE CALCULATOR TO DO ALL


THE ARITHMETIC OPERATIONS
AIM:

To write Create a simple calculator to do all the arithmetic


operations.
PROCEDURE:

Step 1: Open the Idle python.


Step 2: To click file and click new file option.
Step 3: The new window was opened.
Step 4: Add TKinter module and it’s methods.
Step 5: use all the arithmetic operation in a source code
Step 6: Save the program with .py extention.
Step 7: Run the program or click F5 button.
Step 8: Close the program.
PROGRAM:

def add(x,y):
return x+y
def subtract(x,y):
return x-y
def multiply(x,y):
return x*y
def divide(x,y):
if y!=0:
return x/y
else:
return"error:Division by zero"
while True:
print("select operation:")
print("1.Addition")
print("2.Subtraction")
print("3.Multiplication")
print("4.Division")
print("5.Exit")
choice=input("Enter choce(1/2/3/4/5):")
if choice=="5":
break
if choice in('1','2','3','4','5'):
num1=float(input("Enter 1st number:"))
num2=float(input("Enter 2nd number:"))
if choice=='1':
print(num1,"+",num2,"=",add(num1,num2))
elif choice=='2':
print(num1,"-",num2,"=",subtract(num1,num2))
elif choice=='3':
print(num1,"*",num2,"=",multiply(num1,num2))
elif choice=='4':
print(num1,"/",num2,"=",divide(num1,num2))
else:
print("invalid input please enter a valid option")
OUTPUT:
RESULT:

Thus The Above Program Has Been Verified And


Executed Successfully.
2. WRITE A PROGRAM TO USE CONTROL FLOW
TOOLS LIKE IF
AIM:

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


PROCEDURE:

Step 1: Open the Idle python.


Step 2: To click file and click new file option.
Step 3: The new window was opened.
Step 4: Use if statement and if else statement source
code.
Step 5: Save the program with .py extention.
Step 6: Run the program or click F5 button.
Step 7: Close the program.
PROGRAM:

mark=int(input("Enter the marks1:"))


if(mark>=90):
print("you are in a first grade")
elif(mark>=75 and mark<90):
print("you are in a second grade")
elif(mark>=50 and mark<75):
print("you are in a third grade")
elif(mark>=35 and mark<50):
print("you are passed")
else:
print("you are failed")
OUTPUT:
RESULT:

Thus The Above Program Has Been Verified And


Executed Successfully.
3. WRITE A PROGRAM TO USE FOR LOOP
AIM:
To Write a program to use for loop.
PROCEDURE:
Step 1: Open the Idle python.
Step 2: To click file and click new file option.
Step 3: The new window was opened.
Step 4: use for loop and nested for loop in source code.
Step 5: Save the program with .py extention.
Step 6: Run the program or click F5 button.
Step 7: Close the program.
PROGRAM:
print("Enter The Value of n:")
a=int(input())
print("Using For Loop")
for i in range(0,a):
print(i)
print("Using Nested For Loop")
for i in range(2,4):
for j in range(1,3):
print(j,'*',i,"=",i*j)
print("******************")
OUTPUT:
RESULT:

Thus The Above Program Has Been Verified And


Executed Successfully.
4. DATA STRUCTURES A.USE LIST AS STACK,
B.USE LIST AS QUEUE, C.TUPLE, SEQUENCE.
AIM:

To write a program data structures use list as stack, list as


queue and tuple, sequence.
Procedure:

Step 1: Open the Idle python.


Step 2: To click file and click new file option.
Step 3: The new window was opened.
Step 4: Write a coding using stack such as push,pop.
Step5: Write a code using queue such as
enqueue,dequeue.
Step6: Write a code using tuple such as add,remove.
Step 7: Save the program with .py extention.
Step 8: Run the program or click F5 button.
Step 9: Close the program.
PROGRAM:

A. Use List As Stack


# Creating a stack using a list
stack = []
# Pushing elements onto the stack
stack.append(1)
stack.append(2)
stack.append(3)
# Popping elements from the stack
popped_item = stack.pop()
print(f"Popped item: {popped_item}")
# Peek at the top of the stack (without removing)
top_of_stack = stack[-1] if stack else None
print(f"Top of the stack: {top_of_stack}")
# Display the current stack
print("Current stack:", stack)
B. USE LIST AS QUEUE

# Creating a queue using a list


queue = []
# Enqueue (add elements to the end of the queue)
queue.append(1)
queue.append(2)
queue.append(3)
# Dequeue (remove elements from the front of the
queue)
dequeued_item = queue.pop(0) if queue else None
print(f"Dequeued item: {dequeued_item}")
# Display the current queue
print("Current queue:", queue)
C. TUPLE SEQUENCE

# Creating a tuple
my_tuple = (1, 'hello', 3.14, True)
# Accessing elements
print("First element:", my_tuple[0])
print("Second element:", my_tuple[1])
# Iterating through the tuple
print("Iterating through the tuple:")
for element in my_tuple:
print(element)
# Concatenating tuples
new_tuple = my_tuple + ('world', 42)
print("Concatenated tuple:", new_tuple)
# Repetition
repeated_tuple = new_tuple * 2
print("Repeated tuple:", repeated_tuple)
# Length of the tuple
length_of_tuple = len(new_tuple)
print("Length of the tuple:", length_of_tuple)
OUTPUT:
RESULT:

Thus The Above Program Has Been Verified And


Executed Successfully.
5. CREATE NEW MODULE FOR MATHEMATICAL
OPERATIONS AND USE I YOUR PROGRAM
AIM:

To Create new module for mathematical operations and


use in your program.
PROCEDURE:

Step 1: Open the Idle python.


Step 2: To click file and click new file option.
Step 3: The new window was opened.
Step 4: Create a new module and type a program than
save it.
Step 5: import our own new module in main program.
Step 6: Save the program with .py extention.
Step 7: Run the program or click F5 button.
Step 8: Close the program.
PROGRAM:

#math_operations.py
def add(x, y):
"""Addition function"""
return x + y
def subtract(x, y):
"""Subtraction function"""
return x - y
def multiply(x, y):
"""Multiplication function"""
return x * y
def divide(x, y):
"""Division function"""
if y != 0:
return x / y
else:
raise ValueError("Cannot divide by zero")
def square(x):
"""Square function"""
return x ** 2
def cube(x):
"""Cube function"""
return x ** 3
from math_operations import add, subtract, multiply, divide,
square, cube
num1 = 10
num2 = 5
# Basic operations
print(f"{num1} + {num2} = {add(num1, num2)}")
print(f"{num1} - {num2} = {subtract(num1, num2)}")
print(f"{num1} * {num2} = {multiply(num1, num2)}")
try:
print(f"{num1} / {num2} = {divide(num1, num2)}")
except ValueError as e:
print(f"Error: {e}")
print(f"Square of {num1} = {square(num1)}")
print(f"Cube of {num1} = {cube(num1)}")
OUTPUT:
RESULT:

Thus The Above Program Has Been Verified And


Executed Successfully.
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.
PROCEDURE:

Step 1: Open the Idle python.


Step 2: To click file and click new file option.
Step 3: The new window was opened.
Step 4: Import OS module and write codings for file
concept.
Step5: Such as create,read,write,create directories,delete
directories.
Step6: close the file using codings.
Step 6: Save the program with .py extention.
Step 7: Run the program or click F5 button.
Step 8: Close the program.
PROGRAM:

import os
# Function to create a directory
def create_directory(directory_name):
try:
os.mkdir(directory_name)
print(f"Directory '{directory_name}' created
successfully.")
except FileExistsError:
print(f"Directory '{directory_name}' already
exists.")

# Function to delete a directory


def delete_directory(directory_name):
try:
os.rmdir(directory_name)
print(f"Directory '{directory_name}' deleted
successfully.")
except FileNotFoundError:
print(f"Directory '{directory_name}' not found.")
except OSError as e:
print(f"Error: {e}")

# Function to write to a file


def write_to_file(file_name, content):
with open(file_name, 'w') as file:
file.write(content)
print(f"Content written to '{file_name}' successfully.")

# Function to read from a file


def read_from_file(file_name):
try:
with open(file_name, 'r') as file:
content = file.read()
print(f"Content of '{file_name}':\n{content}")
except FileNotFoundError:
print(f"File '{file_name}' not found.")
except Exception as e:
print(f"Error: {e}")

# Main program
directory_name = 'example_directory'
file_name = 'example_file.txt'
file_content = 'Hello, this is some content for the file.'

# Create a directory
create_directory(directory_name)

# Write to a file in the directory


write_to_file(os.path.join(directory_name, file_name),
file_content)

# Read from the file


read_from_file(os.path.join(directory_name, file_name))

# Delete the directory


delete_directory(directory_name)
OUTPUT:
RESULT:

Thus The Above Program Has Been Verified And


Executed Successfully.
7. WRITE A PROGRAM WITH EXCEPTION
HANDLING
AIM:

To Write a program with exception handling.


PROCEDURE:

Step 1: Open the Idle python.


Step 2: To click file and click new file option.
Step 3: The new window was opened.
Step 4: Write a code for exception handling operation
such as try and except.
Step 6: Save the program with .py extention.
Step 7: Run the program or click F5 button.
Step 8: Close the program.
PROGRAM:

try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
result = numerator / denominator
print(f"Result: {result}")
except ValueError as ve:
print(f"Error: {ve}\nPlease enter valid numbers.")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
else:
print("Division successful.")
finally:
print("Program execution complete.")
if __name__ == "__main__":
divide_numbers()
OUTPUT:
RESULT:

Thus The Above Program Has Been Verified And


Executed Successfully.
8. WRITE A PROGRAM USING CLASSES
AIM:

To write a program using classes.


PROCEDURE:

Step 1: Open the Idle python.


Step 2: To click file and click new file option.
Step 3: The new window was opened.
Step4: Add math module.
Step5: use class and object concept in source code .
Step 6: Save the program with .py extention.
Step 7: Run the program or click F5 button.
Step 8: Close the program.
PROGRAM:

class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade

def display_info(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
print(f"Grade: {self.grade}")

def promote(self):
if self.grade.lower().startswith("12th"):
print(f"{self.name} has graduated!")
else:
print(f"{self.name} is promoted to the next grade.")

# Example usage:
if __name__ == "__main__":
# Create students
student1 = Student("Alice", 17, "11th")
student2 = Student("Bob", 18, "12th")
student3 = Student("Charlie", 16, "10th")

# Display student information


print("Student 1:")
student1.display_info()
student1.promote()

print("\nStudent 2:")
student2.display_info()
student2.promote()

print("\nStudent 3:")
student3.display_info()
student3.promote()
OUTPUT:
RESULT:

Thus The Above Program Has Been Verified And


Executed Successfully.
9. CONNECT WITH MYSQL AND CREATE ADDRESS
BOOK
AIM:

To Connect with MySQL and create address book..


PROCEDURE:

Step 1: Open the Idle python.


Step 2: To click file and click new file option.
Step 3: The new window was opened.

Step4: Add TKinter module and it’s objects..


Step5: Design addressbook using the variables.
Step 6: Save the program with .py extention.
Step 7: Run the program or click F5 button.
Step 8: Close the program.
PROGRAM:

import mysql.connector

# Connect to MySQL
connection = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="address_book"
)

# Create a cursor object


cursor = connection.cursor()

# Create the contacts table


cursor.execute("""
CREATE TABLE IF NOT EXISTS contacts (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100),
phone VARCHAR(20)
)
""")

# Insert a contact into the table


cursor.execute("""
INSERT INTO contacts (name, email, phone) VALUES
('John Doe', '[email protected]', '123-456-7890')
""")

# Commit the transaction


connection.commit()

# Fetch all contacts from the table


cursor.execute("SELECT * FROM contacts")
contacts = cursor.fetchall()

# Print all contacts


print("Contacts:")
for contact in contacts:
print(contact)

# Close cursor and connection


cursor.close()
connection.close()
OUTPUT:

Contacts:
(1, 'John Doe', '[email protected]', '123-456-7890')

This output indicates that there is one contact in the contacts


table with the following details:

 ID: 1
 Name: John Doe
 Email: [email protected]
 Phone: 123-456-7890
RESULT:

Thus The Above Program Has Been Verified And


Executed Successfully.
10. WRITE A PROGRAM USING STRING
HANDLING AND REGULAR EXPRESSIONS
AIM:

To Write a program using string handling and regular


expressions.
PROCEDURE:

Step 1: Open the Idle python.


Step 2: To click file and click new file option.
Step 3: The new window was opened.
Step4: Using string operation and regular expressions.
Step 5: Save the program with .py extention.
Step 6: Run the program or click F5 button.
Step 7: Close the program.
PROGRAM:

import re
target_str = "My roll number is 65"
res = re.findall(r"\d", target_str)
# extract mathing value
print(res)

def special(string):
charRe = re.compile(r'[^A-Z0-9]')
string = charRe.search(string)
return not bool(string)
print(special("ABCDEF123450"))
print(special("*&%@#!}{"))
print(special("abcEF123450"))

def match(text):
patterns = '^a(b*)$'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
print(match("ac"))
print(match("abc"))
print(match("a"))
print(match("ab"))
print(match("abb"))

text = "Clearly, he has no excuse for such was behavior."


for m in re.finditer(r"\w+as", text):
print('%d-%d: %s' % (m.start(), m.end(), m.group(0)))

text = "The quick brown fox jumps over the lazy dog."
# remove words between 1 and 3
shortword = re.compile(r'\W*\b\w{1,3}\b')
print(shortword.sub('', text))
OUTPUT:
RESULT:

Thus The Above Program Has Been Verified And


Executed Successfully.

You might also like