[go: up one dir, main page]

0% found this document useful (0 votes)
33 views43 pages

Py 1204

The document contains a series of Python programming exercises covering various concepts such as variable declaration, arithmetic operations, control structures, loops, and functions. Each exercise includes a code snippet along with expected output. The exercises are designed to help learners understand and practice fundamental programming skills in Python.

Uploaded by

dhruvvasvani624
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)
33 views43 pages

Py 1204

The document contains a series of Python programming exercises covering various concepts such as variable declaration, arithmetic operations, control structures, loops, and functions. Each exercise includes a code snippet along with expected output. The exercises are designed to help learners understand and practice fundamental programming skills in Python.

Uploaded by

dhruvvasvani624
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/ 43

1 Write a program to declare variables of different data types (int,

float, string).
integer_var = 10
float_var = 5.5
string_var = "Hello"
print(f"Integer: {integer_var}, Float: {float_var}, String: {string_var}")

OUTPUT-

Integer: 10, Float: 5.5, String: Hello

2. Write a program to perform basic arithmetic operations (+, -, , /) on


two numbers.
a, b = 10, 5
addition = a + b
subtraction = a - b
multiplication = a * b
division = a / b
print(f"Addition: {addition}, Subtraction: {subtraction}, Multiplication:
{multiplication}, Division: {division}")

OUTPUT-
Addition: 15, Subtraction: 5, Multiplication: 50, Division: 2.0

3. Write a program to demonstrate the use of identifiers and reserved


words.
my_variable = 10 # Valid identifier
another_var = 20 # Valid identifie
r # print = 30 # Error: 'print' is a reserved word
print(f"my_variable: {my_variable}, another_var: {another_var}")

OUTPUT-
my_variable: 10, another_var: 20

4. Write a program to show the difference between expressions and


statements.
expression = 5 + 3
print(f"Expression result: {expression}")
statement = print("This is a statement")

OUTPUT-
Expression result: 8
This is a statement

5. Write a program to display all essential Python libraries (e.g., math,


random).
import math
import random
import os
import sys
print("Essential Python libraries:")
print("math - For mathematical operations")
print("random - For random number generation")
print("os - For operating system interactions")
print("sys - For system-specific parameters")

6. Write a program to explain the concept of indentation in Python.


def greet():
message = "Hello, Python!" # Indented block
print(message) # Indented under function
greet()
# print(message) # Error: Not indented, out of scope
print("Indentation defines code blocks in Python.")
OUTPUT-
Hello, Python!
Indentation defines code blocks in Python.

7. Write a program to comment a block of code using single-line and


multi-line comments.
# This is a single-line comment
print("This will execute")
""" This is a multi-line comment It can span multiple lines This will not execute
"""
print("This will also execute")

OUTPUT-
This will execute
This will also execute

8. Write a program to assign and print multiple variables in a single


line.
a, b, c = 1, 2.5, "Python"
print(f"a: {a}, b: {b}, c: {c}")

OUTPUT-
a: 1 , b: 2.5 , c: Python

9. Write a program to demonstrate the use of operators (e.g., +, -, *, /,


%, ).
a, b = 10, 3
addition = a + b
subtraction = a - b
multiplication = a * b
division = a / b
modulus = a % b
exponent = a ** b
print(f"+: {addition}, -: {subtraction}, *: {multiplication}, /: {division}, %: {modulus},
**: {exponent}")

OUTPUT-
+: 13 , - : 7 , * : 30 , / : 3.3333333333333335 , % : 1 , ** : 1000

10. Write a program to check if a number is positive using an if


statement.
num = float(input("Enter a number: "))
if num > 0:
print(f"{num} is positive! ")
if num < 0:
print(f"{num} is negative! ")
if num.is_integer():
print(f"{num} is a rational integer! ")
else:
print(f"{num} is a rational decimal! ")

OUTPUT-
Enter a number: -9
-9.0 is negative!
-9.0 is a rational integer!

Enter a number: 89
89.0 is positive!
89.0 is a rational integer!

11. Write a program to find the largest of two numbers using if-else.
a, b = map(int, input("Enter two numbers: ").split())
if a > b:
print(f"Largest: {a}")
else:
print(f"Largest: {b}")
OUTPUT-
Enter two numbers: 5 3

Largest: 5

12. Write a program to check voting eligibility (age >= 18) using if-else.
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote")
else: print("You are not eligible to vote")

OUTPUT-
Enter your age: 76

You are eligible to vote

13. Write a program to determine a grade (A, B, C) based on a score


using nested if.
score = float(input("Enter your score: "))
if score >= 90:
if score >= 95:
print("Grade: A+")
else:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else: print("Grade: F")

OUTPUT-
Enter your score: 34
Grade: F

14. Write a program to check if a number is divisible by 3 using if-elif-


else.
num = int(input("Enter a number: "))
if num % 3 == 0:
print(f"{num} is divisible by 3")
elif num % 3 == 1:
print(f"{num} has remainder 1 when divided by 3")
else:
print(f"{num} has remainder 2 when divided by 3")

OUTPUT-
Enter a number: 71
71 has remainder 2 when divided by 3

15. Write a program to find the type of triangle (equilateral, isosceles,


scalene) using if.
a, b, c = map(int, input("Enter three sides: ").split())
if a == b == c:
print("Equilateral triangle")
elif a == b or b == c or a == c:
print("Isosceles triangle")
else:
print("Scalene triangle")

OUTPUT-
Enter three sides: 6 6 7
Isosceles triangle

Enter three sides: 6 6 7


Isosceles triangle

Enter three sides: 3 5 12


Scalene triangle

16. Write a program to check if a character is uppercase using if-else.


char = input("Enter a character: ")
if char.isupper():
print(f"{char} is uppercase")
else:
print(f"{char} is not uppercase")

OUTPUT-
Enter a character: G
G is uppercase

Enter a character: F
F is uppercase

17. Write a program to determine if a year is leap using nested if


conditions.
year = int(input("Enter a year: "))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
else:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")

OUTPUT-
Enter a year: 2009
2009 is not a leap year
Enter a year: 2004
2004 is a leap year

18. Write a program to compare two strings using if-else.


s1, s2 = input("Enter two strings: ").split()
if s1 == s2:
print("Strings are equal")
else:
print("Strings are not equal")
# Explanation: Uses if-else to compare string equality.

OUTPUT-
Enter two strings: 5 5
Strings are equal

Enter two strings: 544 86


Strings are not equal

19. Write a program to check if a number is within a range (10-50)


using if-elif-else.
num = int(input("Enter a number: "))
if num >= 10 and num <= 50:
print(f"{num} is within range 10-50")
elif num < 10:
print(f"{num} is below range")
else:
print(f"{num} is above range")
# Explanation: Uses if-elif-else to check if a number falls within 10-50.

OUTPUT-
Enter a number: 3542
3542 is above range

Enter a number: 5
5 is below ra
20.Print numbers 1 to 10 using a while loop:
i=1
while i <= 10:
print(i)
i += 1

OUTPUT-

1,2,3,4,5,6,7,8,9,10

21.Calculate sum of numbers from 1 to N using a for loop:


n = int(input("Enter a number: "))
sum = 0
for i in range(1, n + 1):
sum += i
print(f"Sum of numbers from 1 to {n} is: {sum}")

OUTPUT-

Enter a number: 3

Sum of numbers from 1 to 3 is: 6

22.Print even numbers up to N using a while loop:


n = int(input("Enter a number: "))
i=2
while i <= n:
print(i) i += 2

OUTPUT-
Enter a number: 8

2,4,6,8

23.Print multiplication table using a for loop:


n = int(input("Enter a number for multiplication table: "))
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")

OUTPUT-

Enter a number for multiplication table: 4


4x1=4
4x2=8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40

24.Reverse a number using a while loop:


num = int(input("Enter a number: "))
reversed_num = 0
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
print(f"Reversed number: {reversed_num}")

OUTPUT-
Enter a number: 57

Reversed number: 75

25. Find factorial of a number using a for loop:


n = int(input("Enter a number: "))
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f"Factorial of {n} is: {factorial}")

OUTPUT-

Enter a number: 5
Factorial of 5 is: 120

26. Print star pattern using nested while loops:


rows = 5
i=0
while i < rows:
j=0
while j <= i:
print("*", end=" ")
j += 1
print()
i += 1

OUTPUT-

**

***
****

*****

27. Count digits in a number using a while loop:


num = int(input("Enter a number: "))
count = 0
while num > 0:
count += 1
num //= 10
print(f"Number of digits: {count}")

OUTPUT-

Enter a number: 54

Number of digits: 2

28. Print numbers in descending order using a for loop:


n = int(input("Enter a number: "))
for i in range(n, 0, -1):
print(i)

OUTPUT-

Enter a number: 5

2
1

29. Sum odd numbers up to N using a while loop:


n = int(input("Enter a number: "))
sum = 0
i=1
while i <= n:
sum += i
i += 2
print(f"Sum of odd numbers up to {n} is: {sum}")

OUTPUT-

Enter a number: 7
Sum of odd numbers up to 7 is: 16

30. Print numbers 1 to 10 and use break to exit at 5:


i=1
while i <= 10:
print(i)
if i == 5:
break
i += 1

OUTPUT-

1
2
3
4
5
31. Print numbers 1 to 10 and skip 5 using continue:
for i in range(1, 11):
if i == 5:
continue
print(i)

OUTPUT-

1
2
3
4
6
7
8

32. Use pass in an empty loop structure:


for i in range(5):
pass
# Placeholder for future code
print("Loop completed with pass")

OUTPUT-

Loop completed with pass

33. Print prime numbers up to N using a for loop with break:


n = int(input("Enter a number: "))
for num in range(2, n + 1):
for i in range(2, num):
if num % i == 0:
break
else:
print(num, "is prime")

OUTPUT-

Enter a number: 6
2 is prime
3 is prime
5 is prime

34. Print a sequence and use continue to skip even numbers:


n = int(input("Enter a number: "))
for i in range(1, n + 1):
if i % 2 == 0:
continue
print(i)

OUTPUT-

Enter a number: 5

35. Demonstrate nested loops with break:


for i in range(1, 6):
for j in range(1, 4):
if j == 2:
break
print(f"i={i}, j={j}")

OUTPUT-
i=1, j=1
i=2, j=1
i=3, j=1
i=4, j=1
i=5, j=1

36. Use continue in a nested loop to skip specific iterations:


for i in range(1, 6):
for j in range(1, 4):
if j == 2:
continue
print(f"i={i}, j={j}")

OUTPUT-

i=1, j=1

i=1, j=3

i=2, j=1

i=2, j=3

i=3, j=1

i=3, j=3

i=4, j=1

37. Exit a loop when a condition is met using break:


sum = 0
while True:
num = int(input("Enter a number (0 to exit): "))
if num == 0:
break
sum += num
print(f"Sum: {sum}")

OUTPUT-

Enter a number (0 to exit): 7


Enter a number (0 to exit): 8
Enter a number (0 to exit): 0
Sum: 15

38.Print a pattern using nested loops with continue:

rows = 5
for i in range(rows):
for j in range(i + 1):
if j % 2 == 0:
continue
print("*", end=" ")
print()

OUTPUT-

**

**

39. Demonstrate the else clause in a for loop:

n = int(input("Enter a number to check if prime: "))


for i in range(2, n):
if n % i == 0:
print(f"{n} is not prime")
break
else:
print(f"{n} is prime")

OUTPUT-

Enter a number to check if prime: 65


65 is not prime

40. Function to add two numbers and return the result:


def add_numbers(a, b):
return a + b
# Test the function
num1 = 5
num2 = 3
result = add_numbers(num1, num2)
print(f"Sum of {num1} and {num2} is: {result}")

OUTPUT-

Sum of 5 and 3 is: 8

41. Function to check if a number is even and return a boolean:


def is_even(num):
return num % 2 == 0
# Test the function
number = 6
print(f"Is {number} even? {is_even(number)}")

OUTPUT-
Is 6 even? True

42. Function to calculate the area of a circle with a parameter:


def circle_area(radius):
pi = 3.14159
return pi * radius * radius
# Test the function
r=5
area = circle_area(r)
print(f"Area of circle with radius {r} is: {area}")

OUTPUT-

Area of circle with radius 5 is: 78.53975

43. Function to find the maximum of three numbers:


def find_max(a, b, c):
return max(a, b, c)
# Test the function
x, y, z = 10, 25, 15
maximum = find_max(x, y, z)
print(f"Maximum of {x}, {y}, and {z} is: {maximum}")

OUTPUT-

Maximum of 10, 25, and 15 is: 25

44. Function with default arguments to print a greeting:


def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
# Test the function
greet("Dhruv")
greet("Rahul", "Hi")

OUTPUT-

Hello, Dhruv! Hi, Rahul!

45. Function using positional arguments to multiply numbers:


def multiply(a, b, c):
return a * b * c
# Test the function
result = multiply(2, 3, 4)
print(f"Result of multiplication: {result}")

OUTPUT-

Result of multiplication: 24

46. Function with keyword arguments to format a name:


def format_name(first, last, middle=""):
if middle:
return f"{first} {middle} {last}"
return f"{first} {last}"
# Test the function
print(format_name(first="Raj", last="singh"))
print(format_name(first="Raj", middle="veer", last="singh"))

OUTPUT-

Raj singh
Raj veer singh
47. Function with arbitrary arguments to sum all inputs:
def sum_all(*args):
return sum(args)
# Test the function
print(sum_all(1, 2, 3, 4))
print(sum_all(5, 10, 15))

OUTPUT-

10 30

48. Function to demonstrate local and global scope of variables:


x = 10 # Global variable
def scope_demo():
x = 5 # Local variable
print(f"Inside function, x = {x}")
return x
# Test the function
print(f"Before function, x = {x}")
scope_demo()
print(f"After function, x = {x}")

OUTPUT-

Before function, x = 10
Inside function, x = 5
After function, x = 10

49. Function to calculate power using recursive calls:


def power(base, exp):
if exp == 0:
return 1
return base * power(base, exp - 1)
# Test the function
base = 2

exponent = 3
result = power(base, exponent)
print(f"{base} raised to {exponent} is: {result}")

OUTPUT-

2 raised to 3 is: 8

50. Capitalize the first letter of a string:


def capitalize_string(text):
return text.capitalize()
# Test the function
string = "hello world"
result = capitalize_string(string)
print(f"Original: {string}")
print(f"Capitalized: {result}")

OUTPUT-

Original: hello world


Capitalized: Hello world

51. Check if a string is alphanumeric:


def is_alphanumeric(text):
return text.isalnum()
# Test the function
string1 = "Hello123"
string2 = "Hello 123"
print(f"'{string1}' is alphanumeric: {is_alphanumeric(string1)}")
print(f"'{string2}' is alphanumeric: {is_alphanumeric(string2)}")

OUTPUT-

'Hello123' is alphanumeric: True 'Hello 123' is alphanumeric: False

52. Center a string with a specified width:


def center_string(text, width):
return text.center(width, '*')
# Test the function
string = "Python"
width = 10
result = center_string(string, width)
print(f"Centered string: '{result}'")

OUTPUT-

Centered string: '**Python***'

53. Count occurrences of a substring:


def count_substring(text, sub):
return text.count(sub)
# Test the function
string = "hello hello world hello"
substring = "hello"
count = count_substring(string, substring)
print(f"'{substring}' appears {count} times in '{string}'")

OUTPUT-

'hello' appears 3 times in 'hello hello world hello'


54. Encode a string to bytes:
def encode_string(text):
return text.encode('utf-8')
# Test the function
string = "Hello World"
encoded = encode_string(string)
print(f"Original: {string}")
print(f"Encoded: {encoded}")

Original: Hello World Encoded: b'Hello World'

55. Check if a string ends with a specific suffix:


def ends_with(text, suffix):
return text.endswith(suffix)
# Test the function
string = "filename.txt"
suffix = ".txt"
print(f"'{string}' ends with '{suffix}': {ends_with(string, suffix)}")

OUTPUT-

'filename.txt' ends with '.txt': True

56. Find the index of a substring:


def find_substring(text, sub):
return text.find(sub)
# Test the function
string = "Hello World"
substring = "World"
index = find_substring(string, substring)
print(f"Index of '{substring}' in '{string}': {index}")
OUTPUT-

Index of 'World' in 'Hello World': 6

57. Format a string using the format() method:


def format_string(name, age):
return "Name: {n}, Age: {a}".format(n=name, a=age)
# Test the function
name = "Alice"
age = 25

result = format_string(name, age)


print(result)

OUTPUT-

Name: Alice, Age: 25

58. Check if a string contains only digits:


def is_digits_only(text):
return text.isdigit()
# Test the function
string1 = "12345"
string2 = "123abc"
print(f"'{string1}' contains only digits: {is_digits_only(string1)}")
print(f"'{string2}' contains only digits: {is_digits_only(string2)}")

OUTPUT-

'12345' contains only digits: True '123abc' contains only digits: False

59. Join a list of strings with a delimiter:


def join_strings(string_list, delimiter):
return delimiter.join(string_list)
# Test the function
strings = ["apple", "banana", "orange"]
delimiter = ", "
result = join_strings(strings, delimiter)
print(f"Joined string: '{result}'")

OUTPUT-

Joined string: 'apple, banana, orange'

60. Match a pattern of digits using re.search():


import re
def match_digits(text):
pattern = r'\d+'
match = re.search(pattern, text)
return match.group() if match else "No digits found"
# Test the function
string = "Hello 123 World"
result = match_digits(string)
print(f"First digit sequence found: {result}")

OUTPUT-

First digit sequence found: 123

61. Replace all digits with 'X' using re.sub():


import re
def replace_digits(text):
pattern = r'\d'
return re.sub(pattern, 'X', text)
# Test the function
string = "Phone: 123-456-7890"
result = replace_digits(string)
print(f"Original: {string}")
print(f"After replacement: {result}")

OUTPUT-

Original: Phone: 123-456-7890 After replacement: Phone: XXX-XXX-XXXX

62. Find all email addresses in a string using regex:


import re
def find_emails(text):
pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
return re.findall(pattern, text)
# Test the function
string = "Contact: alice@example.com, bob123@domain.co.uk"
emails = find_emails(string)

print(f"Emails found: {emails}")

OUTPUT-

Emails found: ['alice@example.com', 'bob123@domain.co.uk']

63. Validate a phone number format with regex (e.g., XXX-XXX-


XXXX):
import re
def is_valid_phone(phone):
pattern = r'^\d{3}-\d{3}-\d{4}$'
return bool(re.match(pattern, phone))
# Test the function
phone1 = "123-456-7890"
phone2 = "123-456-789"
print(f"'{phone1}' is valid: {is_valid_phone(phone1)}")
print(f"'{phone2}' is valid: {is_valid_phone(phone2)}")

OUTPUT-

'123-456-7890' is valid: True


'123-456-789' is valid: False

64. Split a string by whitespace using re.split():


import re
def split_by_whitespace(text):
pattern = r'\s+'
return re.split(pattern, text)
# Test the function
string = "Hello World Python Programming"
result = split_by_whitespace(string)
print(f"Split result: {result}")

OUTPUT-

Split result: ['Hello', 'World', 'Python', 'Programming']

65. Remove special characters using regex:


import re
def remove_special_chars(text):
pattern = r'[^a-zA-Z0-9\s]'
return re.sub(pattern, '', text)
# Test the function
string = "Hello!@# World$%^"
result = remove_special_chars(string)
print(f"Original: {string}")
print(f"Cleaned: {result}")

OUTPUT-

Original: Hello!@# World$%^


Cleaned: Hello World

66. Find the first match of a word in a string:


import re
def find_first_word(text, word):
pattern = rf'\b{word}\b'
match = re.search(pattern, text)
return match.start() if match else -1
# Test the function
string = "The quick brown fox jumps"
word = "brown"
index = find_first_word(string, word)
print(f"First occurrence of '{word}' at index: {index}")

OUTPUT-

First occurrence of 'brown' at index: 10

67. Replace multiple spaces with a single space:


import re
def normalize_spaces(text):
pattern = r'\s+' return re.sub(pattern, ' ', text.strip())
# Test the function
string = "Hello World Python "
result = normalize_spaces(string)
print(f"Original: '{string}'")
print(f"Normalized: '{result}'")
OUTPUT-

Original: 'Hello World Python '


Normalized: 'Hello World Python'

68. Check if a string is a valid URL using regex:


import re
def is_valid_url(url):
pattern = r'^(https?://)?[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(/.*)?$'
return bool(re.match(pattern, url))
# Test the function
url1 = "https://www.example.com"
url2 = "invalid url"
print(f"'{url1}' is valid: {is_valid_url(url1)}")
print(f"'{url2}' is valid: {is_valid_url(url2)}")

OUTPUT-

'https://www.example.com' is valid: True


'invalid url' is valid: False

69. Extract all dates from a text using regex (format: DD/MM/YYYY):
import re
def extract_dates(text):

pattern = r'\b\d{2}/\d{2}/\d{4}\b'
return re.findall(pattern, text)
# Test the function
string = "Meetings on 12/05/2023 and 25/12/2024"
dates = extract_dates(string)
print(f"Dates found: {dates}")

OUTPUT-
Dates found: ['12/05/2023', '25/12/2024']

70. Create an empty list and append elements:


def append_to_list():
my_list = []
my_list.append(1)
my_list.append(2)
my_list.append(3)
return my_list
# Test the function
result = append_to_list() print(f"List after appending: {result}")

OUTPUT-

List after appending: [1, 2, 3]

71. Access the first element of a list:


def get_first_element():
my_list = [10, 20, 30, 40]
return my_list[0]
# Test the function
first = get_first_element()
print(f"First element: {first}")

OUTPUT-

First element: 10

72. Slice a list to get elements from index 1 to 3:


def slice_list():
my_list = [0, 1, 2, 3, 4, 5]
return my_list[1:4]
# Returns elements at index 1, 2, 3
# Test the function
sliced = slice_list()
print(f"Sliced list (index 1 to 3): {sliced}")

OUTPUT-

Sliced list (index 1 to 3): [1, 2, 3]

73. Use negative indices to access the last element:


def get_last_element():
my_list = [10, 20, 30, 40, 50]
return my_list[-1]
# Test the function
last = get_last_element()
print(f"Last element: {last}")

OUTPUT-

Last element: 50

74. Reverse a list using the reverse() method:


def reverse_list():
my_list = [1, 2, 3, 4, 5]
my_list.reverse()
return my_list
# Test the function
reversed_list = reverse_list()
print(f"Reversed list: {reversed_list}")

OUTPUT-

Reversed list: [5, 4, 3, 2, 1]


75. Sort a list using the sort() method:
def sort_list():
my_list = [5, 2, 8, 1, 9]
my_list.sort()
return my_list
# Test the function
sorted_list = sort_list()
print(f"Sorted list: {sorted_list}")

OUTPUT-

Sorted list: [1, 2, 5, 8, 9]

76. Remove an element from a list using remove():


def remove_element():
my_list = [10, 20, 30, 40, 20]
my_list.remove(20)
# Removes first occurrence of 20
return my_list
# Test the function
result = remove_element() print(f"List after removing 20: {result}")

OUTPUT-

List after removing 20: [10, 30, 40, 20]

77. Create a list comprehension for squares of numbers:


def square_list():
return [x**2 for x in range(1, 6)]
# Test the function
squares = square_list() print(f"List of squares: {squares}")
OUTPUT-

List of squares: [1, 4, 9, 16, 25]

78. Count occurrences of an element in a list:


def count_element(my_list, element):
return my_list.count(element)
# Test the function
my_list = [1, 2, 3, 2, 4, 2, 5]
element = 2
count = count_element(my_list, element)
print(f"Occurrences of {element} in {my_list}: {count}")

OUTPUT-

Occurrences of 2 in [1, 2, 3, 2, 4, 2, 5]: 3

79. Extend a list with another list:


def extend_list():
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
return list1
# Test the function
extended = extend_list()
print(f"Extended list: {extended}")

OUTPUT-

Extended list: [1, 2, 3, 4, 5, 6]

80. Create an empty tuple:


def create_empty_tuple():
my_tuple = ()
return my_tuple
# Test the function
empty_tuple = create_empty_tuple()
print(f"Empty tuple: {empty_tuple}")

OUTPUT-

Empty tuple: ()

81. Access the second element of a tuple:


def get_second_element():
my_tuple = (10, 20, 30, 40)
return my_tuple[1]
# Test the function
second = get_second_element()
print(f"Second element: {second}")

OUTPUT-

Second element: 20

82. Slice a tuple to get the first three elements:


def slice_tuple():
my_tuple = (0, 1, 2, 3, 4, 5)
return my_tuple[:3]
# Returns elements at index 0, 1, 2
# Test the function
sliced = slice_tuple()
print(f"First three elements: {sliced}")

OUTPUT-
First three elements: (0, 1, 2)

83. Use negative indices to access the last element of a tuple:


def get_last_element():
my_tuple = (10, 20, 30, 40, 50)
return my_tuple[-1]
# Test the function
last = get_last_element()
print(f"Last element: {last}")

OUTPUT-

Last element: 50

84. Concatenate two tuples:


def concatenate_tuples():
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
return tuple1 + tuple2
# Test the function
concatenated = concatenate_tuples()
print(f"Concatenated tuple: {concatenated}")

OUTPUT-

Concatenated tuple: (1, 2, 3, 4, 5, 6)

85. Repeat a tuple three times:


def repeat_tuple():
my_tuple = (1, 2, 3)
return my_tuple * 3
# Test the function
repeated = repeat_tuple()
print(f"Tuple repeated 3 times: {repeated}")

OUTPUT-

Tuple repeated 3 times: (1, 2, 3, 1, 2, 3, 1, 2, 3)

86. Find the length of a tuple:


def tuple_length():
my_tuple = (10, 20, 30, 40, 50)
return len(my_tuple)
#Test the function
length = tuple_length()
print(f"Length of tuple: {length}")

OUTPUT-

Length of tuple: 5

87. Check if an element exists in a tuple:


def check_element(my_tuple, element):
return element in my_tuple
# Test the function
my_tuple = (1, 2, 3, 4, 5)
element = 3
result = check_element(my_tuple, element)
print(f"Is {element} in {my_tuple}? {result}")

OUTPUT-

Is 3 in (1, 2, 3, 4, 5)? True


88. Count occurrences of an item in a tuple:
def count_item(my_tuple, item):
return my_tuple.count(item)
# Test the function
my_tuple = (1, 2, 3, 2, 4, 2, 5)
item = 2
count = count_item(my_tuple, item)
print(f"Occurrences of {item} in {my_tuple}: {count}")

OUTPUT-

Occurrences of 2 in (1, 2, 3, 2, 4, 2, 5): 3

89. Find the index of an element in a tuple:


def find_index(my_tuple, element):
return my_tuple.index(element)
# Test the function
my_tuple = (10, 20, 30, 40, 50)
element = 30
index = find_index(my_tuple, element)
print(f"Index of {element} in {my_tuple}: {index}")

OUTPUT-

Index of 30 in (10, 20, 30, 40, 50): 2

90.Create an empty dictionary and add a key-value pair:

def add_to_dict():
my_dict = {}
my_dict["name"] = "Alice"
return my_dict
# Test the function
result = add_to_dict()
print(f"Dictionary after adding pair: {result}")

Output-
Dictionary after adding pair: {'name': 'Alice'}

91. Access a value by key in a dictionary:


def get_value():
my_dict = {"name": "Bob", "age": 25}
return my_dict["name"]
# Test the function
value = get_value()
print(f"Value for key 'name': {value}")

Output-
Value for key 'name': Bob

92. Replace a value for an existing key in a dictionary


def replace_value():
my_dict = {"name": "Charlie", "age": 30}
my_dict["age"] = 35 return my_dict
# Test the function
result = replace_value()
print(f"Dictionary after replacing value: {result}")

Output-:
Dictionary after replacing value: {'name': 'Charlie', 'age': 35}

93. Add a new key-value pair to a dictionary:


def add_new_pair():

my_dict = {"name": "David"}


my_dict["city"] = "New York"
return my_dict
# Test the function
result = add_new_pair()
print(f"Dictionary after adding new pair: {result}")

Output-
Dictionary after adding new pair: {'name': 'David', 'city': 'New York'}

94. Remove a key-value pair using pop():


def remove_pair():
my_dict = {"name": "Eve", "age": 28}
removed_value = my_dict.pop("age")
return my_dict, removed_value
# Test the function
dict_result, value = remove_pair()
print(f"Dictionary after removal: {dict_result}")
print(f"Removed value: {value}")

Output-
Dictionary after removal: {'name': 'Eve'} # Removed value: 28

95. Get all keys from a dictionary:


def get_keys():
my_dict = {"name": "Frank", "age": 40, "city": "London"}
return my_dict.keys()
# Test the function
keys = get_keys()
print(f"All keys: {list(keys)}")

Output-
: All keys: ['name', 'age', 'city']

96. Get all values from a dictionary:


def get_values():
my_dict = {"name": "Grace", "age": 22, "city": "Paris"}
return my_dict.values()
# Test the function
values = get_values()
print(f"All values: {list(values)}")

Output-
All values: ['Grace', 22, 'Paris']

97. Check if a key exists in a dictionary:


def check_key(my_dict, key):
return key in my_dict
# Test the function
my_dict = {"name": "Hank", "age": 33}
key = "age"
result = check_key(my_dict, key)
print(f"Is '{key}' in dictionary? {result}")

Output-
Is 'age' in dictionary? True

98. Merge two dictionaries:


def merge_dicts():
dict1 = {"name": "Ivy"}
dict2 = {"age": 27, "city": "Tokyo"}
dict1.update(dict2)
return dict1
# Test the function
merged = merge_dicts()
print(f"Merged dictionary: {merged}")

Output-
Merged dictionary: {'name': 'Ivy', 'age': 27, 'city': 'Tokyo'}’’

99. Clear all items from a dictionary


def clear_dict():
my_dict = {"name": "Jack", "age": 45, "city": "Berlin"}
my_dict.clear()
return my_dict
# Test the function
result = clear_dict()
print(f"Dictionary after clearing: {result}")

Output-
Dictionary after clearing: {}

100.Create an empty set and add an element:


def add_to_set():
my_set = set()
my_set.add(5)
return my_set
# Test the function
result = add_to_set()
print(f"Set after adding element: {result}")
Output-
Set after adding element: {5}

You might also like