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

Python Record

The document contains various Python programs demonstrating arithmetic operations, control flow, loops, data structures (stack, queue, tuple), exception handling, classes, MySQL database interaction, and string handling with regular expressions. Each section includes code snippets and sample outputs for clarity. The programs cover fundamental programming concepts and practical applications in Python.

Uploaded by

s.v.dharshan2005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Record

The document contains various Python programs demonstrating arithmetic operations, control flow, loops, data structures (stack, queue, tuple), exception handling, classes, MySQL database interaction, and string handling with regular expressions. Each section includes code snippets and sample outputs for clarity. The programs cover fundamental programming concepts and practical applications in Python.

Uploaded by

s.v.dharshan2005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

1.

Simple Arithmetic calculator program in Python

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):

return x/y

print("\t\tSIMPLE CALCULATOR")

print("\t\t*****************")

print("select operation")

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

print("1. Add")

print("2. sub")

print("3. multi")

print("4. div")

choice= input("Enterchoice(1/2/3/4):")

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

num2 = int(input("Enter Second 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")
Output:-
SIMPLE ARITHMETIC CALCULAATOR

************************************

Select operation.

1.Add

2.Subtract

3.Multiply

4.Divide

Enter choice(1/2/3/4): 1

Enter first number: 20.5

Enter second number: 35.5

20.5 + 35.5 = 56.0

Result:-
2. PROGRAM USING CONTROL FLOW TOOLS

(PROGRAM TO FIND THE FACTORIAL OF A GIVEN NUMBER)

print("PROGRAM TO FIND THE FACTORIAL OF A GIVEN NUMBER\n")

n=int(input("enter the number : "))

factorial=1

if n < 0 :

print("factorial doesn't exist for negative number")

elif n==0:

print("for zero factorial is always one")

else:

print("Factorial of {} is :".format(n))

for i in range(1,n+1):

factorial=factorial*i

print(factorial)
Output:-

PROGRAM TO FIND THE FACTORIAL OF A GIVEN NUMBER


enter the number : 4

Factorial of 4 is : 24

Result:-
3. PROGRAM USING FOR LOOP
(PROGRAM TO PRINT THE MULTIPLICATION TABLE OF A GIVEN NUMBER)

n=int(input("enter the number: "))

for i in range(1,21):

x=n*i

print("{} * {} = {}".format(n,i,x))
Output:-
enter the number: 4

4*1=4

4*2=8

4 * 3 = 12

4 * 4 = 16

4 * 5 = 20

4 * 6 = 24

4 * 7 = 28

4 * 8 = 32

4 * 9 = 36

4 * 10 = 40

4 * 11 = 44

4 * 12 = 48

4 * 13 = 52

4 * 14 = 56

4 * 15 = 60

4 * 16 = 64

4 * 17 = 68

4 * 18 = 72

4 * 19 = 76

4 * 20 = 80

Result:-
4. a. PYTHON PROGRAM TO DEMONSTRATE STACK
IMPLEMENTATION USING LIST

# 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']

Result:-
4. b. PYTHON PROGRAM TO DEMONSTRATE QUEUE
IMPLEMENTATION USING LIST
# 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:-
Queue elements are:

['SRI', 'VIDYA', 'KAMACHI', 'ARTS', 'SCIENCE']

Deleted elements are:

SRI

['VIDYA', 'KAMACHI', 'ARTS', 'SCIENCE']

VIDYA

Queue elements are:

['KAMACHI', 'ARTS', 'SCIENCE']

Result:-
4. c. PYTHON PROGRAM TO DEMONSTRATE TUPLE AND

SEQUENCE IMPLEMENTATION
print("Tuple creation in python")

tuple_1 = ("PythonGeeks", "Sequences", "Tutorial") # [all string tuple]

print(f'tuple 1: {tuple_1}')

tuple_2 = tuple() # [empty tuple]

print(f'tuple 2: {tuple_2}')

tuple_3 = [2021, ('hello', 2020), 2.0] # [integer, tuple, float]

print(f'tuple 3: {tuple_3}')

tuple_4 = [{'language': 'Python'}, [1,2]] # [dictionary, list]

print(f'tuple 4: {tuple_4}')

print("Example for sequences:")

sequence= range(1, 10, 2)

for i in sequence:

print(i)
Output:-
tuple creation in python

tuple 1: ('PythonGeeks', 'Sequences', 'Tutorial')

tuple 2: ()

tuple 3: [2021, ('hello', 2020), 2.0]

tuple 4: [{'language': 'Python'}, [1, 2]]

Example for sequences:

Result:-
5. CREATION OF NEW MODULE FOR MATHEMATICAL
OPERATIONS
Calci.py

#Module for arithmetic operations

def add(a, b):

return a + b

def sub(a, b):

return a - b

def mul(a, b):

return a * b

def div(a, b):

return a / b

Mathmod.py

import Calci

print("10 + 5 ={}".format(Calci.add(10, 5)))

print("10 - 5 ={}".format(Calci.sub(10, 5)))

print("10 * 5 ={}".format(Calci.mul(10, 5)))

print("10 / 5 ={}".format(Calci.div(10, 5)))


Output:-
10 + 5 =15

10 - 5 =5

10 * 5 =50

10 / 5 =2.0

Result:-
6. CREATION AND DELETION OF NEW DIRECTORIES AND FILES
import os

import shutil

def main():

# Create a directory

directory_name = "new_directory"

os.mkdir(directory_name)

print(f"Directory '{directory_name}' created.")

# Create a file within the directory

file_name = os.path.join(directory_name, "new_file.txt")

open(file_name, 'a').close()

print(f"File '{file_name}' created.")

# Delete the file

if os.path.exists(file_name):

os.remove(file_name)

print(f"File '{file_name}' deleted.")

else:

print(f"The file '{file_name}' does not exist.")

# Delete the directory

if os.path.exists(directory_name):

shutil.rmtree(directory_name)

print(f"Directory '{directory_name}' deleted.")

else:
print(f"The directory '{directory_name}' does not exist.")

if __name__ == "__main__":

main()
Output:-
Directory 'new_directory' created.

File 'new_directory\new_file.txt' created.

File 'new_directory\new_file.txt' deleted.

Directory 'new_directory' deleted.

Result:-
7. EXCEPTION HANDLING
def divide(a, b):

try:

result = a / b

except ZeroDivisionError:

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

except Exception as e:

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

else:

print(f"The result of the division is: {result}")

finally:

print("Division operation completed.")

a=(input("enter the value a :"))

b=(input("enter the value b :"))

divide(a,b)
Output:-
enter the value a :45

enter the value b :6

The result of the division is: 7.5

Division operation completed.

Result:-
8. PROGRAM USING CLASSES

class Rectangle:

def __init__(self, length, width):

self.length = length

self.width = width

def area(self):

return self.length * self.width

def perimeter(self):

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

# Creating an instance of Rectangle class

rect1 = Rectangle(5, 4)

# Calculating area and perimeter of the rectangle

print("Area of rectangle:", rect1.area())

print("Perimeter of rectangle:", rect1.perimeter())


Output:-
Area of rectangle: 20

Perimeter of rectangle: 18

Result:-
9. PROGRAM TO CONNECT WITH MYSQL AND CREATING ADDRESS BOOK.

import sys

import MySQLdb

import mysql.connector

import mysql.connector

from mysql.connector import Error

#connect

conn =

mysql.connector.connect(host='localhost',user='root',password='',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,state,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:-

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

Result:-
10. PROGRAM USING STRING HANDLING AND REGULAR EXPRESSIONS

import re

print (" \n STRING HANDINLING USING REGULAR EXPRESSIONS\n")

#Check if the string starts with "The" and ends with "Spain":

txt = "The rain in Spain"

x = re.search("^The.*Spain$", txt)

if x:

print("YES! We have a match!")

else:

print("No match")

#Find all lower case characters alphabetically between "a" and "m":

x = re.findall("[a-m]", txt)

print(x)

#Check if the string starts with "The":

x = re.findall("\AThe", txt)

print(x)

if x:

print("Yes, there is a match!")

else:

print("No match")

#Return a match at every white-space character:

x = re.findall("\s", txt)

print(x)

if x:

print("Yes, there is at least one match!")

else:

print("No match")
#Split the string at every white-space character:

txt = "The rain in Spain"

x = re.split("\s", txt)

print(x)

#Replace all white-space characters with the digit "9":

txt = "The rain in Spain"

x = re.sub("\s", "9", txt)

print(x)
Output:-
STRING HANDINLING USING REGULAR EXPRESSIONS

YES! We have a match!

['h', 'e', 'a', 'i', 'i', 'a', 'i']

['The']

Yes, there is a match!

[' ', ' ', ' ']

Yes, there is at least one match!

['The', 'rain', 'in', 'Spain']

The9rain9in9Spain

Result:-

You might also like