0% found this document useful (0 votes)
2 views55 pages

Python PDF

The document contains various Python functions and scripts for performing mathematical calculations, such as finding averages, calculating areas and volumes of geometric shapes, and handling user input. It also includes examples of string manipulations, conditionals, and basic data processing. Overall, the document serves as a comprehensive guide for basic programming tasks in Python.

Uploaded by

ajaydelhi1678
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)
2 views55 pages

Python PDF

The document contains various Python functions and scripts for performing mathematical calculations, such as finding averages, calculating areas and volumes of geometric shapes, and handling user input. It also includes examples of string manipulations, conditionals, and basic data processing. Overall, the document serves as a comprehensive guide for basic programming tasks in Python.

Uploaded by

ajaydelhi1678
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/ 55

# Function to calculate the average of three numbers

def find_average(num1, num2, num3):


average = (num1 + num2 + num3) / 3
return average
# Input: Taking three numbers from the user
number1 = float(input("Enter the first number: "))
number2 = float(input("Enter the second number: "))
number3 = float(input("Enter the third number: "))

# Calculate the average


average = find_average(number1, number2, number3)

# Output: Display the result


print("The average of", number1, ",", number2, "and", number3, "is:",
average)

Enter the first number: 5


Enter the second number: 4
Enter the third number: 7

The average of 5.0 , 4.0 and 7.0 is: 5.333333333333333

def calculate_sum_and_percentage():
"""Calculates the sum of 5 subjects and finds the percentage.

Returns:
A tuple containing the sum of marks and the percentage.
"""

marks = []
for i in range(5):
mark = float(input(f"Enter marks for subject {i+1}: "))
marks.append(mark)

total_marks = sum(marks)
percentage = (total_marks / (5 * 100)) * 100

return total_marks, percentage

if __name__ == "__main__":
total_marks, percentage = calculate_sum_and_percentage()
print(f"Total Marks: {total_marks}")
print(f"Percentage: {percentage:.2f}%")

Enter marks for subject 1: 89


Enter marks for subject 2: 98
Enter marks for subject 3: 85
Enter marks for subject 4: 88
Enter marks for subject 5: 99
Total Marks: 459.0
Percentage: 91.80%

def calculate_gross_salary(basic_salary):
"""Calculates the gross salary given the basic salary.

Args:
basic_salary: The basic salary of the employee.

Returns:
The gross salary of the employee.
"""

# Assuming standard allowances:


da = 0.40 * basic_salary # Dearness Allowance (40% of basic salary)
hra = 0.20 * basic_salary # House Rent Allowance (20% of basic
salary)

gross_salary = basic_salary + da + hra

return gross_salary

if __name__ == "__main__":
basic_salary = float(input("Enter Basic Salary: "))
gross_salary = calculate_gross_salary(basic_salary)
print(f"Gross Salary: {gross_salary}")

Enter Basic Salary: 89466

Gross Salary: 143145.6

import math

def calculate_area_of_circle(radius):
"""Calculates the area of a circle.

Args:
radius: The radius of the circle.

Returns:
The area of the circle.
"""

area = math.pi * radius * radius


return area

if __name__ == "__main__":
radius = float(input("Enter the radius of the circle: "))
area = calculate_area_of_circle(radius)
print(f"The area of the circle is: {area:.2f}")
Enter the radius of the circle: 7

The area of the circle is: 153.94

def calculate_area_of_rectangle(length, width):


"""Calculates the area of a rectangle.

Args:
length: The length of the rectangle.
width: The width of the rectangle.

Returns:
The area of the rectangle.
"""

area = length * width


return area

if __name__ == "__main__":
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = calculate_area_of_rectangle(length, width)
print(f"The area of the rectangle is: {area}")

Enter the length of the rectangle: 8


Enter the width of the rectangle: 9

The area of the rectangle is: 72.0

def calculate_area_of_square(side):
"""Calculates the area of a square.

Args:
side: The length of one side of the square.

Returns:
The area of the square.
"""
area = side * side
return area

if __name__ == "__main__":
side = float(input("Enter the side of the square: "))
area = calculate_area_of_square(side)
print(f"The area of the square is: {area}")

Enter the side of the square: 56

The area of the square is: 3136.0

import math
def calculate_circle_properties(radius):
"""Calculates the area and circumference of a circle.

Args:
radius: The radius of the circle.

Returns:
A tuple containing the area and circumference of the circle.
"""
area = math.pi * radius * radius
circumference = 2 * math.pi * radius
return area, circumference

if __name__ == "__main__":
radius = float(input("Enter the radius of the circle: "))
area, circumference = calculate_circle_properties(radius)
print(f"Area of the circle: {area:.2f}")
print(f"Circumference of the circle: {circumference:.2f}")

Enter the radius of the circle: 45

Area of the circle: 6361.73


Circumference of the circle: 282.74

import math

def calculate_area_of_scalene_triangle(side1, side2, side3):


"""Calculates the area of a scalene triangle using Heron's formula.

Args:
side1, side2, side3: The lengths of the three sides of the
triangle.

Returns:
The area of the scalene triangle.
"""
s = (side1 + side2 + side3) / 2 # Semi-perimeter
area = math.sqrt(s * (s - side1) * (s - side2) * (s - side3))
return area

if __name__ == "__main__":
side1 = float(input("Enter the length of side 1: "))
side2 = float(input("Enter the length of side 2: "))
side3 = float(input("Enter the length of side 3: "))
area = calculate_area_of_scalene_triangle(side1, side2, side3)
print(f"The area of the scalene triangle is: {area:.2f}")

Enter the length of side 1: 8


Enter the length of side 2: 6
Enter the length of side 3: 9
The area of the scalene triangle is: 23.53

def calculate_area_of_right_triangle(base, height):


"""Calculates the area of a right-angled triangle.

Args:
base: The base of the right-angled triangle.
height: The height of the right-angled triangle.

Returns:
The area of the right-angled triangle.
"""
area = 0.5 * base * height
return area

if __name__ == "__main__":
base = float(input("Enter the base of the right-angled triangle: "))
height = float(input("Enter the height of the right-angled triangle:
"))
area = calculate_area_of_right_triangle(base, height)
print(f"The area of the right-angled triangle is: {area}")

Enter the base of the right-angled triangle: 8


Enter the height of the right-angled triangle: 45

The area of the right-angled triangle is: 180.0

def calculate_area_of_trapezium(base1, base2, height):


"""Calculates the area of a trapezium.

Args:
base1: The length of the first base.
base2: The length of the second base.
height: The perpendicular distance between the bases.

Returns:
The area of the trapezium.
"""
area = 0.5 * (base1 + base2) * height
return area

if __name__ == "__main__":
base1 = float(input("Enter the length of the first base: "))
base2 = float(input("Enter the length of the second base: "))
height = float(input("Enter the height of the trapezium: "))
area = calculate_area_of_trapezium(base1, base2, height)
print(f"The area of the trapezium is: {area}")

Enter the length of the first base: 8


Enter the length of the second base: 5
Enter the height of the trapezium: 9
The area of the trapezium is: 58.5

#Area of a Rhombus
D1 = float(input("Diagonal 1: "))
D2 = float(input("Diagonal 2: "))
Area = (1 / 2) * D1 * D2
print(Area)

#area of parallelogram
#Base*Height
B = float(input("Base: "))
H = float(input("Height: "))
Area = B * H
print(Area)

#Volume and surface area of cuboids


#v = lbh
def cuboid_volume(l, w, h):
"""Calculate the volume of a cuboid."""
return l * w * h

def cuboid_surface_area(l, w, h):


"""Calculate the surface area of a cuboid."""
return 2 * (l * w + w * h + h * l)

l = float(input("Enter the length of the cuboid: "))


w = float(input("Enter the width of the cuboid: "))
h = float(input("Enter the height of the cuboid: "))

v = cuboid_volume(l, w, h)
sa = cuboid_surface_area(l, w, h)

print(f"Volume of the cuboid: {v}")


print(f"Surface area of the cuboid: {sa}")

#vol and surface area of cylinder


import math
r = float(input("Radius: "))
h = float(input("height: "))
SA = 2 * math.pi * r * (r + h)
vol = math.pi * (r ** 2) * h
print("Surface Area:", SA, "Volume:", vol)

#vol and surface area of cylinder


import math
r = float(input("Radius: "))
h = float(input("height: "))
SA = 2 * math.pi * r * (r + h)
vol = math.pi * (r ** 2) * h
print("Surface Area:", SA, "Volume:", vol)
Surface Area: 345.57519189487726 Volume: 471.23889803846896

#Swap two variables


a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
temp = a
a = b
b = temp
print("After swapping:")
print("First number:", a)
print("Second number:", b)

#vol and surface area of cylinder


import math
r = float(input("Radius: "))
h = float(input("height: "))
SA = 2 * math.pi * r * (r + h)
vol = math.pi * (r ** 2) * h
print("Surface Area:", SA, "Volume:", vol)

Surface Area: 345.57519189487726 Volume: 471.23889803846896

#Swap two variables w/o using third variable


a = int(input("Enter the first variable (a): "))
b = int(input("Enter the second variable (b): "))

a = a + b
b = a - b
a = a - b

print(f"After swapping: a = {a}, b = {b}")

#Fahrenheit to celsius
f = float(input("Fahrenheit: "))
c = (f - 32) * 5 / 9
print("F is equal to","c:", c)

#Simple Interest
p = float(input("Principal Amount: "))
r = float(input("Rate of Interest: "))
t = float(input("Time(in years): "))
SI = (p * r * t) / 100
print("Simple Interest:", SI)

#Surface area and volume of cone


import math

def cone_surface_area(radius, height):


"""Calculate the surface area of a cone."""
slant_height = math.sqrt(radius**2 + height**2)
return math.pi * radius * (radius + slant_height)
def cone_volume(radius, height):
"""Calculate the volume of a cone."""
return (1 / 3) * math.pi * radius**2 * height
radius = float(input("Enter the radius of the base of the cone: "))
height = float(input("Enter the height of the cone: "))
surface_area = cone_surface_area(radius, height)
volume = cone_volume(radius, height)
print(f"Surface Area of the cone: {surface_area:.2f}")
print(f"Volume of the cone: {volume:.2f}")

Surface Area of the cone: 665.40


Volume of the cone: 523.60

#Surface area and volume of sphere


import math

def sphere_surface_area(radius):
"""Calculate the surface area of a sphere."""
return 4 * math.pi * radius**2
def sphere_volume(radius):
"""Calculate the volume of a sphere."""
return (4 / 3) * math.pi * radius**3
radius = float(input("Enter the radius of the sphere: "))
surface_area = sphere_surface_area(radius)
volume = sphere_volume(radius)
print(f"Surface Area of the sphere: {surface_area:.2f}")
print(f"Volume of the sphere: {volume:.2f}")

Surface Area of the sphere: 314.16


Volume of the sphere: 523.60

#Perimeter of a circle rectangle and triangle


import math

def circle_perimeter(radius):
"""Calculate the perimeter of a circle."""
return 2 * math.pi * radius
def rectangle_perimeter(length, width):
"""Calculate the perimeter of a rectangle."""
return 2 * (length + width)
def triangle_perimeter(a, b, c):
"""Calculate the perimeter of a triangle."""
return a + b + c
radius = float(input("Enter the radius of the circle: "))
circle_p = circle_perimeter(radius)
print(f"Perimeter of the circle: {circle_p:.2f}")
length = float(input("\nEnter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
rectangle_p = rectangle_perimeter(length, width)
print(f"Perimeter of the rectangle: {rectangle_p:.2f}")
a = float(input("\nEnter the first side of the triangle: "))
b = float(input("Enter the second side of the triangle: "))
c = float(input("Enter the third side of the triangle: "))
triangle_p = triangle_perimeter(a, b, c)
print(f"Perimeter of the triangle: {triangle_p:.2f}")

x=input("Enter a word")
y=x.upper()
print(y)

ZAHID

x=input("Enter a word")
y=x.lower()
print(y)

zaihd

string = "Hello World!"


vowels = "aeiouAEIOU"
result = ''.join([char for char in string if char in vowels or not
char.isalpha()])
print(result)

eo o!

string = "Hello 123!"


letters = sum(1 for char in string if char.isalpha())
digits = sum(1 for char in string if char.isdigit())
spaces = sum(1 for char in string if char.isspace())
others = len(string) - (letters + digits + spaces)
print(f"Letters: {letters}, Digits: {digits}, Spaces: {spaces},
Others: {others}")

Letters: 5, Digits: 3, Spaces: 1, Others: 1

string = "Hello World! Welcome to Python"


words = string.split()
print(len(words))

string1 = "Hello"
string2 = "World"
concatenated = string1 + string2
print(concatenated)

HelloWorld
string = "hello"
sorted_string = ''.join(sorted(string))
print(sorted_string)

ehllo

string = "Hello"
length = len(string)
print(length)

string = "Hello"
length = 0
for i in string:
length += 1
print(length)

string = "A man a plan a canal Panama"


cleaned_string = ''.join(filter(str.isalnum, string)).lower()
is_palindrome = cleaned_string == cleaned_string[::-1]
print(is_palindrome)

True

name = "RAM KUMAR"


initials = ''.join([part[0].upper() for part in name.split()])
print(initials)

RK

names = ["John", "Alice", "Bob"]


sorted_names = sorted(names)
print(sorted_names)

['Alice', 'Bob', 'John']

a, b = 10, 20
if a > b:
print(f"The greatest number is {a}")
else:
print(f"The greatest number is {b}")

The greatest number is 20

a, b = 10, 10
if a == b:
print("The numbers are equal")
else:
print("The numbers are not equal")
The numbers are equal

num = -5
if num > 0:
print("The number is positive")
else:
print("The number is negative")

The number is negative

num = 15
if num % 5 == 0:
print("The number is divisible by 5")
else:
print("The number is not divisible by 5")

The number is divisible by 5

a, b = 25, 30
if a == b:
print("The numbers are equal")
else:
print("The numbers are not equal")

The numbers are not equal

a, b, c = 15, 25, 10
if a > b and a > c:
print(f"The greatest number is {a}")
elif b > c:
print(f"The greatest number is {b}")
else:
print(f"The greatest number is {c}")

The greatest number is 25

a, b, c = 15, 25, 10
if a > b:
if a > c:
print(f"The greatest number is {a}")
else:
print(f"The greatest number is {c}")
else:
if b > c:
print(f"The greatest number is {b}")
else:
print(f"The greatest number is {c}")

The greatest number is 25

char="Shah Rukh Khan"


if char.islower():
print(char.upper())
else:
print(char.lower())

shah rukh khan

year = 2024
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")

2024 is a leap year

char = 'e'
if char.lower() in 'aeiou':
print(f"{char} is a vowel")
else:
print(f"{char} is a consonant")

e is a vowel

x, y = -5, 10
if x > 0 and y > 0:
print("Point is in the first quadrant")
elif x < 0 and y > 0:
print("Point is in the second quadrant")
elif x < 0 and y < 0:
print("Point is in the third quadrant")
elif x > 0 and y < 0:
print("Point is in the fourth quadrant")
else:
print("Point is on the axis")

Point is in the second quadrant

a, b = complex(2, 3), complex(4, 5)


result = a + b
print(f"The sum of the complex numbers is {result}")

The sum of the complex numbers is (6+8j)

import math
a, b, c = 1, -7, 12
discriminant = math.sqrt(b**2 - 4*a*c)
root1 = (-b + discriminant) / (2 * a)
root2 = (-b - discriminant) / (2 * a)
print(f"The roots are {root1} and {root2}")

The roots are 4.0 and 3.0


day_number = 3
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"]
if 1 <= day_number <= 7:
print(days[day_number - 1])
else:
print("Invalid day number")

Tuesday

color_letter = 'R'
colors = {"R": "Red", "G": "Green", "B": "Blue", "Y": "Yellow", "P":
"Purple"}
print(colors.get(color_letter.upper(), "Invalid color letter"))

Red

operator = '+'
a, b = 10, 5
if operator == '+':
print(a + b)
elif operator == '-':
print(a - b)
elif operator == '*':
print(a * b)
elif operator == '/':
print(a / b)
else:
print("Invalid operator")

15

choice = 1
if choice == 1: # Circle
radius = 7
print(f"Area of the circle: {3.14 * radius**2}")
elif choice == 2: # Square
side = 5
print(f"Area of the square: {side**2}")
elif choice == 3: # Rectangle
length, width = 8, 4
print(f"Area of the rectangle: {length * width}")
elif choice == 4: # Triangle
base, height = 6, 3
print(f"Area of the triangle: {0.5 * base * height}")
else:
print("Invalid choice")

Area of the circle: 153.86


myset={1,2,3,4,5,6}
edp={3,6,9}
print("myset : ",myset)
print("set2 :",edp)
print("union :",myset.union(edp))
print("intersection :",myset.intersection(edp))
print("difference",myset.difference(edp))

myset : {1, 2, 3, 4, 5, 6}
set2 : {9, 3, 6}
union : {1, 2, 3, 4, 5, 6, 9}
intersection : {3, 6}
difference {1, 2, 4, 5}

def remove_duplicates(lst):
unique_set = set(lst)
return list(unique_set)

my_list = [1, 2, 2, 3, 4, 4, 5]
print("Original List:", my_list)

result = remove_duplicates(my_list)
print("List After Removing Duplicates:", result)

Original List: [1, 2, 2, 3, 4, 4, 5]


List After Removing Duplicates: [1, 2, 3, 4, 5]

def is_subset(set1, set2):


return set1.issubset(set2)

set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}

if is_subset(set1, set2):
print("set1 is a subset of set2")
else:
print("set1 is not a subset of set2")

set1 is a subset of set2

def count_char_frequency(input_str):
char_count = {}
for char in input_str:
char_count[char] = char_count.get(char, 0) + 1
return char_count

input_str = "programming"
print("Input String:", input_str)

result = count_char_frequency(input_str)
print("Character Frequency:", result)
fruits:{'banana', 'apple'}
veggies:{'cauliflower', 'beans'}

def create_dict(keys, values):


return dict(zip(keys, values))

keys = ["name", "age", "city"]


values = ["Alice", 25, "New York"]
result = create_dict(keys, values)
print("Created Dictionary:", result)

Word List: ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']


Word Occurrences: {'apple': 3, 'banana': 2, 'orange': 1}

def merge_and_sort_dicts(dict1, dict2):


merged_dict = {**dict1, **dict2}
sorted_dict = dict(sorted(merged_dict.items()))
return sorted_dict

dict1 = {3: 'three', 1: 'one', 4: 'four'}


dict2 = {2: 'two', 5: 'five'}

print("Dictionary 1:", dict1)


print("Dictionary 2:", dict2)

Dictionary 1: {3: 'three', 1: 'one', 4: 'four'}


Dictionary 2: {2: 'two', 5: 'five'}

data={"fruits":{"apple","banana"},"veggies":{"beans","cauliflower"}}
for i ,v in data.items():
print(f"{i}:{v}")

Created Dictionary: {'name': 'Alice', 'age': 25, 'city': 'New York'}

def word_occurrences(word_list):
word_count = {}
for word in word_list:
word_count[word] = word_count.get(word, 0) + 1
return word_count

words = ["apple", "banana", "apple", "orange", "banana", "apple"]


print("Word List:", words)

result = word_occurrences(words)
print("Word Occurrences:", result)

Word List: ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']


Word Occurrences: {'apple': 3, 'banana': 2, 'orange': 1}

import re

def extract_emails(text):
email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
emails = re.findall(email_pattern, text)
return emails

text = "Please contact us at [email protected] or [email protected]


for more information. You can also reach out to [email protected]."

emails = extract_emails(text)

print("Extracted Emails:")
print(emails)

Extracted Emails:
['[email protected]', '[email protected]', '[email protected]']

import re

def validate_phone_number(phone_number):
phone_pattern = r'\d{3}-\d{3}-\d{4}'
if re.fullmatch(phone_pattern, phone_number):
return True
else:
return False

phone_numbers = ["123-456-7890", "987-654-321", "123-4567-890", "123-


456-7890"]

print("Phone Number Validation Results:")


for number in phone_numbers:
print(f"{number}: {'Valid' if validate_phone_number(number) else
'Invalid'}")

#Question-1
def generate_primes(n):
if n < 2:
return []

primes = []

for num in range(2, n + 1):


is_prime = True

for i in range(2, int(num ** 0.5) + 1):


if num % i == 0:
is_prime = False
break

if is_prime:
primes.append(num)
return primes

n = 20
print(generate_primes(n))

[2, 3, 5, 7, 11, 13, 17, 19]

#question-2
def is_armstrong(num):
digits = [int(d) for d in str(num)]
power = len(digits)
return num == sum(d ** power for d in digits)

print(is_armstrong(153))
print(is_armstrong(370))
print(is_armstrong(123))

True
True
False

#Question -3
def convert_temperature(temp, to_scale):
if to_scale.lower() == 'fahrenheit':
return (temp * 9/5) + 32
elif to_scale.lower() == 'celsius':
return (temp - 32) * 5/9
else:
return "Invalid scale. Use 'celsius' or 'fahrenheit'."

print(convert_temperature(25, 'fahrenheit'))
print(convert_temperature(77, 'celsius'))

77.0
25.0

#Question-5
def is_perfect(num):
if num <= 1:
return False

divisors = [i for i in range(1, num) if num % i == 0]

return sum(divisors) == num


print(is_perfect(6))
print(is_perfect(28))
print(is_perfect(12))

True
True
False

#Question-4
def find_divisors(num):
divisors = [i for i in range(1, num + 1) if num % i == 0]
return divisors
print(find_divisors(6))
print(find_divisors(28))

[1, 2, 3, 6]
[1, 2, 4, 7, 14, 28]

#Question-6
import math

def find_divisors(num):
divisors = []
for i in range(1, int(math.sqrt(num)) + 1):
if num % i == 0:
divisors.append(i)
if i != num // i:
divisors.append(num // i)
divisors.remove(num)
return divisors

def is_perfect(num):
if num <= 1:
return False
divisors = find_divisors(num)
return sum(divisors) == num

print(is_perfect(6))
print(is_perfect(28))
print(is_perfect(12))

True
True
False

#Question-8
def longest_word(sentence):

words = sentence.split()
longest = max(words, key=len)

return longest

sentence = "The quick brown fox jumped over the lazy dog"
print(longest_word(sentence))

jumped

#Question_7
def are_anagrams(s1, s2):

s1 = s1.replace(" ", "").lower()


s2 = s2.replace(" ", "").lower()

return sorted(s1) == sorted(s2)

s1 = "listen"
s2 = "silent"
print(are_anagrams(s1, s2))

s1 = "hello"
s2 = "world"
print(are_anagrams(s1, s2))

True
False

#Question-9
import math

def is_strong(num):

num_str = str(num)

sum_of_factorials = sum(math.factorial(int(digit)) for digit in


num_str)

return sum_of_factorials == num

print(is_strong(145))
print(is_strong(123))
True
False

#Question-10
def factorial(n):

if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

num = 5
print(f"The factorial of {num} is {factorial(num)}")

The factorial of 5 is 120

#Question-11
def average_of_three(num1, num2, num3):

average = (num1 + num2 + num3) / 3


return average

num1 = 10
num2 = 20
num3 = 30
result = average_of_three(num1, num2, num3)
print(f"The average of {num1}, {num2}, and {num3} is {result}")

The average of 10, 20, and 30 is 20.0

#Question-12
def calculate_percentage(marks):

total_marks = sum(marks)

maximum_marks = 500

percentage = (total_marks / maximum_marks) * 100


return total_marks, percentage

marks = [85, 90, 78, 92, 88]


total_marks, percentage = calculate_percentage(marks)

print(f"Total marks obtained: {total_marks}")


print(f"Percentage: {percentage:.2f}%")
Total marks obtained: 433
Percentage: 86.60%

#Question-13
import math

def area_of_circle(radius):

area = math.pi * radius ** 2


return area

radius = 5
area = area_of_circle(radius)
print(f"The area of the circle with radius {radius} is {area:.2f}")

The area of the circle with radius 5 is 78.54

#Question-14
def area_of_rectangle(length, width):

area = length * width


return area

length = 10
width = 5
area = area_of_rectangle(length, width)
print(f"The area of the rectangle with length {length} and width
{width} is {area}")

The area of the rectangle with length 10 and width 5 is 50

#Question-15
import math

def area_and_circumference_of_circle(radius):

area = math.pi * radius ** 2

circumference = 2 * math.pi * radius

return area, circumference

radius = 7
area, circumference = area_and_circumference_of_circle(radius)
print(f"The area of the circle with radius {radius} is {area:.2f}")
print(f"The circumference of the circle with radius {radius} is
{circumference:.2f}")
The area of the circle with radius 7 is 153.94
The circumference of the circle with radius 7 is 43.98

#Question-16
import math

def area_of_scalene_triangle(a, b, c):

s = (a + b + c) / 2

area = math.sqrt(s * (s - a) * (s - b) * (s - c))

return area

a = 5
b = 6
c = 7
area = area_of_scalene_triangle(a, b, c)
print(f"The area of the scalene triangle with sides {a}, {b}, and {c}
is {area:.2f}")

The area of the scalene triangle with sides 5, 6, and 7 is 14.70

#Question-17
def area_of_right_angle_triangle(base, height):

area = 0.5 * base * height


return area

base = 6
height = 8
area = area_of_right_angle_triangle(base, height)
print(f"The area of the right-angled triangle with base {base} and
height {height} is {area}")

The area of the right-angled triangle with base 6 and height 8 is 24.0

#Question-18
def area_of_parallelogram(base, height):

area = base * height


return area

base = 10
height = 5
area = area_of_parallelogram(base, height)
print(f"The area of the parallelogram with base {base} and height
{height} is {area}")

The area of the parallelogram with base 10 and height 5 is 50

#Question-19
def cube_volume_and_surface_area(side):

volume = side ** 3

surface_area = 6 * side ** 2

return volume, surface_area

side = 4
volume, surface_area = cube_volume_and_surface_area(side)
print(f"The volume of the cube with side {side} is {volume}")
print(f"The surface area of the cube with side {side} is
{surface_area}")

The volume of the cube with side 4 is 64


The surface area of the cube with side 4 is 96

#Question-20
import math

def cylinder_volume_and_surface_area(radius, height):

volume = math.pi * radius ** 2 * height

surface_area = 2 * math.pi * radius * (radius + height)

return volume, surface_area

radius = 5
height = 10
volume, surface_area = cylinder_volume_and_surface_area(radius,
height)

print(f"The volume of the cylinder with radius {radius} and height


{height} is {volume:.2f}")
print(f"The surface area of the cylinder with radius {radius} and
height {height} is {surface_area:.2f}")

The volume of the cylinder with radius 5 and height 10 is 785.40


The surface area of the cylinder with radius 5 and height 10 is 471.24
# Define a global variable
count = 0

def increment():
global count # Declare the global variable
count += 1 # Modify the global variable
print(f"Count inside the function: {count}")

# Call the function


increment()

# Print the global variable after modification


print(f"Count outside the function: {count}")

def outer_function():
message = "Hello"

def inner_function():
nonlocal message # Declaring message as nonlocal
message += ", World!" # Modifying the variable from the outer
function
print(f"Inner function message: {message}")

inner_function()
print(f"Outer function message after modification: {message}")

outer_function()

# Recursion
def sum_natural_numbers(n):
# Base case: if n is 1, the sum is 1
if n == 1:
return 1
# Recursive case: n + sum of numbers up to n-1
return n + sum_natural_numbers(n - 1)

# Example usage
n = 10
result = sum_natural_numbers(n)
print(f"The sum of the first {n} natural numbers is: {result}")

def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case: n * factorial of (n-1)
return n * factorial(n - 1)

# Example usage
number = 5
result = factorial(number)
print(f"The factorial of {number} is: {result}")

def fibonacci(n):
# Base cases: Fibonacci(0) = 0, Fibonacci(1) = 1
if n == 0:
return 0
elif n == 1:
return 1
# Recursive case: Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2)
return fibonacci(n - 1) + fibonacci(n - 2)

# Example usage
n = 10
result = fibonacci(n)
print(f"The {n}th Fibonacci number is: {result}")

def tower_of_hanoi(n, source, target, auxiliary):


if n == 1:
# Base case: Move the last disk directly from source to target
print(f"Move disk 1 from {source} to {target}")
return
# Move n-1 disks from source to auxiliary, using target as an
auxiliary
tower_of_hanoi(n - 1, source, auxiliary, target)
# Move the nth disk from source to target
print(f"Move disk {n} from {source} to {target}")
# Move the n-1 disks from auxiliary to target, using source as an
auxiliary
tower_of_hanoi(n - 1, auxiliary, target, source)

# Example usage
n = 3 # Number of disks
tower_of_hanoi(n, 'A', 'C', 'B') # A is source, C is target, B is
auxiliary

def gcd(a, b):


# Base case: if b is 0, the GCD is a
if b == 0:
return a
# Recursive case: GCD of b and a % b
return gcd(b, a % b)

# Example usage
num1 = 48
num2 = 18
result = gcd(num1, num2)
print(f"The GCD of {num1} and {num2} is: {result}")

def sum_of_digits(n):
# Base case: if n is a single digit, return n
if n < 10:
return n
# Recursive case: add the last digit to the sum of the remaining
digits
return (n % 10) + sum_of_digits(n // 10)

# Example usage
number = 1234
result = sum_of_digits(number)
print(f"The sum of digits of {number} is: {result}")

# Lambda Function
# Lambda function to check if a number is even or odd
is_even = lambda x: x % 2 == 0

# Example usage
number = 7
if is_even(number):
print(f"{number} is even.")
else:
print(f"{number} is odd.")

# Lambda function to calculate the square of a number


square = lambda x: x ** 2

number = 5
result = square(number)
print(f"The square of {number} is: {result}")

# Lambda function to find the larger of two numbers


larger = lambda x, y: x if x > y else y

num1 = 8
num2 = 5
result = larger(num1, num2)
print(f"The larger of {num1} and {num2} is: {result}")

# List of dictionaries
people = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35},
{"name": "David", "age": 28}
]

# Sort the list of dictionaries by the 'age' key


sorted_people = sorted(people, key=lambda x: x["age"])

# Example usage
print("Sorted list of people by age:")
for person in sorted_people:
print(person)

# Lambda function to calculate the product of two numbers


product = lambda x, y: x * y

# Example usage
num1 = 6
num2 = 7
result = product(num1, num2)
print(f"The product of {num1} and {num2} is: {result}")

# Lambda function to extract the second element from a tuple


second_element = lambda t: t[1]

# Example usage
my_tuple = (10, 20, 30, 40)
result = second_element(my_tuple)
print(f"The second element of the tuple is: {result}")

# List of words
words = ["apple", "is", "a", "banana", "cat", "dog", "elephant"]

# Filter words with length less than 4 using a lambda function


filtered_words = list(filter(lambda word: len(word) >= 4, words))

# Example usage
print("Words with length 4 or greater:")
print(filtered_words)
# List of numbers
numbers = [15, 30, 10, 25, 50, 45, 60, 7, 18]

# Filter numbers divisible by both 3 and 5 using a lambda function


divisible_by_3_and_5 = list(filter(lambda x: x % 3 == 0 and x % 5 ==
0, numbers))

# Example usage
print("Numbers divisible by both 3 and 5:")
print(divisible_by_3_and_5)

# Functional Programming Tools (map, filter, reduce)


# Map
# List of temperatures in Celsius
celsius_temps = [0, 25, 30, 100, -10]

# Convert Celsius to Fahrenheit using map() and a lambda function


fahrenheit_temps = list(map(lambda c: (c * 9/5) + 32, celsius_temps))

# Example usage
print("Temperatures in Fahrenheit:")
print(fahrenheit_temps)

# List of strings
words = ["hello", "world", "python", "is", "awesome"]

# Capitalize the first letter of each word using map() and a lambda
function
capitalized_words = list(map(lambda word: word.capitalize(), words))

# Example usage
print("Capitalized words:")
print(capitalized_words)

# List of numbers
numbers = [1, 2, 3, 4, 5]

# Find the square of all numbers using map() and a lambda function
squared_numbers = list(map(lambda x: x ** 2, numbers))

# Example usage
print("Squared numbers:")
print(squared_numbers)

# Two lists of numbers


list1 = [1, 2, 3, 4, 5]
list2 = [10, 20, 30, 40, 50]

# Add corresponding elements of the two lists using map() and a lambda
function
sum_lists = list(map(lambda x, y: x + y, list1, list2))

# Example usage
print("Sum of corresponding elements:")
print(sum_lists)

# List of strings
tasks = ["task1", "task2", "task3", "task4"]

# Append "_done" to each string using map() and a lambda function


tasks_done = list(map(lambda task: task + "_done", tasks))

# Example usage
print("Updated tasks:")
print(tasks_done)

# Filter
# 22. Use filter() to find all even numbers in a list
# List of numbers
numbers = [10, 15, 22, 33, 44, 55, 60, 71, 80]

# Filter out even numbers using filter() and a lambda function


even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

# Example usage
print("Even numbers in the list:")
print(even_numbers)

# List of strings
words = ["apple", "is", "banana", "cat", "elephant", "dog", "python"]

# Filter out strings with length less than 5 using filter() and a
lambda function
long_words = list(filter(lambda word: len(word) >= 5, words))

# Example usage
print("Words with length 5 or greater:")
print(long_words)

# Function to check if a number is prime


def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True

# List of numbers
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17]
# Filter prime numbers using filter() and the is_prime function
prime_numbers = list(filter(is_prime, numbers))

# Example usage
print("Prime numbers in the list:")
print(prime_numbers)

# List of numbers
numbers = [10, -5, 20, -15, 30, -2, 0, -8, 25]

# Filter out negative numbers using filter() and a lambda function


positive_numbers = list(filter(lambda x: x >= 0, numbers))

# Example usage
print("Positive numbers in the list:")
print(positive_numbers)

# List of words
words = ["apple", "banana", "avocado", "cherry", "apricot",
"blueberry", "pear"]

# Specific letter to check for (e.g., "a")


letter = "a"

# Filter words starting with the specific letter using filter() and a
lambda function
words_starting_with_letter = list(filter(lambda word:
word.startswith(letter), words))

# Example usage
print(f"Words starting with the letter '{letter}':")
print(words_starting_with_letter)

# Reduce
# 27. Use reduce() to find the product of all numbers in a list.
from functools import reduce

# List of numbers
numbers = [1, 2, 3, 4, 5]

# Use reduce() to find the product of all numbers in the list


product = reduce(lambda x, y: x * y, numbers)

# Example usage
print("Product of all numbers in the list:", product)

from functools import reduce

# List of numbers
numbers = [5, 12, 3, 19, 8, 7]
# Use reduce() to find the maximum number in the list
max_number = reduce(lambda x, y: x if x > y else y, numbers)

# Example usage
print("Maximum number in the list:", max_number)

from functools import reduce

# List of numbers
numbers = [1, 2, 3, 4, 5]

# Use reduce() to calculate the sum of the squares of all numbers


sum_of_squares = reduce(lambda x, y: x + y**2, numbers, 0)

# Example usage
print("Sum of the squares of all numbers:", sum_of_squares)

from functools import reduce

# Custom factorial function using reduce()


def factorial(n):
if n == 0 or n == 1:
return 1
return reduce(lambda x, y: x * y, range(1, n + 1))

# Example usage
n = 5
print(f"Factorial of {n} is:", factorial(n))

# 1. Write a custom module mathutils.py with functions for:


# Calculating factorial of a number.
# Checking if a number is prime.
# mathutils.py

# Function to calculate the factorial of a number


def factorial(n):
if n == 0 or n == 1:
return 1
result = 1
for i in range(2, n + 1):
result *= i
return result

# Function to check if a number is prime


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
# 2. Create a package stringutils with modules:
# ○ string_operations.py: Functions to reverse a string and check for
# palindrome.
# ○ case_operations.py: Functions to convert a string to uppercase and
# lowercase.
# stringutils/string_operations.py

# Function to reverse a string


def reverse_string(s):
return s[::-1]

# Function to check if a string is a palindrome


def is_palindrome(s):
return s == s[::-1]

# Function to check if a string is a palindrome


def is_palindrome(s):
return s == s[::-1]

# stringutils/case_operations.py

# Function to convert a string to uppercase


def to_uppercase(s):
return s.upper()

# Function to convert a string to lowercase


def to_lowercase(s):
return s.lower()

# stringutils/case_operations.py

# Function to convert a string to uppercase


def to_uppercase(s):
return s.upper()

# Function to convert a string to lowercase


def to_lowercase(s):
return s.lower()

# 3. Write a program to explore the os module:


# ○ Create a directory.
# ○ List all files in the directory.
# ○ Delete the created directory.
import os

# Step 1: Create a directory


directory_name = "my_test_directory"

# Check if the directory already exists to avoid errors


if not os.path.exists(directory_name):
os.mkdir(directory_name)
print(f"Directory '{directory_name}' created.")
else:
print(f"Directory '{directory_name}' already exists.")

# Step 2: List all files in the directory


# This will list files in the current directory or specified directory
files_in_directory = os.listdir(directory_name)
if files_in_directory:
print(f"Files in '{directory_name}': {files_in_directory}")
else:
print(f"No files in '{directory_name}'.")

# Step 3: Delete the created directory


# Make sure the directory is empty before deletion
try:
os.rmdir(directory_name)
print(f"Directory '{directory_name}' deleted.")
except OSError as e:
print(f"Error deleting directory '{directory_name}': {e}")

# Use the random module to:


# ○ Generate 10 random numbers between 1 and 100.
# ○ Simulate rolling a dice.
import random

# Step 1: Generate 10 random numbers between 1 and 100


random_numbers = [random.randint(1, 100) for _ in range(10)]
print("10 Random numbers between 1 and 100:")
print(random_numbers)

# Step 2: Simulate rolling a dice (random number between 1 and 6)


dice_roll = random.randint(1, 6)
print("\nSimulated dice roll:")
print(dice_roll)

# Create a package mathpackage with the following modules:


# ○ arithmetic.py: Functions for addition, subtraction,
multiplication, and division.
# ○ geometry.py: Functions to calculate the area of a circle and
rectangle
# mathpackage/arithmetic.py

# Function for addition


def add(a, b):
return a + b

# Function for subtraction


def subtract(a, b):
return a - b
# Function for multiplication
def multiply(a, b):
return a * b

# Function for division


def divide(a, b):
if b != 0:
return a / b
else:
return "Division by zero is not allowed."

# mathpackage/geometry.py
import math

# Function to calculate the area of a circle


def area_of_circle(radius):
return math.pi * (radius ** 2)

# Function to calculate the area of a rectangle


def area_of_rectangle(length, width):
return length * width

# main.py

from mathpackage import arithmetic, geometry

# Example usage of arithmetic functions


print("Addition:", arithmetic.add(10, 5))
print("Subtraction:", arithmetic.subtract(10, 5))
print("Multiplication:", arithmetic.multiply(10, 5))
print("Division:", arithmetic.divide(10, 5))

# Example usage of geometry functions


print("Area of Circle with radius 5:", geometry.area_of_circle(5))
print("Area of Rectangle with length 10 and width 5:",
geometry.area_of_rectangle(10, 5))

# 6. Write a program to:


# ○ Import and explore the sys module.
# ○ Print the Python version and platform details.
import sys

# Step 1: Print Python version


print("Python version:")
print(sys.version)

# Step 2: Print platform details


print("\nPlatform details:")
print(sys.platform)
# Step 3: Print the version of the Python interpreter
print("\nPython interpreter version details:")
print(sys.version_info)

# Optional: List of command line arguments passed to the script


print("\nCommand line arguments passed to the script:")
print(sys.argv)

# 7. Write a function in a custom module that:


# ○ Reads a file and counts the frequency of each word.
# fileutils.py

from collections import Counter


import string

def count_word_frequency(file_path):
"""Reads a file and counts the frequency of each word."""

# Initialize a Counter to store word frequencies


word_count = Counter()

try:
with open(file_path, 'r') as file:
# Read the content of the file
text = file.read()

# Convert text to lowercase and remove punctuation


text = text.lower()
text = text.translate(str.maketrans('', '',
string.punctuation))

# Split the text into words


words = text.split()

# Update the word count


word_count.update(words)

return word_count
except FileNotFoundError:
return f"The file '{file_path}' was not found."
except Exception as e:
return f"An error occurred: {e}"

# main.py

import fileutils
# Example usage of count_word_frequency
file_path = 'example.txt' # Provide the path to your file
word_frequency = fileutils.count_word_frequency(file_path)

# Display the word frequency count


print(word_frequency)

# 8. Use the dir() function to list all available functions in:


# ○ The random module.○ A custom module you create.
import random

# List all available functions in the random module


print("Functions in the 'random' module:")
print(dir(random))

# mymodule.py

def function_one():
return "This is function one."

def function_two():
return "This is function two."

def function_three():
return "This is function three."

import mymodule

# List all available functions in the custom module


print("Functions in the 'mymodule' module:")
print(dir(mymodule))

# Write a script that uses the datetime module to:


# ○ Print the current date and time.
# ○ Calculate the number of days between two dates
import datetime

# Print the current date and time


current_datetime = datetime.datetime.now()
print(f"Current Date and Time: {current_datetime}")

# Define two dates for comparison


date1 = datetime.date(2025, 1, 1) # Example date 1
date2 = datetime.date(2025, 1, 17) # Example date 2

# Calculate the number of days between the two dates


days_difference = (date2 - date1).days
print(f"Number of days between {date1} and {date2}: {days_difference}
days")

# 10. Create a package utilities with:


# ● An __init__.py file that imports specific functions from its
modules.
# ● Modules for math operations, string operations, and date
operations.
# __init__.py
from .math_operations import add, subtract
from .string_operations import reverse_string, capitalize_string
from .date_operations import get_current_date,
calculate_days_between_dates

# math_operations.py
def add(a, b):
"""Add two numbers."""
return a + b

def subtract(a, b):


"""Subtract two numbers."""
return a - b

# string_operations.py
def reverse_string(s):
"""Reverse the input string."""
return s[::-1]

def capitalize_string(s):
"""Capitalize the first letter of each word in the string."""
return s.title()

# date_operations.py
import datetime

def get_current_date():
"""Get the current date."""
return datetime.date.today()

def calculate_days_between_dates(date1, date2):


"""Calculate the number of days between two dates."""
return (date2 - date1).days

from utilities import add, reverse_string, get_current_date,


calculate_days_between_dates

# Math operation
result = add(5, 3)
print(f"Sum: {result}")

# String operation
reversed_str = reverse_string("hello")
print(f"Reversed String: {reversed_str}")

# Date operation
current_date = get_current_date()
print(f"Current Date: {current_date}")

# Calculate days between two dates


date1 = datetime.date(2025, 1, 1)
date2 = datetime.date(2025, 1, 17)
days_between = calculate_days_between_dates(date1, date2)
print(f"Days Between: {days_between}")

# Tuple Packing
a, b, c = 10, 20, 30
packed_tuple = (a, b, c)
print("Packed Tuple:", packed_tuple)

# Tuple Unpacking
x, y, z = packed_tuple
print("Unpacked Values:", x, y, z)

# Initial values
x = 5
y = 10
print("Before Swap: x =", x, ", y =", y)

# Swapping using tuple unpacking


x, y = y, x
print("After Swap: x =", x, ", y =", y)

# Function to return sum and product


def calculate_sum_and_product(a, b):
return a + b, a * b

# Calling the function and unpacking


sum_result, product_result = calculate_sum_and_product(7, 3)
print("Sum:", sum_result)
print("Product:", product_result)

# Nested tuple
nested_tuple = (1, 2, (3, 4), [5, 6])

# Unpacking
a, b, (c, d), [e, f] = nested_tuple
print("Outer Elements:", a, b)
print("Inner Tuple Elements:", c, d)
print("Inner List Elements:", e, f)
# Sequence
numbers = [1, 2, 3, 4, 5, 6]

# Unpacking
head, *middle, tail = numbers
print("Head:", head)
print("Middle:", middle)
print("Tail:", tail)

# Mutable sequence: List


mutable_list = [1, 2, 3]
print("Original List:", mutable_list)
mutable_list[0] = 10 # Modifying element
print("Modified List:", mutable_list)

# Immutable sequence: Tuple


immutable_tuple = (1, 2, 3)
print("Original Tuple:", immutable_tuple)
try:
immutable_tuple[0] = 10 # Attempting to modify element
except TypeError as e:
print("Error:", e)

# Mutable: List
mutable_list = [1, 2, 3]
print("Original List Memory Address:", id(mutable_list))
mutable_list[0] = 10
print("Modified List Memory Address:", id(mutable_list))

# Immutable: Tuple
immutable_tuple = (1, 2, 3)
print("Original Tuple Memory Address:", id(immutable_tuple))
immutable_tuple = (10, 2, 3) # Reassigning the tuple
print("New Tuple Memory Address:", id(immutable_tuple))

# Mutable: Shopping cart as a list


shopping_cart = ["apple", "banana"]
print("Shopping Cart (Mutable):", shopping_cart)
shopping_cart.append("orange") # Adding an item
print("After Adding Orange:", shopping_cart)

# Immutable: Shopping cart as a tuple


shopping_cart_tuple = ("apple", "banana")
print("Shopping Cart (Immutable):", shopping_cart_tuple)
try:
shopping_cart_tuple += ("orange",) # Attempting to add an item
print("After Adding Orange:", shopping_cart_tuple)
except TypeError as e:
print("Error:", e)
# Mutable: List
mutable_list = [1, 2, 3, 4, 5]
print("Original List:", mutable_list)
mutable_list[1:4] = [20, 30, 40] # Slicing and replacing
print("Modified List:", mutable_list)

# Immutable: Tuple
immutable_tuple = (1, 2, 3, 4, 5)
print("Original Tuple:", immutable_tuple)
new_tuple = immutable_tuple[:1] + (20, 30, 40) + immutable_tuple[4:]
print("Modified Tuple (New Object):", new_tuple)

# Mutable: List
mutable_list = [1, 2, 3]
print("Original List:", mutable_list)
mutable_list += [4, 5]
print("After Concatenation (Mutable):", mutable_list)

# Immutable: Tuple
immutable_tuple = (1, 2, 3)
print("Original Tuple:", immutable_tuple)
new_tuple = immutable_tuple + (4, 5)
print("After Concatenation (Immutable):", new_tuple)

from collections import Counter

sentence = "This is a test. This test is only a test."


words = sentence.lower().replace('.', '').split()
word_count = Counter(words)
print("Word Frequencies:", word_count)

text = " Hello, Python programming is fun! "

# Using strip()
stripped_text = text.strip()
print("Stripped Text:", stripped_text)

# Using split()
words = stripped_text.split()
print("Split into Words:", words)

# Using join()
joined_text = "-".join(words)
print("Joined Text:", joined_text)

# Using find()
index = stripped_text.find("Python")
print("Index of 'Python':", index)

# Using replace()
replaced_text = stripped_text.replace("fun", "awesome")
print("Replaced Text:", replaced_text)

def format_string(s):
words = s.split()
formatted_words = [word[0].upper() + word[1:].swapcase() for word
in words]
return " ".join(formatted_words)

input_string = "hello world! python is AMAZING."


result = format_string(input_string)
print("Formatted String:", result)

def find_palindromic_substrings(s):
palindromes = []
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
substring = s[i:j]
if substring == substring[::-1] and len(substring) > 1:
palindromes.append(substring)
return palindromes

input_string = "abba madam racecar level"


palindromes = find_palindromic_substrings(input_string)
print("Palindromic Substrings:", palindromes)

import re

text = """
Contact us at [email protected] or [email protected].
Visit our website at https://www.example.com or http://example.org.
"""

# Extracting email addresses


emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]
{2,}\b', text)
print("Email Addresses:", emails)

# Extracting URLs
urls = re.findall(r'https?://[^\s]+', text)
print("URLs:", urls)

squares = [x**2 for x in range(1, 11)]


print("List of Squares:", squares)

input_string = "List comprehensions are powerful!"


vowels = "aeiouAEIOU"
filtered_string = [char for char in input_string if char not in
vowels]
print("String without Vowels:", "".join(filtered_string))
two_d_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
flattened_list = [item for sublist in two_d_list for item in sublist]
print("Flattened List:", flattened_list)

primes = [x for x in range(2, 51) if all(x % y != 0 for y in range(2,


int(x**0.5) + 1))]
print("Prime Numbers Between 1 and 50:", primes)

keys = ["name", "age", "city"]


values = ["Alice", 25, "New York"]

dictionary = {keys[i]: values[i] for i in range(len(keys))}


print("Dictionary:", dictionary)

# Creating a tuple
my_tuple = (10, 20, 30, 40, 50)

# Accessing elements
print("First Element:", my_tuple[0])
print("Last Element:", my_tuple[-1])

# Demonstrating immutability
try:
my_tuple[1] = 25 # Attempting to modify
except TypeError as e:
print("Error:", e)

# List of tuples
tuple_list = [(1, 3), (4, 1), (2, 5), (3, 2)]

# Sorting by the second element


sorted_list = sorted(tuple_list, key=lambda x: x[1])
print("Sorted List of Tuples:", sorted_list)

# Tuple of numbers
numbers = (10, 25, 5, 40, 15)

# Finding max and min


max_value = max(numbers)
min_value = min(numbers)
print("Maximum Value:", max_value)
print("Minimum Value:", min_value)

# Creating a dictionary with tuples as keys


coordinates = {
(0, 0): "Origin",
(1, 2): "Point A",
(3, 4): "Point B"
}

# Accessing values using tuple keys


print("Value at (1, 2):", coordinates[(1, 2)])
print("Value at (0, 0):", coordinates[(0, 0)])

# Tuple
my_tuple = (10, 20, 30, 40, 50)

# Finding the index of an element


element = 30
if element in my_tuple:
index = my_tuple.index(element)
print(f"Index of {element}:", index)
else:
print(f"{element} is not in the tuple.")

# Two lists
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

# Combining using zip()


zipped_list = list(zip(list1, list2))
print("Zipped List:", zipped_list)

# Unpacking the tuples


for num, char in zipped_list:
print(f"Number: {num}, Character: {char}")

def separate_even_odd(numbers):
even = [num for num in numbers if num % 2 == 0]
odd = [num for num in numbers if num % 2 != 0]
return even, odd

# Example usage
numbers = [1, 2, 3, 4, 5, 6]
even_list, odd_list = separate_even_odd(numbers)
print("Even Numbers:", even_list)
print("Odd Numbers:", odd_list)

import copy

# Original list
original_list = [(1, 2), (3, 4), (5, 6)]

# Shallow copy
shallow_copy = copy.copy(original_list)

# Deep copy
deep_copy = copy.deepcopy(original_list)

# Modifying the original list


original_list[0] = (10, 20)
original_list[1][0] = 30 # This would raise an error as tuples are
immutable

print("Original List:", original_list)


print("Shallow Copy:", shallow_copy)
print("Deep Copy:", deep_copy)

def sum_from_string(number_string):
numbers = [int(num) for num in number_string.split(',')]
return sum(numbers)

# Example usage
number_string = "1,2,3,4,5"
result = sum_from_string(number_string)
print("Sum of Numbers:", result)

def to_uppercase_unique(strings):
return list({string.upper() for string in strings})

# Example usage
string_list = ["apple", "banana", "Apple", "BANANA", "cherry"]
result = to_uppercase_unique(string_list)
print("Unique Uppercase Strings:", result)

Unique Uppercase Strings: ['APPLE', 'CHERRY', 'BANANA']

for i in range(1, 11):


print(i)

1
2
3
4
5
6
7
8
9
10

for i in range(1, 21):


if i % 2 == 0:
print(i)

2
4
6
8
10
12
14
16
18
20

for i in range(1, 21):


if i % 2 != 0:
print(i)

1
3
5
7
9
11
13
15
17
19

for i in range(1, 101):


if i % 7 == 0:
print(i)

7
14
21
28
35
42
49
56
63
70
77
84
91
98

for i in range(1, 11):


print(f"2 x {i} = {2 * i}")

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
for i in range(1, 11):
print(f"5 X {i} = {5 * i}")

5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50

total_sum = 0
for i in range(1, 51):
total_sum += i
print("The sum of the first 50 natural numbers is:", total_sum)

The sum of the first 50 natural numbers is: 1275

number = int(input("Enter a number: "))


factorial = 1

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


factorial *= i

print(f"The factorial of {number} is: {factorial}")

The factorial of 300 is:


3060575122164406360353704612972686293885888041735769994167767412594765
3317671686746551529142247757334993914788870172636886426390775900315422
6842927906974559841225476930271954604008012215776252176854255965356903
5067887252643218962642993652045764488303889097539434896254360532259807
7652127082243763944912012867867536830571229368194364995646049816645022
7716500185176546469340112226034729724066333258583506870150169794168850
3537521375549102891264071571548302822849379526365801452352331569364822
3343679925459409527682060806223281238738388081704960000000000000000000
0000000000000000000000000000000000000000000000000000000

number = int(input("Enter a number: "))


factorial = 1
i = 1

while i <= number:


factorial *= i
i += 1

print(f"The factorial of {number} is: {factorial}")

The factorial of 5 is: 120


number = int(input("Enter a number: "))
sum_of_digits = 0

while number > 0:


sum_of_digits += number % 10
number //= 10

print("The sum of the digits is:", sum_of_digits)

The sum of the digits is: 5

number = int(input("Enter a number: "))


reverse_number = 0

while number > 0:


reverse_number = reverse_number * 10 + number % 10
number //= 10

print("The reversed number is:", reverse_number)

number = int(input("Enter a number: "))


sum_of_divisors = 0

for i in range(1, number):


if number % i == 0:
sum_of_divisors += i

if sum_of_divisors == number:
print(f"{number} is a Perfect Number.")
else:
print(f"{number} is not a Perfect Number.")

print("Armstrong numbers from 1 to 1000:")


for number in range(1, 1001):
temp = number
sum_of_cubes = 0

while temp > 0:


digit = temp % 10
sum_of_cubes += digit ** 3
temp //= 10

if sum_of_cubes == number:
print(number, end=" ")

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


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

result = 1
for _ in range(N):
result *= X
print(f"The value of {X}^{N} is: {result}")

def factorial(num):
result = 1
for i in range(1, num + 1):
result *= i
return result

n = int(input("Enter n: "))
r = int(input("Enter r: "))

if r > n:
print("Invalid input! r cannot be greater than n.")
else:
nCr = factorial(n) // (factorial(r) * factorial(n - r))
print(f"The value of {n}C{r} is: {nCr}")

n = int(input("Enter the number of terms: "))


a, b = 0, 1
print("Fibonacci series:")

for _ in range(n):
print(a, end=" ")
a, b = b, a + b

print("The first 10 natural numbers:")


for i in range(1, 11):
print(i, end=" ")

number = int(input("Enter a number: "))


original_number = number
reverse_number = 0

while number > 0:


reverse_number = reverse_number * 10 + number % 10
number //= 10

if original_number == reverse_number:
print(f"{original_number} is a Palindrome.")
else:
print(f"{original_number} is not a Palindrome.")

number = int(input("Enter a number: "))


original_number = number
reverse_number = 0

while number > 0:


reverse_number = reverse_number * 10 + number % 10
number //= 10
if original_number == reverse_number:
print(f"{original_number} is a Palindrome.")
else:
print(f"{original_number} is not a Palindrome.")

number = int(input("Enter a number: "))


original_number = number
sum_of_cubes = 0

while number > 0:


digit = number % 10
sum_of_cubes += digit ** 3
number //= 10

if original_number == sum_of_cubes:
print(f"{original_number} is an Armstrong Number.")
else:
print(f"{original_number} is not an Armstrong Number.")

number = int(input("Enter a number: "))


sum_of_divisors = 0

for i in range(1, number):


if number % i == 0:
sum_of_divisors += i

if sum_of_divisors == number:
print(f"{number} is a Perfect Number.")
else:
print(f"{number} is not a Perfect Number.")

number = int(input("Enter a number: "))


is_prime = True

if number <= 1:
is_prime = False
else:
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
is_prime = False
break

if is_prime:
print(f"{number} is a Prime Number.")
else:
print(f"{number} is not a Prime Number.")

print("Prime numbers between 50 and 500:")


for number in range(50, 501):
is_prime = True
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
is_prime = False
break
if is_prime:
print(number, end=" ")

sum_of_primes = 0

for number in range(2, 1001):


is_prime = True
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
is_prime = False
break
if is_prime:
sum_of_primes += number

print("The sum of all prime numbers from 1 to 1000 is:",


sum_of_primes)

for i in range(5):
print("* " * 5)

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

for i in range(1, 6):


print("* " * i)

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

for i in range(1, 6):


for j in range(1, i + 1):
print(j, end=" ")
print()

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

for i in range(1, 6):


print(f"{i} " * i)
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

char = 65 # ASCII value of 'A'


for i in range(1, 6):
print(chr(char) + "" * (i - 1) + (chr(char) + "") * (i - 1))
char += 1

A
BB
CCC
DDDD
EEEEE

for i in range(5, 0, -1):

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

for i in range(5, 0, -1):


for j in range(1, i + 1):
print(j, end=" ")
print()

1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

for i in range(1, 6):


print("* " * (2 * i - 1))

from math import factorial


n=5
for i in range(0,n):
for j in range(n-i+1):
print(end=" ")
for k in range(i+1):
print(factorial(i)//(factorial(k)*factorial(i-k)),end=" ")
print()

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

char = 65 # ASCII value for 'A'


for i in range(1, 6):
for j in range(i):
print(chr(char), end=" ")
char += 1
print()

A
B C
D E F
G H I J
K L M N O

for i in range(1, 6):


for j in range(i):
print(chr(65 + i - j), end="")
for j in range(i - 1, 0, -1):
print(chr(65 + i - j), end="")
print()

B
CBB
DCBBC
EDCBBCD
FEDCBBCDE

for i in range(5, 0, -1):


for j in range(1, i + 1):
print(f"{j}{chr(65 + j - 1)}", end="")
print()

1A2B3C4D5E
1A2B3C4D
1A2B3C
1A2B
1A

for i in range(5):
for j in range(i, -1, -1):
print(j, end=" ")
for j in range(1, i + 1):
print(j, end=" ")
print()

0
1 0 1
2 1 0 1 2
3 2 1 0 1 2 3
4 3 2 1 0 1 2 3 4

for i in range(0, 12, 2):


print(i, end=", " if i < 10 else "")

a = int(input("Enter the first term: "))


d = int(input("Enter the common difference: "))
n = int(input("Enter the number of terms: "))
sum_ap = (n / 2) * (2 * a + (n - 1) * d)
print(f"The sum of the A.P. series is: {sum_ap}")

The sum of the A.P. series is: 91.0

a = int(input("Enter the first term: "))


r = int(input("Enter the common ratio: "))
n = int(input("Enter the number of terms: "))
sum_gp = a * (1 - r**n) / (1 - r) if r != 1 else a * n
print(f"The sum of the G.P. series is: {sum_gp}")

The sum of the G.P. series is: 19531.0

a = int(input("Enter the first term: "))


d = int(input("Enter the common difference: "))
n = int(input("Enter the number of terms: "))
sum_hp = 0
for i in range(n):
sum_hp += 1 / (a + i * d)
print(f"The sum of the H.P. series is: {sum_hp}")

The sum of the H.P. series is: 0.8675055880938234

n = int(input("Enter the number of terms: "))


val = 1
for i in range(n):
print(val, end=", " if i < n - 1 else "")
val *= 2

1, 2, 4, 8, 16, 32, 64

for i in range(-8, 9, 2):


print(i, end=", " if i < 8 else "")

-8, -6, -4, -2, 0, 2, 4, 6, 8

n = int(input("Enter the value of n: "))


sum_series = (n * (n + 1)) // 2
print(f"The sum of the series is: {sum_series}")

The sum of the series is: 15


n = int(input("Enter the value of n: "))
sum_series = sum(i * i for i in range(1, n + 1))
print(f"The sum of the series is: {sum_series}")

The sum of the series is: 91

n = int(input("Enter the value of n: "))


sum_series = 0
for i in range(1, n + 1):
sum_series += sum(range(1, i + 1))
print(f"The sum of the series is: {sum_series}")

def factorial(num):
if num == 0 or num == 1:
return 1
else:
return num * factorial(num - 1)

n = int(input("Enter the value of n: "))


sum_series = sum(factorial(i) for i in range(1, n + 1))
print(f"The sum of the series is: {sum_series}")

The sum of the series is: 873

n = int(input("Enter the value of n: "))


sum_series = sum(i ** i for i in range(1, n + 1))
print(f"The sum of the series is: {sum_series}")

The sum of the series is: 50069

def factorial(num):
if num == 0 or num == 1:
return 1
else:
return num * factorial(num - 1)

n = int(input("Enter the value of n: "))


sum_series = sum(factorial(i) / i for i in range(1, n + 1))
print(f"The sum of the series is: {sum_series}")

The sum of the series is: 874.0

n = int(input("Enter the value of n: "))


sum_series = sum((i ** i) / i for i in range(1, n + 1))
print(f"The sum of the series is: {sum_series}")

The sum of the series is: 701.0

def factorial(num):
if num == 0 or num == 1:
return 1
else:
return num * factorial(num - 1)

n = int(input("Enter the value of n: "))


sum_series = sum((i ** i) / factorial(i) for i in range(1, n + 1))
print(f"The sum of the series is: {sum_series}")

The sum of the series is: 272.40972222222223

n = int(input("Enter the number of terms: "))


sum_series = 0
for i in range(1, n + 1):
if i % 2 != 0:
sum_series += i / (i + 1)
else:
sum_series -= i / (i + 1)
print(f"The sum of the series is: {sum_series}")

The sum of the series is: 0.6345238095238096

n = int(input("Enter the number of terms: "))


val = 1
for i in range(n):
print(val, end=", " if i < n - 1 else "")
val *= 3

1, 3, 9, 27, 81, 243, 729

n = int(input("Enter the number of terms: "))


val = 2
for i in range(n):
print(val, end=", " if i < n - 1 else "")
val += (i + 1) * (i + 2)

2, 4, 10, 22, 42, 72

n = int(input("Enter the number of terms: "))


val = 1
for i in range(n):
print(val, end=", " if i < n - 1 else "")
val += (i + 1) * (i + 1)

1, 2, 6, 15, 31, 56

You might also like