1.
Program to check whether a year is leap year or not
def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
# Example usage:
year_to_check = 2024 # Replace this with the year you want to check
if is_leap_year(year_to_check):
print(f"{year_to_check} is a leap year.")
else:
print(f"{year_to_check} is not a leap year.")
2. Program to check duplicate character in a given string
def has_duplicate_characters(input_string):
char_count = {}
for char in input_string:
# Check if the character is already in the dictionary
if char in char_count:
return True # Duplicate character found
else:
char_count[char] = 1
return False # No duplicate characters found
# Example usage:
input_str = "hello" # Replace this with the string you want to check
if has_duplicate_characters(input_str):
print(f"The string '{input_str}' has duplicate characters.")
else:
print(f"The string '{input_str}' does not have duplicate characters.")
3. Program demonstrate various string functions and
operations
# Define a sample string
sample_string = "Hello, World! How are you doing?"
# Basic string operations
print("Original String:", sample_string)
print("Length of String:", len(sample_string))
print("Concatenation:", sample_string + " I'm fine, thank you!")
print("Repetition:", sample_string * 2)
print("Substring:", sample_string[7:12]) # Extracting substring
print("Uppercase:", sample_string.upper())
print("Lowercase:", sample_string.lower())
print("Replace 'World' with 'Universe':", sample_string.replace("World", "Universe"))
# String formatting
name = "Alice"
age = 30
formatted_string = f"Hello, {name}! You are {age} years old."
print("Formatted String:", formatted_string)
# String splitting and joining
word_list = sample_string.split() # Split the string into a list of words
print("Split String:", word_list)
joined_string = "-".join(word_list) # Join the words using a hyphen
print("Joined String:", joined_string)
# Checking for substring existence
substring = "How"
if substring in sample_string:
print(f"'{substring}' found in the string.")
else:
print(f"'{substring}' not found in the string.")
# Stripping whitespace
whitespace_string = " Some spaces "
print("Original String:", whitespace_string)
print("Stripped String:", whitespace_string.strip())
# String formatting using the format() method
formatted_string_2 = "My name is {} and I'm {} years old.".format("Bob", 25)
print("Formatted String (using format()):", formatted_string_2)
4. Program to demonstrate list function and operatins
# Creating a sample list
sample_list = [1, 2, 3, 4, 5]
# Basic list operations
print("Original List:", sample_list)
print("Length of List:", len(sample_list))
print("Concatenation:", sample_list + [6, 7, 8])
print("Repetition:", sample_list * 2)
print("Accessing Elements:")
print("First Element:", sample_list[0])
print("Slicing:", sample_list[1:4]) # Extracting a sublist
sample_list[2] = 99 # Modifying an element
print("Modified List:", sample_list)
# List methods
sample_list.append(6) # Appending an element
print("Appended List:", sample_list)
removed_element = sample_list.pop() # Removing and returning the last element
print("Popped Element:", removed_element)
print("List after Pop:", sample_list)
sample_list.extend([7, 8, 9]) # Extending the list with another list
print("Extended List:", sample_list)
sample_list.remove(99) # Removing a specific element
print("List after Removal:", sample_list)
index_of_4 = sample_list.index(4) # Finding the index of an element
print("Index of 4:", index_of_4)
sample_list.insert(2, 100) # Inserting an element at a specific index
print("List after Insertion:", sample_list)
sample_list.reverse() # Reversing the list in place
print("Reversed List:", sample_list)
sorted_list = sorted(sample_list) # Creating a new sorted list
print("Sorted List (new):", sorted_list)
# List comprehension
squared_numbers = [x ** 2 for x in sample_list]
print("Squared Numbers:", squared_numbers)
# Checking for element existence
if 3 in sample_list:
print("3 is present in the list.")
else:
print("3 is not present in the list.")
# Clearing the list
sample_list.clear()
print("Cleared List:", sample_list)
5. Program to demonstrate tuple function and operation
# Creating a sample tuple
sample_tuple = (1, 2, 3, 4, 5)
# Basic tuple operations
print("Original Tuple:", sample_tuple)
print("Length of Tuple:", len(sample_tuple))
print("Concatenation:", sample_tuple + (6, 7, 8))
print("Repetition:", sample_tuple * 2)
print("Accessing Elements:")
print("First Element:", sample_tuple[0])
print("Slicing:", sample_tuple[1:4]) # Extracting a subtuple
# Tuple methods
index_of_3 = sample_tuple.index(3) # Finding the index of an element
print("Index of 3:", index_of_3)
# Tuple comprehension (generating a new tuple based on existing tuple)
squared_numbers = tuple(x ** 2 for x in sample_tuple)
print("Squared Numbers:", squared_numbers)
# Checking for element existence
if 3 in sample_tuple:
print("3 is present in the tuple.")
else:
print("3 is not present in the tuple.")
# Unpacking a tuple
a, b, *rest = sample_tuple
print("Unpacked Values:")
print("a:", a)
print("b:", b)
print("Rest:", rest)
# Nested tuple
nested_tuple = ((1, 2), (3, 4), (5, 6))
print("Nested Tuple:", nested_tuple)
# Converting a tuple to a list and vice versa
tuple_to_list = list(sample_tuple)
print("Tuple converted to List:", tuple_to_list)
list_to_tuple = tuple(tuple_to_list)
print("List converted to Tuple:", list_to_tuple)
6. Program to demonstrate dictionary function and operation
# Creating a sample dictionary
sample_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
# Basic dictionary operations
print("Original Dictionary:", sample_dict)
print("Length of Dictionary:", len(sample_dict))
print("Accessing Values:")
print("Name:", sample_dict['name'])
print("Age:", sample_dict['age'])
# Dictionary methods
sample_dict['occupation'] = 'Engineer' # Adding a new key-value pair
print("Dictionary after Addition:", sample_dict)
sample_dict['age'] = 31 # Modifying the value of an existing key
print("Dictionary after Modification:", sample_dict)
removed_value = sample_dict.pop('city') # Removing and returning a value by key
print("Removed City:", removed_value)
print("Dictionary after Removal:", sample_dict)
# Getting keys, values, and items
keys = sample_dict.keys()
values = sample_dict.values()
items = sample_dict.items()
print("Keys:", keys)
print("Values:", values)
print("Items:", items)
# Checking for key existence
if 'name' in sample_dict:
print("'name' is a key in the dictionary.")
else:
print("'name' is not a key in the dictionary.")
# Dictionary comprehension
squared_values = {key: value ** 2 for key, value in sample_dict.items()}
print("Squared Values:", squared_values)
# Clearing the dictionary
sample_dict.clear()
print("Cleared Dictionary:", sample_dict)
7. Program to find sum of a digit of number using recursion
def sum_of_digits(n):
# Base case: if the number has only one digit
if n < 10:
return n
else:
# Recursive case: sum the last digit and the sum of the remaining digits
return n % 10 + sum_of_digits(n // 10)
# Example usage:
number = 12345 # Replace this with the number for which you want to find the sum of digits
result = sum_of_digits(number)
print(f"The sum of digits in {number} is {result}.")
8. Program to print inverted star pattern
def inverted_star_pattern(rows):
for i in range(rows, 0, -1):
for j in range(0, rows - i):
print(" ", end="")
for k in range(0, i):
print("*", end="")
print()
# Example usage:
num_rows = 5 # Replace this with the number of rows you want in the pattern
inverted_star_pattern(num_rows)
9. Program to display fibonacci series using recursion
def fibonacci(n):
if n <= 0:
return "Please enter a positive integer."
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
fib_series = fibonacci(n - 1)
fib_series.append(fib_series[-1] + fib_series[-2])
return fib_series
# Example usage:
num_terms = 10 # Replace this with the number of terms you want in the Fibonacci series
result = fibonacci(num_terms)
print(f"Fibonacci Series with {num_terms} terms: {result}")
10. Program to demonstrate set operations
# Create two sample sets
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
# Basic set operations
print("Set 1:", set1)
print("Set 2:", set2)
# Union of sets
union_set = set1.union(set2)
print("Union of Set 1 and Set 2:", union_set)
# Intersection of sets
intersection_set = set1.intersection(set2)
print("Intersection of Set 1 and Set 2:", intersection_set)
# Difference between sets
difference_set1 = set1.difference(set2)
difference_set2 = set2.difference(set1)
print("Difference of Set 1 - Set 2:", difference_set1)
print("Difference of Set 2 - Set 1:", difference_set2)
# Symmetric difference between sets
symmetric_difference_set = set1.symmetric_difference(set2)
print("Symmetric Difference of Set 1 and Set 2:", symmetric_difference_set)
# Checking for subset and superset
is_subset = set1.issubset(set2)
is_superset = set1.issuperset(set2)
print("Is Set 1 a subset of Set 2?", is_subset)
print("Is Set 1 a superset of Set 2?", is_superset)
# Adding and removing elements from a set
set1.add(6)
set2.remove(6)
print("Set 1 after adding element 6:", set1)
print("Set 2 after removing element 6:", set2)
# Clearing a set
set1.clear()
print("Cleared Set 1:", set1)
11. Program to find quotient and reminder of two numbers
def find_quotient_and_remainder(dividend, divisor):
quotient = dividend // divisor
remainder = dividend % divisor
return quotient, remainder
# Example usage:
dividend = int(input("Enter the dividend: "))
divisor = int(input("Enter the divisor: "))
# Ensure that the divisor is not zero to avoid division by zero error
if divisor != 0:
result_quotient, result_remainder = find_quotient_and_remainder(dividend, divisor)
print(f"The quotient of {dividend} divided by {divisor} is {result_quotient}")
print(f"The remainder of {dividend} divided by {divisor} is {result_remainder}")
else:
print("Error: Division by zero is not allowed.")
12. find area and parameter of a circle using class
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
area = math.pi * self.radius ** 2
return area
def calculate_perimeter(self):
perimeter = 2 * math.pi * self.radius
return perimeter
# Example usage:
radius = float(input("Enter the radius of the circle: "))
# Ensure that the radius is non-negative
if radius >= 0:
# Create an instance of the Circle class
circle_instance = Circle(radius)
# Calculate and display the area and perimeter
area = circle_instance.calculate_area()
perimeter = circle_instance.calculate_perimeter()
print(f"The area of the circle with radius {radius} is: {area:.2f}")
print(f"The perimeter of the circle with radius {radius} is: {perimeter:.2f}")
else:
print("Error: Please enter a non-negative radius.")
13. program to remove duplicate from a list
def remove_duplicates(input_list):
unique_list = list(set(input_list))
return unique_list
# Example usage:
input_list = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7]
result_list = remove_duplicates(input_list)
print("Original List:", input_list)
print("List after removing duplicates:", result_list)
14. Program to demonstrate inheritance and method
overriding
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
print(f"{self.name} makes a generic animal sound.")
class Dog(Animal):
def __init__(self, name, breed):
# Call the constructor of the superclass (Animal)
super().__init__(name)
self.breed = breed
def make_sound(self):
print(f"{self.name} barks loudly.")
class Cat(Animal):
def __init__(self, name, color):
# Call the constructor of the superclass (Animal)
super().__init__(name)
self.color = color
def make_sound(self):
print(f"{self.name} meows softly.")
# Example usage:
dog_instance = Dog("Buddy", "Golden Retriever")
cat_instance = Cat("Whiskers", "Gray")
# Using the overridden method for each instance
dog_instance.make_sound()
cat_instance.make_sound()
15. Program to demonstrate multiple inheritance
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
class Employee:
def __init__(self, employee_id, salary):
self.employee_id = employee_id
self.salary = salary
def display_info(self):
print(f"Employee ID: {self.employee_id}, Salary: ${self.salary}")
class Manager(Person, Employee):
def __init__(self, name, age, employee_id, salary, department):
# Call constructors of both base classes
Person.__init__(self, name, age)
Employee.__init__(self, employee_id, salary)
# Additional attribute for Manager class
self.department = department
def display_info(self):
# Call display_info methods of both base classes
Person.display_info(self)
Employee.display_info(self)
print(f"Department: {self.department}")
# Example usage:
manager_instance = Manager("John", 35, "E123", 80000, "HR")
manager_instance.display_info()