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

Python Practical programs

python programs naan mudhalvan

Uploaded by

rbsiva421688
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)
13 views

Python Practical programs

python programs naan mudhalvan

Uploaded by

rbsiva421688
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/ 18

Write a basic python program for ATM Money Distribution

def atm_money_distribution(amount):
# Available denominations in most ATMs
denominations = [2000, 500, 200, 100, 50, 20, 10]

# Dictionary to hold the count of each denomination


distribution = {}

# Go through each denomination and calculate how many of each are needed
for denom in denominations:
if amount >= denom:
count = amount // denom
distribution[denom] = count
amount = amount % denom

# Check if the remaining amount can't be distributed


if amount > 0:
print(f"Cannot distribute remaining amount: {amount}")

return distribution

# Example usage:
amount = int(input("Enter the amount to withdraw: "))
distribution = atm_money_distribution(amount)

if distribution:
print("Money Distribution:")
for denom, count in distribution.items():
print(f"{denom} INR: {count} notes")
Write a basic python program for Sequential Removal
def sequential_removal(lst, remove_count):
print("Original List:", lst)

for i in range(remove_count):
if len(lst) == 0:
print("List is already empty.")
break
# Remove the first element (or any element sequentially)
removed_element = lst.pop(0)
print(f"Removed: {removed_element}, Remaining List: {lst}")

# Example usage:
my_list = [10, 20, 30, 40, 50, 60]
remove_count = int(input("Enter the number of elements to remove sequentially: "))

sequential_removal(my_list, remove_count)
Write a basic python program for String validation
def string_validation(s):
print(f"Validating string: '{s}'")

# Check if all characters in the string are alphabets


if s.isalpha():
print("The string contains only alphabetic characters.")

# Check if all characters in the string are digits


if s.isdigit():
print("The string contains only digits.")

# Check if the string contains alphanumeric characters (letters and numbers)


if s.isalnum():
print("The string contains only alphanumeric characters.")

# Check if the string contains only lowercase characters


if s.islower():
print("The string contains only lowercase letters.")

# Check if the string contains only uppercase characters


if s.isupper():
print("The string contains only uppercase letters.")

# Check if the string starts with a specific character


if s.startswith("A"):
print("The string starts with 'A'.")

# Check if the string ends with a specific character


if s.endswith("Z"):
print("The string ends with 'Z'.")

# Check for spaces in the string


if " " in s:
print("The string contains spaces.")

# Check if the string is empty


if s == "":
print("The string is empty.")
else:
print("The string is not empty.")

# Example usage:
user_string = input("Enter a string to validate: ")
string_validation(user_string)
Write a basic python program for Number Operations
def number_operations(num1, num2):
print(f"Numbers: {num1}, {num2}")

# Addition
addition = num1 + num2
print(f"Addition: {num1} + {num2} = {addition}")

# Subtraction
subtraction = num1 - num2
print(f"Subtraction: {num1} - {num2} = {subtraction}")

# Multiplication
multiplication = num1 * num2
print(f"Multiplication: {num1} * {num2} = {multiplication}")

# Division
if num2 != 0:
division = num1 / num2
print(f"Division: {num1} / {num2} = {division}")
else:
print("Division by zero is not allowed.")

# Modulus (remainder)
if num2 != 0:
modulus = num1 % num2
print(f"Modulus: {num1} % {num2} = {modulus}")

# Exponentiation (num1 raised to the power of num2)


exponentiation = num1 ** num2
print(f"Exponentiation: {num1} ^ {num2} = {exponentiation}")

# Floor Division
if num2 != 0:
floor_division = num1 // num2
print(f"Floor Division: {num1} // {num2} = {floor_division}")

# Example usage:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

number_operations(num1, num2)
Write a basic python program for Duplicate Number
def find_duplicates(nums):
duplicates = []
seen = set() # A set to keep track of seen numbers

for num in nums:


if num in seen and num not in duplicates:
duplicates.append(num) # Add to duplicates if it's already in 'seen' and not in 'duplicates'
else:
seen.add(num) # Add to 'seen' set if it's encountered for the first time

return duplicates

# Example usage:
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
duplicates = find_duplicates(numbers)

if duplicates:
print("Duplicate numbers:", duplicates)
else:
print("No duplicates found.")
Write a basic python program for Intersection of two arrays
def find_intersection(arr1, arr2):
# Convert both lists to sets to find common elements
set1 = set(arr1)
set2 = set(arr2)

# Find the intersection of both sets


intersection = set1.intersection(set2)

# Convert the result back to a list


return list(intersection)

# Example usage:
array1 = list(map(int, input("Enter the first array (numbers separated by spaces): ").split()))
array2 = list(map(int, input("Enter the second array (numbers separated by spaces): ").split()))

intersection = find_intersection(array1, array2)

if intersection:
print("Intersection of the two arrays:", intersection)
else:
print("No common elements.")
write a basic python program for finding First unique character
def first_unique_character(s):
# Create a dictionary to count the frequency of each character
char_count = {}

# Iterate over the string to populate the dictionary


for char in s:
char_count[char] = char_count.get(char, 0) + 1

# Iterate over the string again to find the first unique character
for char in s:
if char_count[char] == 1:
return char

return None # If no unique character is found

# Example usage:
user_input = input("Enter a string: ")
result = first_unique_character(user_input)

if result:
print(f"The first unique character is: '{result}'")
else:
print("No unique character found.")

Output:
Enter a string: swiss
The first unique character is: 'w'
Write a basic python program to Reverse vowels in a given string
def reverse_vowels(s):
vowels = "aeiouAEIOU" # Define vowels (both uppercase and lowercase)
s_list = list(s) # Convert string to a list for easier manipulation
left, right = 0, len(s) - 1

# Use two-pointer technique to reverse vowels


while left < right:
# Move left pointer to the next vowel
if s_list[left] not in vowels:
left += 1
continue

# Move right pointer to the previous vowel


if s_list[right] not in vowels:
right -= 1
continue

# Swap the vowels at the left and right pointers


s_list[left], s_list[right] = s_list[right], s_list[left]

# Move both pointers inward


left += 1
right -= 1

return ''.join(s_list) # Convert list back to string

# Example usage:
user_input = input("Enter a string: ")
result = reverse_vowels(user_input)
print("String after reversing vowels:", result)
Write a basic python program to find Twin Primes
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def find_twin_primes(limit):
twin_primes = []
# Loop through numbers and check for twin primes
for num in range(2, limit):
if is_prime(num) and is_prime(num + 2):
twin_primes.append((num, num + 2))
return twin_primes
# Example usage:
limit = int(input("Enter the limit to find twin primes: "))
twin_primes = find_twin_primes(limit)

if twin_primes:
print("Twin primes up to", limit, ":")
for pair in twin_primes:
print(pair)
else:
print("No twin primes found.")

Output:
Enter the limit to find twin primes: 20
Twin primes up to 20 :
(3, 5)
(5, 7)
(11, 13)
(17, 19)
Write an object oriented python program to calculate Electricity bill
# Define the Customer class
class Customer:
def __init__(self, name, customer_id):
self.name = name
self.customer_id = customer_id

# Method to display customer details


def display_customer_info(self):
print(f"Customer Name: {self.name}")
print(f"Customer ID: {self.customer_id}")

# Define the ElectricityBill class


class ElectricityBill:
def __init__(self, customer, units_consumed):
self.customer = customer
self.units_consumed = units_consumed

# Method to calculate bill based on the units consumed


def calculate_bill(self):
if self.units_consumed <= 100:
rate = 5 # Rate for the first 100 units
elif self.units_consumed <= 300:
rate = 7 # Rate for the next 200 units
else:
rate = 10 # Rate for units above 300

bill_amount = self.units_consumed * rate


return bill_amount

# Method to display the bill details


def display_bill(self):
self.customer.display_customer_info()
bill_amount = self.calculate_bill()
print(f"Units Consumed: {self.units_consumed}")
print(f"Total Bill Amount: ${bill_amount:.2f}")

# Example usage
customer1 = Customer("Alice", 101)
units_consumed = float(input("Enter the number of units consumed: "))

# Create ElectricityBill object and display the bill


bill = ElectricityBill(customer1, units_consumed)
bill.display_bill()
Write an object oriented python program to calculate Discounted price
# Define the Product class
class Product:
def __init__(self, name, price):
self.name = name
self.price = price

# Method to apply a discount to the product


def apply_discount(self, discount_percentage):
discount_amount = (discount_percentage / 100) * self.price
discounted_price = self.price - discount_amount
return discounted_price

# Method to display product details and price


def display_product_info(self):
print(f"Product Name: {self.name}")
print(f"Original Price: ${self.price:.2f}")

# Define a class to handle multiple products and their discounts


class DiscountSystem:
def __init__(self):
self.products = []

# Method to add a product to the system


def add_product(self, product):
self.products.append(product)

# Method to apply discount to all products


def apply_discount_to_all(self, discount_percentage):
for product in self.products:
discounted_price = product.apply_discount(discount_percentage)
print(f"\nDiscounted price for {product.name}: ${discounted_price:.2f}")

# Example usage of the system


product1 = Product("Laptop", 1200)
product2 = Product("Smartphone", 800)
product3 = Product("Headphones", 150)

# Create the discount system and add products


discount_system = DiscountSystem()
discount_system.add_product(product1)
discount_system.add_product(product2)
discount_system.add_product(product3)

# Display original product details


product1.display_product_info()
product2.display_product_info()
product3.display_product_info()

# Apply discount to all products and show the final price


discount_percentage = float(input("\nEnter discount percentage to apply: "))
discount_system.apply_discount_to_all(discount_percentage)
Write a basic python program to implement Name, password generation
import random
import string
# Function to generate a username
def generate_username(first_name, last_name):
username = first_name.lower() + "." + last_name.lower()
return username
# Function to generate a random password
def generate_password(length=8):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))
return password
# Get user input for first and last name
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
# Generate username and password
username = generate_username(first_name, last_name)
password = generate_password(12) # You can specify the length of the password
# Output the result
print(f"Generated Username: {username}")
print(f"Generated Password: {password}")

Output:
Enter your first name: Gomathi
Enter your last name: Nayagam
Generated Username: gomathi.nayagam
Generated Password: v{9dYz\4;"s{
Write a object oriented python program to implement Student attendance record
# Define the Student class
class Student:
def __init__(self, name, roll_number):
self.name = name
self.roll_number = roll_number
self.attendance_record = [] # List to store attendance ('Present' or 'Absent')

# Method to mark attendance


def mark_attendance(self, status):
if status.lower() in ['present', 'absent']:
self.attendance_record.append(status.capitalize())
else:
print("Invalid status! Please use 'Present' or 'Absent'.")

# Method to display the attendance record of the student


def display_attendance(self):
print(f"\nAttendance record for {self.name} (Roll No: {self.roll_number}):")
for day, status in enumerate(self.attendance_record, start=1):
print(f"Day {day}: {status}")

# Define a class to manage a group of students


class AttendanceSystem:
def __init__(self):
self.students = []

# Method to add a student to the system


def add_student(self, name, roll_number):
student = Student(name, roll_number)
self.students.append(student)
print(f"Student {name} added successfully!")

# Method to mark attendance for all students


def mark_all_attendance(self):
for student in self.students:
status = input(f"Enter attendance for {student.name} (Present/Absent): ")
student.mark_attendance(status)

# Method to display attendance records for all students


def display_all_attendance(self):
for student in self.students:
student.display_attendance()

# Usage of the system


attendance_system = AttendanceSystem()

# Adding students to the system


attendance_system.add_student("Alice", 101)
attendance_system.add_student("Bob", 102)

# Mark attendance for all students


attendance_system.mark_all_attendance()

# Display attendance records for all students


attendance_system.display_all_attendance()

You might also like