Python PDF
Python PDF
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
if __name__ == "__main__":
total_marks, percentage = calculate_sum_and_percentage()
print(f"Total Marks: {total_marks}")
print(f"Percentage: {percentage:.2f}%")
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.
"""
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}")
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.
"""
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
Args:
length: The length of the rectangle.
width: The width of the rectangle.
Returns:
The area of the rectangle.
"""
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}")
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}")
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}")
import math
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}")
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}")
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}")
#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)
v = cuboid_volume(l, w, h)
sa = cuboid_surface_area(l, w, h)
a = a + b
b = a - b
a = a - 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)
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}")
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
eo o!
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)
True
RK
a, b = 10, 20
if a > b:
print(f"The greatest number is {a}")
else:
print(f"The greatest number is {b}")
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")
num = 15
if num % 5 == 0:
print("The number is divisible by 5")
else:
print("The number is not divisible by 5")
a, b = 25, 30
if a == b:
print("The numbers are equal")
else:
print("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}")
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}")
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")
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")
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}")
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")
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)
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")
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'}
data={"fruits":{"apple","banana"},"veggies":{"beans","cauliflower"}}
for i ,v in data.items():
print(f"{i}:{v}")
def word_occurrences(word_list):
word_count = {}
for word in word_list:
word_count[word] = word_count.get(word, 0) + 1
return word_count
result = word_occurrences(words)
print("Word Occurrences:", result)
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
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
#Question-1
def generate_primes(n):
if n < 2:
return []
primes = []
if is_prime:
primes.append(num)
return primes
n = 20
print(generate_primes(n))
#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
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 = "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)
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)}")
#Question-11
def average_of_three(num1, num2, num3):
num1 = 10
num2 = 20
num3 = 30
result = average_of_three(num1, num2, num3)
print(f"The average of {num1}, {num2}, and {num3} is {result}")
#Question-12
def calculate_percentage(marks):
total_marks = sum(marks)
maximum_marks = 500
#Question-13
import math
def area_of_circle(radius):
radius = 5
area = area_of_circle(radius)
print(f"The area of the circle with radius {radius} is {area:.2f}")
#Question-14
def area_of_rectangle(length, width):
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}")
#Question-15
import math
def area_and_circumference_of_circle(radius):
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
s = (a + b + c) / 2
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}")
#Question-17
def area_of_right_angle_triangle(base, height):
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):
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}")
#Question-19
def cube_volume_and_surface_area(side):
volume = side ** 3
surface_area = 6 * side ** 2
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}")
#Question-20
import math
radius = 5
height = 10
volume, surface_area = cylinder_volume_and_surface_area(radius,
height)
def increment():
global count # Declare the global variable
count += 1 # Modify the global variable
print(f"Count inside 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}")
# Example usage
n = 3 # Number of disks
tower_of_hanoi(n, 'A', 'C', 'B') # A is source, C is target, B is
auxiliary
# 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.")
number = 5
result = square(number)
print(f"The square of {number} is: {result}")
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}
]
# Example usage
print("Sorted list of people by age:")
for person in sorted_people:
print(person)
# Example usage
num1 = 6
num2 = 7
result = product(num1, num2)
print(f"The product of {num1} and {num2} is: {result}")
# 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"]
# 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]
# Example usage
print("Numbers divisible by both 3 and 5:")
print(divisible_by_3_and_5)
# 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)
# 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"]
# 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]
# 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)
# 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]
# Example usage
print("Positive numbers in the list:")
print(positive_numbers)
# List of words
words = ["apple", "banana", "avocado", "cherry", "apricot",
"blueberry", "pear"]
# 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]
# Example usage
print("Product of all numbers in the list:", product)
# 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)
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Example usage
print("Sum of the squares of all numbers:", sum_of_squares)
# Example usage
n = 5
print(f"Factorial of {n} is:", factorial(n))
# stringutils/case_operations.py
# stringutils/case_operations.py
# mathpackage/geometry.py
import math
# main.py
def count_word_frequency(file_path):
"""Reads a file and counts the frequency of each word."""
try:
with open(file_path, 'r') as file:
# Read the content of the file
text = file.read()
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)
# 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
# math_operations.py
def add(a, b):
"""Add 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()
# 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}")
# 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)
# 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: 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))
# 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)
# 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)
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
import re
text = """
Contact us at [email protected] or [email protected].
Visit our website at https://www.example.com or http://example.org.
"""
# Extracting URLs
urls = re.findall(r'https?://[^\s]+', text)
print("URLs:", urls)
# 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)]
# Tuple of numbers
numbers = (10, 25, 5, 40, 15)
# Tuple
my_tuple = (10, 20, 30, 40, 50)
# Two lists
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
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)
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)
1
2
3
4
5
6
7
8
9
10
2
4
6
8
10
12
14
16
18
20
1
3
5
7
9
11
13
15
17
19
7
14
21
28
35
42
49
56
63
70
77
84
91
98
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)
if sum_of_divisors == number:
print(f"{number} is a Perfect Number.")
else:
print(f"{number} is not a Perfect Number.")
if sum_of_cubes == number:
print(number, end=" ")
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}")
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
if original_number == reverse_number:
print(f"{original_number} is a Palindrome.")
else:
print(f"{original_number} is not a Palindrome.")
if original_number == sum_of_cubes:
print(f"{original_number} is an Armstrong Number.")
else:
print(f"{original_number} is not an Armstrong Number.")
if sum_of_divisors == number:
print(f"{number} is a Perfect Number.")
else:
print(f"{number} is not a Perfect Number.")
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.")
sum_of_primes = 0
for i in range(5):
print("* " * 5)
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
*
* *
* * *
* * * *
* * * * *
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
A
BB
CCC
DDDD
EEEEE
* * * * *
* * * *
* * *
* *
*
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
A
B C
D E F
G H I J
K L M N O
B
CBB
DCBBC
EDCBBCD
FEDCBBCDE
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
1, 2, 4, 8, 16, 32, 64
def factorial(num):
if num == 0 or num == 1:
return 1
else:
return num * factorial(num - 1)
def factorial(num):
if num == 0 or num == 1:
return 1
else:
return num * factorial(num - 1)
def factorial(num):
if num == 0 or num == 1:
return 1
else:
return num * factorial(num - 1)
1, 2, 6, 15, 31, 56