PYTHON MAIN PRGMs
PYTHON MAIN PRGMs
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:
# 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:
#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:
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.")
# 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)
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:
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")
print("\nStudent 2:")
student2.display_info()
student2.promote()
print("\nStudent 3:")
student3.display_info()
student3.promote()
OUTPUT:
RESULT:
import mysql.connector
# Connect to MySQL
connection = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="address_book"
)
Contacts:
(1, 'John Doe', '[email protected]', '123-456-7890')
ID: 1
Name: John Doe
Email: [email protected]
Phone: 123-456-7890
RESULT:
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 = "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: