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

III B.Sc(Python Manual)

The document contains various Python programming examples covering topics such as a simple calculator, control flow with conditional statements, loops, data structures like stacks and queues, and mathematical operations. It also includes file handling, exception handling, class usage, and a MySQL address book application. Each section provides code snippets demonstrating the respective concepts and functionalities.

Uploaded by

Shanmuga Priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

III B.Sc(Python Manual)

The document contains various Python programming examples covering topics such as a simple calculator, control flow with conditional statements, loops, data structures like stacks and queues, and mathematical operations. It also includes file handling, exception handling, class usage, and a MySQL address book application. Each section provides code snippets demonstrating the respective concepts and functionalities.

Uploaded by

Shanmuga Priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

1.

SIMPLE CALCULATOR
# This function adds two numbers

def add(x, y):

return x + y

# This function subtracts two numbers

def subtract(x, y):

return x - y

# This function multiplies two numbers

def multiply(x, y):

return x * y

# This function divides two numbers

def divide(x, y):

return x / y

print("\n ~~~~~~~~~~~~ SIMPLE CALCULATOR ~~~~~~~~~~~~ \n")

print("Select the Operation.")

print("1.Add")

print("2.Subtract")

print("3.Multiply")

print("4.Divide")

while True:

# take input from the user

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

# check if choice is one of the four options

if choice in ('1', '2', '3', '4'):

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

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

except ValueError:

print("Invalid input. Please enter a number.")

continue

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

# check if user wants another calculation

# break the while loop if answer is no

next_calculation = input("Let's do next calculation? (yes/no): ")

if next_calculation == "no":

break

else:

print("Invalid Input")
OUTPUT:
2. CONTROL FLOW IF

print("\n\n~~~~~~~~~~ CONDITIONAL STATEMENTS~~~~~~~~~~~~\n")

print("\n 1. Equal Or Not Equal\n 2. Biggest and Smallest\n 3.Odd or Even\n\n")

num=input(" Select The Condition: ")

if(num=="1" or num=="2" or num=="3"):

x=int(input("Enter The X Value:"))

y=int(input("Enter The Y Value:"))

if num=="1":

if(x==y):

print("Both X and Y Values Are Equal")

else:

print("Both X and Y Values Are Not Equal")

elif num=="2":

if x>y:

print("X is a Biggest Number")

print("Y is a Smallest Number")

else:

print("Y is Biggest Number")

print("X is a Smallest Number")

elif num=="3":

if x%2:

print("X is a Odd Number")

else:

print("X is Even Number")


if y%2:

print("Y is a Odd Number")

else:

print("Y is a Even Number")

else:

print("Wrong Choice Value")


OUTPUT:
3. FOR LOOP

words= ["Python", "Network Security", "Computer graphics"]

for word in words:

#This loop is fetching word from the list

print ("The following lines will print each letters of "+word)

for letter in word:

#This loop is fetching letter for the word

print (letter)

print("") #This print is used to print a blank line


OUTPUT:
4. i) LIST AS STACK

def isEmpty(stk): # checks whether the stack is empty or not

if stk==[]:

return True

else:

return False

def Push(stk,item): # Allow additions to the stack

stk.append(item)

top=len(stk)-1

def Pop(stk):

if isEmpty(stk): # verifies whether the stack is empty or not

print("Underflow")

else: # Allow deletions from the stack

item=stk.pop()

if len(stk)==0:

top=None

else:

top=len(stk)

print("Popped item is "+str(item))

def Display(stk):

if isEmpty(stk):

print("Stack is empty")

else:

top=len(stk)-1
print("Elements in the stack are: ")

for i in range(top,-1,-1):

print (str(stk[i]))

# executable code

if __name__ == "__main__":

stk=[]

#stk=input("Enter the Element Into Stack : ")

top=None

Push(stk,1)

Push(stk,2)

Push(stk,3)

Push(stk,4)

Pop(stk)

Display(stk)
OUTPUT:
4. ii) LIST AS QUEUE

#Adding elements to queue at the rear end

def enqueue(data):

queue.insert(0,data)

#Removing the front element from the queue

def dequeue():

if len(queue)>0:

return queue.pop()

return ("Queue Empty!")

#To display the elements of the queue

def display():

print("Elements on queue are:");

for i in range(len(queue)):

print(queue[i])

# executable code

if __name__=="__main__":

queue=[]

enqueue(5)

enqueue(6)

enqueue(9)

enqueue(5)

enqueue(3)

print("Popped Element is: "+str(dequeue()))

display()
OUTPUT:
4. iii) TUPLE AS SEQUENCE

# Concatenation of tuples

Tuple1 = (0, 1, 2, 3)

Tuple2 = ('PYTHON', 'COMPUTER GRAPHICS', 'NETWORK SECURITY')

Tuple3 = Tuple1 + Tuple2

# Printing first Tuple

print("Tuple 1: ")

print(Tuple1)

# Printing Second Tuple

print("\nTuple2: ")

print(Tuple2)

# Printing Final Tuple

print("\nTuples after Concatenation: ")

print(Tuple3)

# Slicing of a Tuple with Numbers

Tuple1 = tuple('COMPUTER SCIENCE')

print("Removal of First Element: ")

print(Tuple1[1:])

# Reversing the Tuple

print("\nTuple after sequence of Element is reversed: ")

print(Tuple1[::-1])

# Printing elements of a Range

print("\nPrinting elements between Range 4-9: ")

print(Tuple1[4:9])
OUTPUT:
5. NEW MODULE FOR MATHEMATICAL OPERATION

import math

def fact():

print("\n-------------------- CALCULATE FACTORIAL VALUE---------------------\n")

x=int(input("Enter the number to find factorial : "))

print("The factorial of given number is : ", math.factorial(x) )

fact()

def power():

print("\n-------------------CALCULATE POWER VALUE------------------------\n")

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

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

result = math.pow(base, exponent)

print( f"The value of {base} to the power of {exponent} is: ", result)

power()

def squareroot():

print("\n-------------------CALCULATE SQUARE ROOT VALUE ----------------\n")

number =int(input("Enter the number to find the square root: "))

result = math.sqrt(number)

print(" The square root value is: ",result)

squareroot()

def Trigonometry():

print("\n------------------- CALCULATE TRIGONOMETRY VALUE-----------------\n")

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

angle_radians = math.radians(angle_degrees)
sin_value = math.sin(angle_radians)

cos_value = math.cos(angle_radians)

tan_value = math.tan(angle_radians)

print(" The sin value is" , sin_value)

print(" The cos value is" , cos_value)

print(" The tan value is" , tan_value)

Trigonometry()

def logrithm():

print("\n-----------------------CALCULATE LOG VALUE---------------------\n")

number=int(input("Enter the number to find the log value : "))

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

log_e = math.log(number)

print(log_e)

log_base = math.log(number, base)

print(log_base)

logrithm()
OUTPUT:
6. FILE HANDLING

import os

import sys

import shutil

print("\n ~~~~~~~~~~~~Creating and Deleting File Directories~~~~~~~~~~~~~\n ")

try:

parent_path = input("Enter the Directory Name to Create : \t")

os.makedirs(parent_path)

print("\n Creating Directory '%s' Sucessfully" % parent_path)

except:

print("\n The Directory Name Already Exists..............")

try:

mydir = input("\n Enter the Directory Name to Delete : ")

shutil.rmtree(mydir)

print("\n Deleting Directory '%s' Sucessfully" % parent_path)

except:

print("\n The Directory Name not Exist................")

print("\n ~~~~~~~~~~~~Read and Write a File~~~~~~~~~~~~~")

file=open("Hello.txt",'w')

a=input("\n Enter The Text File Content : ")

file.write(a)

file.close()

file= open("Hello.txt","r")

print("\n The Content of the File \n ")


print(file.read())

print()

file.close()
OUTPUT:
7. EXCEPTION HANDLING

print("\n ------------------ Zero Divisible Error--------------------- \n")

numerator= int(input(" Enter the numerator : \n"))

denominator= int(input(" Enter the denominator : \n "))

try:

result = numerator/denominator

print(result)

except:

print(" \n Error: Denominator cannot be 0. \n ")

print("\n ---------- Array index out of bounds----------------- \n ")

try:

even_numbers = [2,4,6,8]

print(even_numbers[5])

except ZeroDivisionError:

print("Denominator cannot be 0.")

except IndexError:

print("Index Out of Bound.")

print("\n ---------------- File Not Found Exception -------------- \n")

try:

file1 = open("D:/Myfolder/abc.txt")

print( file1.read())

except:

print("file not found")


OUTPUT:
8. PROGRAM USING CLASS
class Student:

def getStudentDetails(self):

print(" \n ----------------- Class Using Student Mark Details -------------------------\n")

self.rollno=input("Enter Roll Number : \t")

self.name = input("Enter Student Name : \t")

self.tamil =int(input("Enter Tamil Mark : \t"))

self.english = int(input("Enter English Mark: \t"))

self.maths = int(input("Enter Maths Mark : \t"))

self.science = int(input("Enter Science Mark :\t "))

self.social = int(input("Enter Social Science Mark : \t"))

def printResult(self):

self.total=(int)(self.tamil + self.english + self.maths+self.science+ self.social)

self.percentage = (float)( self.total/ 500 * 100 );

if((self.tamil>=35) and (self.english>=35) and (self.maths >=35) and (self.science >=35)and


(self.social >=35)):

print("PASS \n ")

else:

print("FAIL \n ")

print("Roll Number : \t ", self.rollno)

print("Student Name : \t ", self.name)

print("Total Marks : \t " ,self.total)

print(" Percentage : \t ",self.percentage)

if self.percentage >= 90:

print("Grade A")
elif self.percentage >= 80 and self.percentage< 90:

print("Grade B")

elif self.percentage >= 70 and self.percentage < 80:

print("Grade C")

elif self.percentage >= 60 and self.percentage< 70:

print("Grade D")

else:

print("Grade E")

S1=Student()

S1.getStudentDetails()

print("\n ------------ Result ----------- \n ")

S1.printResult()
OUTPUT:
9. MY SQL AND CREATE ADDRESS BOOK

import mysql.connector

import time

db = mysql.connector.connect(

host="localhost",

user="root",

password="1234",

database="contact"

cursor = db.cursor()

cursor.execute("""

CREATE TABLE IF NOT EXISTS book (

name char(30) primary key,

address char(100),

mobile char(15),

email char(30)

);

""")

def create_record():

name = input("Enter name: ")

address = input("Enter address: ")

mobile = input("Enter mobile: ")

email = input("Enter email: ")

sql = "INSERT INTO book(name,address,mobile,email) VALUES (%s,%s,%s,%s)"


record = (name, address, mobile, email)

cursor.execute(sql, record)

db.commit()

print("Record Entered Successfully\n")

def search(name):

sql = "SELECT * FROM book WHERE name = %s"

value = (name,)

cursor.execute(sql, value)

record = cursor.fetchone()

if record is None:

print("No such record exists")

else:

print('Name:', record[0])

print('Address:', record[1])

print('Mobile:', record[2])

print('E-mail:', record[3])

def display_all():

cursor.execute("SELECT * FROM book")

print('{0:20}{1:30}{2:15}{3:30}'.format('NAME', 'ADDRESS', 'MOBILE NO', 'E-MAIL'))

for record in cursor:

print('{0:20}{1:30}{2:15}{3:30}'.format(record[0], record[1], record[2], record[3]))

def delete_record(name):

sql = "DELETE FROM book WHERE name = %s"


value = (name,)

cursor.execute(sql, value)

db.commit()

if cursor.rowcount == 0:

print("Record not found")

else:

print("Record deleted successfully")

def modify_record(name):

sql = "SELECT * FROM book WHERE name = %s"

value = (name,)

cursor.execute(sql, value)

record = cursor.fetchone()

if record is None:

print("No such record exists")

else:

while True:

print("\nPress the option you want to edit: ")

print("1. Name")

print("2. Address")

print("3. Mobile")

print("4. BACK")

print()

ch = int(input("Select Your Option (1-4): "))

if ch == 1:

new_name = input("Enter new name: ")


sql = "UPDATE book SET name = %s WHERE name = %s"

values = (new_name, name)

cursor.execute(sql, values)

db.commit()

print(cursor.rowcount, "record updated successfully")

elif ch == 2:

new_address = input("Enter new address: ")

sql = "UPDATE book SET address = %s WHERE name = %s"

values = (new_address, name)

cursor.execute(sql, values)

db.commit()

print(cursor.rowcount, "record updated successfully")

elif ch == 3:

new_mobile = input("Enter new mobile : ")

sql = "UPDATE book SET mobile = %s WHERE name = %s"

values = (new_mobile, name)

cursor.execute(sql, values)

db.commit()

print(cursor.rowcount, "record updated successfully")

elif ch == 4:

break

else:

print("Invalid choice !!!\n")

def main():

while True:
print("\nMAIN MENU ")

print("1. ADD NEW RECORD")

print("2. SEARCH RECORD")

print("3. DISPLAY ALL RECORDS")

print("4. DELETE RECORD")

print("5. MODIFY RECORD")

print("6. EXIT")

print()

ch = int(input("Select Your Option (1-6): "))

print()

if ch == 1:

print("ADD NEW RECORD")

create_record()

elif ch == 2:

print("SEARCH RECORD BY NAME")

name = input("Enter name: ")

search(name)

elif ch == 3:

print("DISPLAY ALL RECORDS")

display_all()

elif ch == 4:

print("DELETE RECORD")

name = input("Enter name: ")

delete_record(name)

elif ch == 5:
print("MODIFY RECORD")

name = input("Enter name: ")

modify_record(name)

elif ch == 6:

print("Thanks for using Contact Book")

db.close()

break

else:

print("Invalid choice")

main()
OUTPUT:
10. STRING HANDLING AND REGULAR EXPRESSION
import re

print(" \n ************ STRING HANLING AND REGULAR EXPRESSION


**************** \n ")

string1 = str(input(" Enter the String 1 : "))

string2= str(input(" Enter the String 2 : "))

print("\n -------- String Length---------- \n ")

print ( "The String 1 Length is :", len(string1))

print ( "The String 2 Length is :", len(string2))

print(" \n -------- String Concatenation ---------- \n ")

string3=string1+string2

print("Concatenation string is :",string3)

print("\n -------- Capitalize a String---------- \n ")

x= string1.upper()

y= string2.upper()

print(x)

print(y)

print(" \n ---------------- String Copy --------------- \n")

print("Original string:", string1)

copied_string = string1[:]

print ("Copy of the string: ",copied_string)

print("\n ------------- String Replace---------------\n")

rep3=string1.replace(string1,string2)

print (" The Replaced content is : \n",rep3)

print("\n ------------- Match Function --------------- \n")


match_object = re.match(r'.w* (.w?) (.w*?)' , string1, re.M|re.I)

if match_object:

print ("match object group : ", match_object.group())

print ("match object 1 group : ", match_object.group(1))

print ("match object 2 group : ", match_object.group(2))

else:

print ( "There isn't any match!!" )

print("\n ------------------Split Function -------------\n")

pattern = ' '

line = "Learn Python through tutorials on javatpoint"

result = re.split( pattern, line)

print("Original String",line)

print("When maxsplit = 0, result:", result)


OUTPUT:

You might also like