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

Python

The document contains various Python programming examples covering arithmetic operations, control flow, data structures, file handling, exception handling, classes, and connecting to a MySQL database. Each section includes code snippets, sample inputs, and outputs demonstrating the functionality of the programs. Key topics include creating a simple calculator, finding factorials, using lists as stacks and queues, and validating email addresses with regular expressions.

Uploaded by

ksaravanank671
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)
9 views

Python

The document contains various Python programming examples covering arithmetic operations, control flow, data structures, file handling, exception handling, classes, and connecting to a MySQL database. Each section includes code snippets, sample inputs, and outputs demonstrating the functionality of the programs. Key topics include creating a simple calculator, finding factorials, using lists as stacks and queues, and validating email addresses with regular expressions.

Uploaded by

ksaravanank671
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/ 30

1.

CREATE A SIMPLE CALCULATOR TO DO


ALL THE ARITHMETIC OPERATIONS

CODING:

# Simple Calculator 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 "Cannot divide by zero."
def calculator():
print("Simple Calculator")
print("Select operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice = input("Enter choice (1/2/3/4): ")
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
result = add(num1, num2)
operator = "+"
elif choice == '2':
result = subtract(num1, num2)
operator = "-"
elif choice == '3':
result = multiply(num1, num2)
operator = "*"
elif choice == '4':
result = divide(num1, num2)
operator = "/"
print(f"{num1} {operator} {num2} = {result}")
else:
print("Invalid input. Please enter a valid operation
(1/2/3/4).")
if name == " main ":
SAMPLE INPUT / OUTPUT:

Simple Calculator
Select operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter choice (1/2/3/4): 3
Enter first number: 4
Enter second number: 5
4.0 * 5.0 = 20.0
2. PROGRAM USING CONTROL FLOW TOOLS
(PROGRAM TO FIND THE FACTORIAL OF A
GIVEN NUMBER)

CODING:

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


if number > 0:
print(f"{number} is a positive number.")
elif number < 0:
print(f"{number} is a negative number.")
else:
print("The number is zero.")
SAMPLE INPUT / OUTPUT:

Enter a number: -5
-5.0 is a negative number.
3. WRITE A PROGRAM TO USE FOR LOOP

CODING:

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


# Sum calculation using for loop
sum_of_numbers = 0
for i in range(1, n + 1):
sum_of_numbers += i
print(f"The sum of the first {n} natural numbers is:
{sum_of_numbers}")
SAMPLE INPUT / OUTPUT:

Enter the value of n: 5


The sum of the first 5 natural numbers is: 15
4. DATA STRUCTURE

A. USE LIST AS STACK


Coding:

Stack.py
# Python code to demonstrate Implementing
# stack using list
stack = ["SRI", "VIDYA", "KAMACHI"]
print(stack)
stack.append("ARTS")
stack.append("SCIENCE")
print("After Inserting elements the Stack is:")
print(stack)
print("Stack POP operations:")
# Removes the last item
stack.pop()
print("After Removing last element the Stack is:")
print(stack)
# Removes the last item
stack.pop()
print("After Removing last element the Stack is:")
print(stack)
OUTPUT:

['SRI', 'VIDYA', 'KAMACHI']


After Inserting elements the Stack is:
['SRI', 'VIDYA', 'KAMACHI', 'ARTS', 'SCIENCE']
Stack POP operations:
After Removing last element the Stack is:
['SRI', 'VIDYA', 'KAMACHI', 'ARTS']
After Removing last element the Stack is:
['SRI', 'VIDYA', 'KAMACHI']
B. USE LIST AS QUEUE.

Coding:

Queue.py
# Python code to demonstrate Implementing
# Queue using list
queue = ["SRI", "VIDYA", "KAMACHI"]
queue.append("ARTS")
queue.append("SCIENCE")
print("Queue elements are:")
print(queue)
print("Deleted elements are:")
# Removes the first item
print(queue.pop(0))
print(queue)
# Removes the first item
print(queue.pop(0))
print("Queue elements are:")
print(queue)
OUTPUT:

>>> %Run Queue.py


Queue elements are:
['SRI', 'VIDYA', 'KAMACHI', 'ARTS', 'SCIENCE']
Deleted elements are:
SRI
['VIDYA', 'KAMACHI', 'ARTS', 'SCIENCE']
VIDYA
Queue elements are:
['KAMACHI', 'ARTS', 'SCIENCE']
>>>
C. TUPLE, SEQUENCE

CODING:

# Using tuple as a sequence


# Initialize a tuple
my_tuple = (1, 2, 3, 4, 5)
# Access elements using indexing
element_at_index_2 = my_tuple[2]
# Iterate through the tuple
for element in my_tuple:
print(element)
# Output
print("Element at index 2:", element_at_index_2)
SAMPLE INPUT / OUTPUT:

1
2
3
4
5
Element at index 2: 3
5. CREATE NEW MODULE FOR
MATHEMATICAL OPERATIONS AND
USE IN YOUR PROGRAM

CODING:

# math_operations.py
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 "Cannot divide by zero."
# Program using the mathematical operations module
# Import the mathematical operations module
import math_operations as math_ops 12
# Input
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Perform mathematical operations
sum_result = math_ops.add(num1, num2)
difference_result = math_ops.subtract(num1, num2)
product_result = math_ops.multiply(num1, num2)
division_result = math_ops.divide(num1, num2)
# Output
print(f"Sum: {sum_result}")
print(f"Difference: {difference_result}")
print(f"Product: {product_result}")
print(f"Division: {division_result}")
SAMPLE INPUT / OUTPUT:

Enter the first number: 10


Enter the second number: 5
Sum: 15.0
Difference: 5.0
Product: 50.0
Division: 2.0
6. WRITE A PROGRAM TO READ AND WRITE
FILES.
CREATE AND DELETE DIRECTORIES.

CODING:
Import os
def read_file():
filename = input("Enter the name of the file to read: ")
try:
with open(filename, 'r') as file: 14
content = file.read()
print("\nFile content:\n", content)
except FileNotFoundError:
print(f"File '{filename}' not found.")
def write_to_file():
filename = input("Enter the name of the file to write: ")
content = input("Enter the content to write to the file: ")
with open(filename, 'w') as file:
file.write(content)
print(f"Content successfully written to '{filename}'.")
def create_directory():
dirname = input("Enter the name of the directory to
create: ")
try:
os.mkdir(dirname)
print(f"Directory '{dirname}' created successfully.")
except FileExistsError:
print(f"Directory '{dirname}' already exists.")
def delete_directory():
dirname = input("Enter the name of the directory to
delete: ")
try:
os.rmdir(dirname)
print(f"Directory '{dirname}' deleted successfully.")
except FileNotFoundError:
print(f"Directory '{dirname}' not found.")
except OSError as e:
print(f Error deleting directories’{dirname}’:{e}”)
# Sample Input & Output
read_file()
write_to_file()
create_directory()
delete_directory()
SAMPLE INPUT / OUTPUT:

Enter the name of the file to read: sample.txt


File 'sample.txt' not found.
Enter the name of the file to write: new_file.txt
Enter the content to write to the file: This is a new file
content.
Content successfully written to 'new_file.txt'.
Enter the name of the directory to create: new_directory
Directory 'new_directory' created successfully.
Enter the name of the directory to delete: new_directory
Directory 'new_directory' deleted successfully.
7. WRITE A PROGRAM TO EXCEPTIONS
HANDLING IN PYTHON

CODING:

def perform_division():
try:
# Input
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
# Division Operation
result = numerator / denominator
# Output
print(f"Result of {numerator} / {denominator} =
{result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:

print("Error: Please enter valid numbers.") 17


# Sample Input & Output
perform_division()
SAMPLE INPUT / OUTPUT:

Enter the numerator: 10


Enter the denominator: 2
Result of 10.0 / 2.0 = 5.0
Enter the numerator: 8
Enter the denominator: 0
Error: Cannot divide by zero.
Enter the numerator: abc
8. WRITE A PYTHON PROGRAM TO USING
CLASS
Coding: Dog.py
# Python program to show that the variables with a
value assigned in the class declaration,
#are class variables and variables inside methods and
constructors are instance variables.
# Class for Dog
class Dog:
# Class Variable
animal = 'dog'
# The init method or constructor
def init (self, breed, color):
# Instance Variable
self.breed = breed
self.color = color
# Objects of Dog class
Rodger = Dog("Pug", "brown")
Buzo = Dog("Bulldog", "black")
print('Rodger details:')
print('Rodger is a', Rodger.animal)
print('Breed: ', Rodger.breed)
print('Color: ', Rodger.color)
print('\nBuzo details:')
print('Buzo is a', Buzo.animal)
print('Breed: ', Buzo.breed)
print('Color: ', Buzo.color)
# Class variables can be accessed using class name also
print("\nAccessing class variable using class name")
print(Dog.animal)
OUTPUT:
>>> %Run Dog.py
Rodger details:
Rodger is a dog
Breed: Pug
Color: brown
Buzo details:
Buzo is a dog
Breed: Bulldog
Color: black
Accessing class variable using class name
Dog
>>>
9. PROGRAM TO CONNECT WITH MYSQL AND
CREATING ADDRESS BOOK.
CODING:
Myaddr.py
import sys
import MySQLdb
import mysql.connector
import mysql.connector
from mysql.connector import Error
#connect
conn =
mysql.connector.connect(host='localhost',user='root',pa
ssword='',database="Address_Book")
#create a cursor
cursor = conn.cursor()
#Add Records
def Add():
var = True
while var:
ssn = raw_input("Enter SSN number:")
name = raw_input("Enter a Name:")
address = raw_input("Enter the Address:")
city = raw_input("Enter the City: ")
state= raw_input("Enter the State:")
postcode = raw_input("Enter the Postcode:")
country = raw_input("Enter the country:")
cursor.execute("""
insert into addresses
(ssn,name,address,city,state,postcode,country)
values
(%s,%s,%s,%s,%s,%s,%s)""",(ssn,name,address,city,st
ate,postcode,country))
print("Add Another Record y/n")
enter = raw_input("Enter the option:")
if enter == 'y':
var = True
else:
printToConsole()
var = False
#Modify Records
def Modify():
ssn = raw_input("Enter the old ssn number to update:")
newssn = raw_input("Enter the new ssn number:")
cursor.execute("""
update addresses set ssn = %s
where ssn = %s""",(newssn,ssn))
#Delete records
def Delete():
ssn = raw_input("Enter the ssn record to be deleted:")
cursor.execute("""
delete from addresses
where ssn=%s""",ssn)
#View Records
def List():
print("List the Records")
cursor.execute("select * from addresses")
result = cursor.fetchall()
for record in result:
print(record[0],"–>",record[1],"–>",record[2],"–>
",record[3],"–>",record[4])
def Exit():
sys.exit()
def printToConsole():
while True:
print('1.Add Record')
print('2.Modify Record')
print('3.Delete Record')
print('4.List Record')
print('5.Exit')
option = int(raw_input('Enter the Option :'))
if option == 1:
Add()
elif option == 2:
Modify()
elif option == 3:
Delete()
elif option == 4:
List()
elif option == 5:
Exit()
printToConsole()
OUTPUT:

RESTART: C:\Python27\Myaddr.py
1. Add Record
2. Modify Record
3. Delete Record
4. List Record
5. Exit
Enter the Option :1
Enter SSN number:001
Enter a Name:nithi
Enter the Address:mecheri
Enter the City: salem
Enter the State:tamilnadu
Enter the Postcode:636453
Enter the country:India
Add Another Record y/n
Enter the option:y
Enter SSN number:002
Enter a Name:rathi
Enter the Address:mettur
Enter the City: salem
Enter the State:tamilnadu
Enter the Postcode:636453
Enter the country:India
Add Another Record y/n
Enter the option:n
10. PROGRAM USING STRING HANDLING AND
REGULAR EXPRESSIONS

CODING:
import re
def validate_and_extract_email(input_email):
# Regular expression pattern for a simple email
validation
email_pattern = r'^\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-
]+\.[A-Z|a-z]{2,}\b'
# Check if the input email matches the pattern
match_result = re.match(email_pattern, input_email) 24
if match_result:
print(f"The email '{input_email}' is valid.")
# Extract information from the email using regular
expressions
extracted_info = re.findall(r'([A-Za-z0-9._%+-]+)@([A-
Za-z0-9.-]+)\.([A-Z|a-z]{2,})', input_email)
# Display extracted information
print("Username:", extracted_info[0][0])
print("Domain:", extracted_info[0][1])
print("Top-level Domain:", extracted_info[0][2])
else:
print(f"The email '{input_email}' is not valid.")
# Sample Input & Output
input_email = input("Enter an email address: ")
validate_and_extract_email(input_email)
SAMPLE INPUT/OUTPUT:

Enter an email address: [email protected]


The email '[email protected]' is valid.
Username: john.doe
Domain: example
Top-level Domain: com
Enter an email address: invalid_email
The email 'invalid_email' is not valid.

You might also like