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

Python Excercises for Interview

The document contains a series of Python exercises designed to practice basic programming concepts, including arithmetic operations, string manipulation, list handling, and file operations. Each exercise includes a brief description, example code, and expected output. The exercises range from simple calculations to more complex tasks like checking for palindromes and formatting strings.

Uploaded by

tanuteju79
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)
6 views

Python Excercises for Interview

The document contains a series of Python exercises designed to practice basic programming concepts, including arithmetic operations, string manipulation, list handling, and file operations. Each exercise includes a brief description, example code, and expected output. The exercises range from simple calculations to more complex tasks like checking for palindromes and formatting strings.

Uploaded by

tanuteju79
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/ 46

2/18/25, 2:27 AM pythonexcercise.

ipynb - Colab

keyboard_arrow_down PYTHON BASIC EXCERCISE


Exercise 1: Calculate the multiplication and sum of two numbers?

def sum(a,b):
print("sum of two numbers is",a+b)
def product(a,b):
print("product is",a*b)

a = int(input("Enter your first number"))


b= int(input("Enter your second number"))
sum(a,b)
product(a,b)

Enter your first number10


Enter your second number20
sum of two numbers is 30
product is 200

Exercise 2: Print the Sum of a Current Number and a Previous number?

Write a Python code to iterate the first 10 numbers, and in each iteration, print the sum of the current and previous number.

for i in range(1,11):
print("current number is ",i, "sum is",i+(i-1))

current number is 1 sum is 1


current number is 2 sum is 3
current number is 3 sum is 5
current number is 4 sum is 7
current number is 5 sum is 9
current number is 6 sum is 11
current number is 7 sum is 13
current number is 8 sum is 15
current number is 9 sum is 17
current number is 10 sum is 19

Exercise 3: Print characters present at an even index number?

Write a Python code to accept a string from the user and display characters present at an even index number.

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 1/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
str = input("Enter your string")
for i in str:
if str.index(i) %2 == 0:
print(str[str.index(i)] )

Enter your stringTapan


T
p
n

Exercise 4: Remove first n characters from a string?

Write a Python code to remove characters from a string from 0 to n and return a new string.

def remove_char(word,n):
print("original word is ",word)
return(word[n:])

word = input("enter your word")


n= int(input("Enter the first number you want to remove"))
remove_char(word,n)

enter your wordtapan


Enter the first number you want to remove1
original word is tapan
' '

Exercise 5: Check if the first and last numbers of a list are the same?

Write a code to return True if the list’s first and last numbers are the same. If the numbers are different, return False.

ls = [10,20,30,40,50]
print(ls[0])
print(ls[-1])
print(ls[:3])
print(ls[2:])
print(ls[:-1])

def check_list(ls):
if ls[0] == ls[-1]:
return True
else:
return False
check_list(ls)

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 2/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

10
50
[10, 20, 30]
[30, 40, 50]
[10, 20, 30, 40]
False

Exercise 6: Display numbers divisible by 5?

Write a Python code to display numbers from a list divisible by 5

list = [10,12,15,20]
list1=[]
for i in list:
if i %5 ==0:
list1.append(i)
print(list1)

[10, 15, 20]

Exercise 7: Find the number of occurrences of a substring in a string?

Write a Python code to find how often the substring “Emma” appears in the given string.

str_x = "Emma is good developer. Emma is a writer"


cnt = str_x.count('Emma')
print(cnt)

Exercise 8: Print the following pattern?

22

333

4444

55555

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 3/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
for num in range(6):

for i in range(num):

print (num, end=" ") #print number


# # new line after each row to display pattern correctly
print("\n")

2 2

3 3 3

4 4 4 4

5 5 5 5 5

Exercise 9: Check Palindrome Number?

Write a Python code to check if the given number is palindrome. A palindrome number is a number that is the same after reverse. For
example, 545 is the palindrome number.

number = input("Enter your number to check")


print(type(number))
if number == number[::-1]:
print("number is palindrome")
else:
print("number is not a palindrome")

Enter your number to check545


<class 'str'>
number is palindrome

n = int(input("Enter your number"))

def palindrome(n):
original_num = n
reverse_num = 0
while n >0:
rem = n%10
reverse_num = (reverse_num *10) + rem
n = n//10
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 4/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
if original_num == reverse_num:
print("number is palindrome")
else:
print("number is not a palindrome")

palindrome(n)

Enter your number121


number is palindrome

Exercise 10: Merge two lists using the following condition?

Given two lists of numbers, write a Python code to create a new list such that the latest list should contain odd numbers from the first list and
even numbers from the second list.

lst1 = [12,13,14,15,16]
lst2 = [21,22,17,18,20,25]
lst3 = []
for i in lst1:
if i % 2 == 0 :
lst3.append(i)
for i in lst2:
if i %2 !=0:
lst3.append(i)
print(lst3)

[12, 14, 16, 21, 17, 25]

Exercise 11: Get each digit from a number in the reverse order.?

For example, If the given integer number is 7536, the output shall be “6 3 5 7“, with a space separating the digits.

given_number = 7536
while given_number>0 :
digit = given_number % 10
given_number = given_number //10
print(digit,end = " ")

6 3 5 7

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 5/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

Exercise 12: Calculate income tax

Calculate income tax for the given income by adhering to the rules below

Taxable Income Rate (in %)

First $10,000 = 0

Next $10,000 = 10

The remaining= 20

Expected Output:

For example, suppose the income is 45000, and the income tax payable is

100000% + 1000010% + 25000*20% = $6000.

income = 45000
tax_payble = 0
print("original income is ",income)
if income <= 10000:
tax_payble = 0
elif income <= 20000:
x = (income-10000)
tax_payble = x * 10/100
else:
tax_payble = 0
tax_payble = 10000 * 10/100
tax_payble = tax_payble + (income-20000) * 20/100
print("tax to be paid is",tax_payble)

original income is 45000


tax to be paid is 6000.0

Exercise 13: Print multiplication table from 1 to 10?

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 6/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
for i in range(1,11):

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

print('\t\t')

1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

Exercise 14: Print a downward half-pyramid pattern of stars

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

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

print('*',end =' ')


print(' ')

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

Exercise 15: Get an int value of base raises to the power of exponent

Write a function called exponent(base, exp) that returns an int value of base raises to the power of exp.

def exp(base,expo):
num = expo
result =1
while num>0:
result = result * base
num = num-1
print(base,"raises to the power of",expo,"is",result)

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 7/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

base = int(input("Enter your base number"))


expo = int(input("Enter your exponent number"))
exp(base,expo)

Enter your base number5


Enter your exponent number4
5 raises to the power of 4 is 625

Python Input and Output Exercise

Exercise 1: Accept numbers from a user

Write a program to accept two numbers from the user and calculate multiplication

def mul(input1,input2):
return input1*input2
input1 = int(input("Enter your first number"))
input2 = int(input("Enter your second number"))
mul(input1,input2)

Enter your first number10


Enter your second number9
90

Exercise 2: Display three string “Name”, “Is”, “James” as “NameIsJames"

#For example: print('Name', 'Is', 'James') will display Name**Is**James


print('My', 'Name', 'Is', 'James', sep='**')

My**Name**Is**James

Exercise 3: Convert Decimal number to octal using print() output formatting

num = 8
octal_num = ('%o'%num)
print(octal_num)

10

Exercise 4: Display float number with 2 decimal places using print()

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 8/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

n = 1537.9892
print('%.2f'%n)

1537.99

Exercise 5: Accept a list of 5 float numbers as an input from the user

numbers = []
for i in (0,5):
print("Enter your number at location",i,":")
num = float(input())
numbers.append(num)
print(numbers)
#

Enter your number at location 0 :


1
Enter your number at location 5 :
3
[1.0, 3.0]

Exercise 6: Write all content of a given file into a new file by skipping line number 5

with open(text1.txt,'r') as fp:


lines = fp.readlines()
with open(text_new.txt,'w') as fp:
count = 0
for line in lines:
if count == 4:
count= count+1
continue
fp.write(line)
count = count+1

Exercise 7: Accept any three string from one input() call

Write a program to take three names as input from a user in the single input() function call.

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 9/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
str1,str2,str3 = input("Enter three strings").split()
print("Name1:",str1)
print("Name2:",str2)
print("Name3:",str3)

Enter three stringsTapan Kumar Pati


Name1: Tapan
Name2: Kumar
Name3: Pati

Exercise 8: Format variables using a string.format() method.

Write a program to use string.format() method to format the following three variables as per the expected output

Given:

totalMoney = 1000

quantity = 3

price = 450

Expected Output:

I have 1000 dollars so I can buy 3 football for 450.00 dollars.

totalMoney = 1000
quantity = 3
price = 450
statement = "I have {1} dollars so i can buy {0} football for {2:.2f} dollars."
print(statement.format(totalMoney,quantity,price))

I have 3 dollars so i can buy 1000 football for 450.00 dollars.

Exercise 9: Check file is empty or not?

Write a program to check if the given file is empty or not

import os
size = os.path.getsize("text1.txt")
if size == 0:
print("file is empty")

Exercise 10: Read line number 4 from the following file

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 10/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

with open("text.txt",'r') as fp:

lines = fp.readlines()
print(lines[3])

keyboard_arrow_down Python if else, for loop, and range() Exercises


Branching and looping techniques are used in Python to decide and control the flow of a program. A good understanding of loops and if-else
statements is necessary to write efficient code in Python.

Exercise 1: Print first 10 natural numbers using while loop?

i = 1
while i <=10:
print(i)
i += 1

1
2
3
4
5
6
7
8
9
10

Exercise 2: Print the following pattern

Write a Python code to print the following number pattern using a loop.

12

123

1234

12345

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 11/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
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

Exercise 3: Calculate sum of all numbers from 1 to a given number?

Write a Python program to accept a number from a user and calculate the sum of all numbers from 1 to a given number.

For example, if the user entered 10, the output should be 55 (1+2+3+4+5+6+7+8+9+10).

n= 0
m = int(input("Enter your number"))
for i in range(m+1):
n = n+i
i+=1
print(n)

Enter your number10


55

Exercise 4: Print multiplication table of a given number?

n = int(input("Enter your number for multiplicaton table"))


for i in range(1,11):
print(n*i)

Enter your number for multiplicaton table2


2
4
6
8
10
12
14
16
18
20

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 12/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

Exercise 5: Display numbers from a list using a loop?

Write a Python program to display only those numbers from a list that satisfy the following conditions.

The number must be divisible by five.

If the number is greater than 150, then skip it and move to the following number.

If the number is greater than 500, then stop the loop.

numbers = [12, 75, 150, 180, 145, 525, 50]


for i in numbers:
if i > 500:
break
elif i > 150:
continue
elif i % 5 == 0:
print(i)

75
150
145

Exercise 6: Count the total number of digits in a number?

count = 0
n = int(input("enter your number"))
while n > 0:
n = n//10
count += 1
print(count)

enter your number120


3

Exercise 7: Print the following pattern?

Write a Python program to print the reverse number pattern using a for loop.

54321

4321

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 13/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

321

21

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

for j in range(i-1,0,-1):
print(j,end = ' ')
print(' ')

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

Exercise 8: Print list in reverse order using a loop?

list1 = [10, 20, 30, 40, 50]


size = len(list1)-1

for i in range(size,-1,-1):
print(list1[i])

50
40
30
20
10

Exercise 9: Display numbers from -10 to -1 using for loop?

for i in range(-10,0,1):
print(i)

-10
-9
-8
-7
-6
-5

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 14/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
-4
-3
-2
-1

Exercise 10: Display a message “Done” after the successful execution of the for loop?

for i in range(10):
print(i)
print('Done!')

0
1
2
3
4
5
6
7
8
9
Done!

Exercise 11: Print all prime numbers within a range?

start = int(input("Enter your start number"))


end = int(input("Enter your end number"))
for i in range(start,end+1):
if i> 1:
for j in range(2,i):
if i % j == 0 :
break
else:
print(i,'is the prime number')

Enter your start number25


Enter your end number50
29 is the prime number
31 is the prime number
37 is the prime number
41 is the prime number
43 is the prime number
47 is the prime number

Exercise 12: Display Fibonacci series up to 10 terms?


https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 15/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

num1 = 0
num2 = 1
for i in range(10):
print(num1,end = ' ')
result = num1 +num2
num1 = num2
num2 = result

0 1 1 2 3 5 8 13 21 34

Find the factorial of a given number?

n= int(input("Enter your number"))


factorial = 1
if n <0 :
print("Factorial is negative")
elif n == 0:
print("factorial is ",1)
else:
for i in range(1,n+1):
factorial = factorial * i
print(factorial)

Enter your number5


120

Exercise 14: Reverse a integer number?

n= int(input("Enter the number"))


rev= 0
while n >0:
reminder = n % 10
rev = (rev *10)+reminder
n = n//10
print(rev)

Enter the number123


321

Exercise 15: Print elements from a given list present at odd index positions

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 16/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
for i in my_list[1::2]:
print(i,end = ' ')

20 40 60 80 100

Exercise 16: Calculate the cube of all numbers from 1 to a given number?

Write a Python program to print the cube of all numbers from 1 to a given number

n = int(input("Enter your number"))


for i in range(1,n+1):
print(i**3,end =' ')

Enter your number10


1 8 27 64 125 216 343 512 729 1000

Exercise 17: Find the sum of the series up to n terms?

Write a program to calculate the sum of series up to n terms. For example, if n

= 5 the series will become 2 + 22 + 222 + 2222 + 22222 = 24690

n = int(input("Enter your numer"))


start = 2
sum = 0
for i in range(0,n):
start = start *10 + 2
sum = sum +start
print(sum)

Enter your numer5


246910

Exercise 18: Print the following pattern?

Write a program to print the following start pattern using the for loop

*
* *
* * *
* * * *

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 17/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
* * * * *
* * * *
* * *
* *
*

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

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

keyboard_arrow_down Python Functions Exercise


Exercise 1: Create a function in Python?

Write a program to create a function that takes two arguments, name and age,

and print their value.

def f1(name,age):
print(name)
print(age)
f1("Tapan",23)

Tapan
23

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 18/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

Exercise 2: Create a function with variable length of arguments?

Write a program to create function func1() to accept a variable length of

arguments and print their value.

def fun1(*args):
for i in args:
print(i,end=' ')
print(' ')

fun1(20,40)
fun1(20,40,60)

20 40
20 40 60

Exercise 3: Return multiple values from a function?

Write a program to create function calculation() such that it can accept two

variables and calculate addition and subtraction. Also, it must return both

addition and subtraction in a single return call.

def sub_add(a,b):
return a+b,a-b

sub_add(20,10)

(30, 10)

Exercise 4: Create a function with a default argument?

Write a program to create a function show_employee() using the following conditions.

It should accept the employee’s name and salary and display both.

If the salary is missing in the function call then assign default value 9000 to salary

def show_employee(name,salary=9000):
print(f"your name is {name}")

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 19/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
print(f"your salary is {salary}")
show_employee("Tapan",40000)
show_employee("Pati")

your name is Tapan


your salary is 40000
your name is Pati
your salary is 9000

Exercise 5: Create an inner function to calculate the addition in the following way

Create an outer function that will accept two parameters, a and b.

Create an inner function inside an outer function that will calculate the addition of a and b.

At last, an outer function will add 5 into addition and return it.

def outer(a,b):
square = a**2
def inner(a,b):
return a+b
add = inner(3,2)
return add+5
result = outer(5,10)
print(result)

10

Exercise 6: Create a recursive function

Write a program to create a recursive function to calculate the sum of numbers from 0 to 10.

*A recursive function is a function that calls itself again and again.

def addition(num):
if num:
return num+addition(num-1)
else:
return 0
addition(55)

1540

Exercise 7: Assign a different name to function and call it through the new name

Below is the function display_student(name, age). Assign a new name


https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 20/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

show_student(name, age) to it and call it using the new name.

def display_student(name,age):
print(name)
print(age)
show_student = display_student
show_student("Tapan",23)

Tapan
23

Exercise 8: Generate a Python list of all the even numbers between 4 to 30?

lst = []
def gen():
for i in range(4,30,2):
lst.append(i)
return lst

l = gen()
print(l)

[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]

Exercise 9: Find the largest item from a given list?

x = [4, 6, 8, 24, 12, 2]


# print(max(x))
largest = x[0]
for num in x:
if num > largest:
largest = num
print("greater is",largest)

greater is 24

keyboard_arrow_down Python String Exercise with Solutions


https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 21/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

Exercise 1A: Create a string made of the first, middle and last character?

Write a program to create a new string made of an input string’s first, middle, and last character.

str = 'james'
result = str[0]
mi = int(len(str)/2)
result = result + str[mi]
result = result + str[-1]
print(result)

jms

Exercise 1B: Create a string made of the middle three characters?

Write a program to create a new string made of the middle three characters of an input string.

str = 'Tapankumar'
mi = int(len(str)/2)
result = str[mi-1] + str[mi] + str[mi+1]
print(result)

nku

Exercise 2: Append new string in the middle of a given string?

Given two strings, s1 and s2. Write a program to create a new string s3 by

appending s2 in the middle of s1.

def fun(str1,str2):
print("original strings are",str1,str2)
mi = int(len(str1)/2)
x = str1[:mi:]
print(x)
x = x+ str2
x= x+ str1[mi:]
print("after appending the string",x)

fun('Tapan','pati')

original strings are Tapan pati


Ta
after appending the string Tapatipan
https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 22/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

Exercise 3: Create a new string made of the first, middle, and last characters of each input string?

Given two strings, s1 and s2, write a program to return a new string made of s1 and s2’s first, middle, and last characters.

s1 = 'Tapan'
s2 = 'pati'
mi_s1= int(len(s1)/2)
mi_s2 = int(len(s2)/2)
new_s = s1[0]+s2[0]+s1[mi_s1]+s2[mi_s2]+s1[-1]+s2[-1]
print(new_s)

Tpptni

Exercise 4: Arrange string characters such that lowercase letters should come first?

Given string contains a combination of the lower and upper case letters. Write

a program to arrange the characters of a string so that all lowercase letters

should come first.

str1 = "TapanKumarPati"
lower =[]
upper =[]
for char in str1:
if char.islower():
lower.append(char)
else:
upper.append(char)

sorted_str = ''.join(lower+upper)
print("Result",sorted_str)

Result apanumaratiTKP

Exercise 5: Count all letters, digits, and special symbols from a given string

def count(str):
char_count = 0
digit_count = 0
symbol_count = 0
for char in str:
if char.isalpha():

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 23/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
char_count += 1
elif char.isdigit():
digit_count += 1
else:
symbol_count+=1
print(f"The number of characaters {char_count},The number of digits{digit_count},The number of symbol{symbol_count}")
count("Tapan@123")

The number of characaters 5,The number of digits3,The number of symbol1

Exercise 6: Create a mixed String using the following rules

Given two strings, s1 and s2. Write a program to create a new string s3 made of

the first char of s1, then the last char of s2, Next, the second char of s1 and

second last char of s2, and so on. Any leftover chars go at the end of the

result.

s1 = "Tapan"
s2 = "Pati"
len1 = len(s1)
len2 = len(s2)

length = len2 if len1 < len2 else len1


result = ""
s2 = s2[::-1]

for i in range(length):
if i < len1 :
result = result + s1[i]
if i < len2:
result = result + s2[i]
print(result)

TiatpaaPn

Exercise 7: String characters balance Test

Write a program to check if two strings are balanced. For example, strings s1

and s2 are balanced if all the characters in the s1 are present in s2. The

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 24/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

character’s position doesn’t matter.

str1 ="Tapan"
str2 = "napTap"
for i in str1:
for j in str2:
if i == j:
pass
print("Two strings are balanced")

Two strings are balanced

Exercise 8: Find all occurrences of a substring in a given string by ignoring the case

Write a program to find all occurrences of “USA” in a given string ignoring the case.

str1 = "Welcome to USA. usa awesome, isn't it?"


sub_string = 'usa'
temp_str = str1.lower()
print(temp_str)
count = temp_str.count(sub_string.lower())
print(f"{sub_string} count is {count}")

welcome to usa. usa awesome, isn't it?


usa count is 2

Exercise 9: Calculate the sum and average of the digits present in a string

Given a string s1, write a program to return the sum and average of the digits that appear in the string, ignoring all other characters.

str1 = "PYnative29@#8496"
sum = 0
count = 0
for i in str1:
if i.isdigit():
sum += int(i)
count += 1
avg = sum/count

print("sum is ",sum)
print("average is",avg)

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 25/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

sum is 38
average is 6.333333333333333

Exercise 10: Write a program to count occurrences of all characters within a string

str1 = "Apple"

char_dict = {}

for char in str1:


count = str1.count(char)

char_dict[char] = count
print('Result:', char_dict)

Result: {'A': 1, 'p': 2, 'l': 1, 'e': 1}

Exercise 11: Reverse a given string

str1 ="Tapan"
rev_str1 = str1[::-1]
print(rev_str1)

napaT

Exercise 12: Find the last position of a given substring

Write a program to find the last position of a substring “Emma” in a given string.

str1 = "Emma is a data scientist who knows Python. Emma works at google."
print("original string",str1)
index = str1.rfind('Emma')
print("Emaa index is",index)

original string Emma is a data scientist who knows Python. Emma works at google.
Emaa index is 43

Exercise 13: Split a string on hyphens

Write a program to split a given string on hyphens and display each substring.

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 26/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
str1 = "Emma-is-a-data-scientist"
str2 = str1.split('-')
print(str2)

['Emma', 'is', 'a', 'data', 'scientist']

Exercise 14: Remove empty strings from a list of strings

str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]


result = []
for i in str_list:
if i:
result.append(i)
print(result)

['Emma', 'Jon', 'Kelly', 'Eric']

str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]


str_new = list(filter(None,str_list))
print(str_new)

['Emma', 'Jon', 'Kelly', 'Eric']

Exercise 15: Remove special symbols / punctuation from a string

import re
str1 = "/*Jon is @developer & musician"
result = re.sub(r'[^\w\s]','',str1)
print(result)

Jon is developer musician

Exercise 16: Removal all characters from a string except integers

import re
str1 = 'I am 25 years and 10 months old'
result = "".join([i for i in str1 if i.isdigit()])
print(result)

2510

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 27/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

Exercise 17: Find words with both alphabets and numbers

Write a program to find words with both alphabets and numbers from an input string.

str1 = "Emma25 is Data scientist50 and AI Expert"


print("The original string is : " + str1)

res = []
# split string on whitespace
temp = str1.split()

# Words with both alphabets and numbers


# isdigit() for numbers + isalpha() for alphabets
# use any() to check each character

for item in temp:


if any(char.isalpha() for char in item) and any(char.isdigit() for char in item):
res.append(item)

print("Displaying words with alphabets and numbers")


for i in res:
print(i)

The original string is : Emma25 is Data scientist50 and AI Expert


Displaying words with alphabets and numbers
Emma25
scientist50

Exercise 18: Replace each special symbol with # in the following string

string = '/*Jon is @developer & musician!!'


print("The original string is : ", str1)

# Replace punctuations with #


replace_char = '#'

for char in string.punctuation:


str1 = str1.replace(char, replace_char)

print("The strings after replacement : ", str1)

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 28/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-cd9e3422ffd1> in <cell line: 2>()
1 string = '/*Jon is @developer & musician!!'
----> 2 print("The original string is : ", str1)
3
4 # Replace punctuations with #
5 replace_char = '#'

NameError: name 'str1' is not defined

keyboard_arrow_down Python Data Structure Exercise for Beginners


Exercise 1: Create a list by picking an odd-index items from the first list and even index items from the second?

l1 = [3, 6, 9, 12, 15, 18, 21]


l2 = [4, 8, 12, 16, 20, 24, 28]
l3 = l1[1:len(l1):2]
print("List picking from odd index",l3)
l4 = l2[0:len(l2):2]
print("list picks for even index",l4)
l5 = l3+l4
print(l5)

List picking from odd index [6, 12, 18]


list picks for even index [4, 12, 20, 28]
[6, 12, 18, 4, 12, 20, 28]

Exercise 2: Remove and add item in a list?

Write a program to remove the item present at index 4 and add it to the 2nd position and at the end of the list.

list1 = [54, 44, 27, 79, 91, 41]


e = list1.pop(4)
print(e)
list1.insert(2,e)
print(list1)
list1.append(e)
print(list1)

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 29/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

91
[54, 44, 91, 27, 79, 41]
[54, 44, 91, 27, 79, 41, 91]

Exercise 3: Slice list into 3 equal chunks and reverse each chunk?

def slice_reverse(sample_list):
try:
if len(sample_list) % 3 != 0:
print("Must be divisible by zero")
length = len(sample_list)
chunk_size = length//3
chunks = [sample_list[i:i+chunk_size] for i in range(0,length,chunk_size)]
reversed_chunks = [chunk[::-1] for chunk in chunks]

return reversed_chunks
except Exception as e:
print(f"error {e}")

sample_list = [11, 45, 8, 23, 14, 12, 78, 45, 89]


result = slice_reverse(sample_list)

print(result)

[[8, 45, 11], [12, 14, 23], [89, 45, 78]]

Exercise 4: Count the occurrence of each element from a list

Write a program to iterate a given list and count the occurrence of each element and create a dictionary to show the count of each element.

sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]

count_dict = {}

for item in sample_list:


if item in count_dict:
count_dict[item] += 1
else:
count_dict[item] = 1
print("Printing count of each item ", count_dict)

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 30/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

Printing count of each item {11: 2, 45: 3, 8: 1, 23: 2, 89: 1}

Exercise 5: Create a Python set such that it shows the element from both lists in a pair?

first_list = [2, 3, 4, 5, 6, 7, 8]
second_list = [4, 9, 16, 25, 36, 49, 64]
result = zip(first_list,second_list)
set_result = set(result)
print(set_result)

{(7, 49), (2, 4), (4, 16), (8, 64), (6, 36), (3, 9), (5, 25)}

Exercise 6: Find the intersection (common) of two sets and remove those elements from the first set?

first_set = {23, 42, 65, 57, 78, 83, 29}


second_set = {57, 83, 29, 67, 73, 43, 48}
intersection_element = first_set.intersection(second_set)
for i in intersection_element:
first_set.remove(i)
print(intersection_element)
print(first_set)

{57, 83, 29}


{65, 23, 42, 78}

Exercise 7: Checks if one set is a subset or superset of another set. If found, delete all elements from that set?

first_set = {27, 43, 34}


second_set = {34, 93, 22, 27, 43, 53, 48}

print("The original first set",first_set)


print("The original second set",second_set)

print("The First set is a subset of second set",first_set.issubset(second_set))


print("The second set is a subset of first set",second_set.issubset(first_set))

print("The First set is a superset of second set",first_set.issuperset(second_set))


print("The second set is a superset of first set",second_set.issuperset(first_set))

if first_set.issubset(second_set):
first_set.clear()
elif second_set.issubset(first_set):

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 31/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
second_set.clear()

print(first_set)
print(second_set)

The original first set {27, 34, 43}


The original second set {48, 34, 53, 22, 27, 43, 93}
The First set is a subset of second set True
The second set is a subset of first set False
The First set is a superset of second set False
The second set is a superset of first set True
set()
{48, 34, 53, 22, 27, 43, 93}

Exercise 8: Iterate a given list and check if a given element exists as a key’s value in a dictionary. If not, delete it from the list?

roll_number = [47, 64, 69, 37, 76, 83, 95, 97]


sample_dict = {'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
for i in roll_number:
if i in sample_dict.values():
pass
else:
roll_number.remove(i)
print(roll_number)

[47, 69, 76, 95, 97]

Exercise 9: Get all values from the dictionary and add them to a list but don’t add duplicates?

speed = {'jan': 47, 'feb': 52, 'march': 47, 'April': 44, 'May': 52, 'June': 53, 'july': 54, 'Aug': 44, 'Sept': 54}
l1 =[]
for value in speed.values():
if value not in l1:
l1.append(value)
print(l1)

[47, 52, 44, 53, 54]

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 32/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

Exercise 10: Remove duplicates from a list and create a tuple and find the minimum and maximum number?

sample_list = [87, 45, 41, 65, 94, 41, 99, 94]


result1 = []
for i in sample_list:
if i not in result1:
result1.append(i)
print("uniqe elements are",result1)
result2 = tuple(result1)
print("Tuple is",result2)
min_element = min(result2)
print("min element",min_element)
max_element = max(result2)
print("max element",max_element)

uniqe elements are [87, 45, 41, 65, 94, 99]


Tuple is (87, 45, 41, 65, 94, 99)
min element 41
max element 99

keyboard_arrow_down Python List Exercise with Solutions


Exercise 1: Reverse a list in Python?

list1 = [100, 200, 300, 400, 500]


reverse = list1[::-1]
print(reverse)

[500, 400, 300, 200, 100]

Exercise 2: Concatenate two lists index-wise

Write a program to add two lists index-wise. Create a new list that contains the 0th index item from both the list, then the 1st index item, and
so on till the last element. any leftover items will get added at the end of the new list.

list1 = ["M", "na", "i", "Ta"]


list2 = ["y", "me", "s", "pan"]
list3 = [i+j for i,j in zip(list1,list2)]
print(list3)

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 33/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

['My', 'name', 'is', 'Tapan']

Exercise 3: Turn every item of a list into its square

Given a list of numbers. write a program to turn every item of a list into its square.?

l1 =[1,2,3,4]
print(list(map(lambda x: x**2,l1)))

[1, 4, 9, 16]

Exercise 4: Concatenate two lists in the following order?

list1 = ["Hello ", "take "]


list2 = ["Dear", "Sir"]

result = [x+y for x in list1 for y in list2]


print(result)

['Hello Dear', 'Hello Sir', 'take Dear', 'take Sir']

Exercise 5: Iterate both lists simultaneously?

Given a two Python list. Write a program to iterate both lists simultaneously and display items from list1 in original order and items from list2
in reverse order

list1 = [10, 20, 30, 40]


list2 = [100, 200, 300, 400]
# list3 = list2[::-1]
# for i in list1:
# print(i)
# for j in list3:
# print(j)

for x,y in zip(list1,list2[::-1]):


print(x, y)

10 400
20 300
30 200
40 100

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 34/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

Exercise 6: Remove empty strings from the list of strings.

list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]


for i in list1:
if i == "":
list1.remove(i)
print(list1)

['Mike', 'Emma', 'Kelly', 'Brad']

Exercise 7: Add new item to list after a specified item.

Write a program to add item 7000 after 6000 in the following Python List?

list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
list1[2][2].append(7000)
print(list1)

[10, 20, [300, 400, [5000, 6000, 7000], 500], 30, 40]

Exercise 8: Extend nested list by adding the sublist.

You have given a nested list. Write a program to extend it by adding the sublist ["h", "i", "j"] in such a way that it will look like the following list.

list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]

# sub list to add


sub_list = ["h", "i", "j"]
list1.extend(sub_list)
print(list1)

['a', 'b', ['c', ['d', 'e', ['f', 'g'], 'k'], 'l'], 'm', 'n', 'h', 'i', 'j']

Exercise 9: Replace list’s item with new value if found?

You have given a Python list. Write a program to find value 20 in the list, and if it is present, replace it with 200. Only update the first
occurrence of an item

list1 = [5, 10, 15, 20, 25, 50, 20]


index = list1.index(20)
list1[index] = 200

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 35/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
print(list1)

[5, 10, 15, 200, 25, 50, 20]

Exercise 10: Remove all occurrences of a specific item from a list?

Given a Python list, write a program to remove all occurrences of item 20.

list1 = [5, 20, 15, 20, 25, 50, 20]


for i in list1:
if i == 20:
list1.remove(i)
print(list1)

[5, 15, 25, 50]

keyboard_arrow_down Python Dictionary Exercise with Solutions


Exercise 1: Convert two lists into a dictionary?

keys = ['Ten', 'Twenty', 'Thirty']


values = [10, 20, 30]
d = dict(zip(keys,values))
print(d)

{'Ten': 10, 'Twenty': 20, 'Thirty': 30}

Exercise 2: Merge two Python dictionaries into one?

dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}


dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

dict4 = dict1.update(dict2)
print(dict1)
dict3 = {**dict1, **dict2}
print(dict3)

{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 36/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

Exercise 3: Print the value of key ‘history’ from the below dict

sampleDict = { "class": { "student": { "name": "Mike", "marks": { "physics": 70, "history": 80 } } } }

sampleDict = {
"class": {
"student": {
"name": "Mike",
"marks": {
"physics": 70,
"history": 80
}
}
}
}

print(sampleDict["class"]["student"]["marks"]["history"])

80

Exercise 4: Initialize dictionary with default values

employees = ['Kelly', 'Emma']


defaults = {"designation": 'Developer', "salary": 8000}
d = {employee:defaults for employee in employees}
print(d)

{'Kelly': {'designation': 'Developer', 'salary': 8000}, 'Emma': {'designation': 'Developer', 'salary': 8000}}

Exercise 5: Create a dictionary by extracting the keys from a given dictionary

sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New york"}

# Keys to extract
keys = ["name", "salary"]
new_dict = {k: sample_dict[k] for k in keys}
print(new_dict)

{'name': 'Kelly', 'salary': 8000}

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 37/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

Exercise 6: Delete a list of keys from a dictionary

sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New york"
}

# Keys to remove
keys = ["name", "salary"]

for k in keys:
sample_dict.pop(k)
print(sample_dict)

{'age': 25, 'city': 'New york'}

Exercise 7: Check if a value exists in a dictionary

Write a Python program to check if value 200 exists in the following dictionary.

sample_dict = {'a': 100, 'b': 200, 'c': 300}


for v in sample_dict.values():
if v == 200:
print("V is present ")
else:
pass

V is present

Exercise 8: Rename key of a dictionary

Write a program to rename a key city to a location in the following dictionary.

sample_dict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york"
}

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 38/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
sample_dict["location"] = sample_dict.pop("city")
print(sample_dict)

{'name': 'Kelly', 'age': 25, 'salary': 8000, 'location': 'New york'}

Exercise 9: Get the key of a minimum value from the following dictionary?

sample_dict = {
'Physics': 82,
'Math': 65,
'history': 75
}
print(min(sample_dict,key = sample_dict.get))

Math

Exercise 10: Change value of a key in a nested dictionary

Write a Python program to change Brad’s salary to 8500 in the following dictionary.

sample_dict = {
'emp1': {'name': 'Jhon', 'salary': 7500},
'emp2': {'name': 'Emma', 'salary': 8000},
'emp3': {'name': 'Brad', 'salary': 500}
}

sample_dict['emp3']['salary'] = 8500
print(sample_dict)

{'emp1': {'name': 'Jhon', 'salary': 7500}, 'emp2': {'name': 'Emma', 'salary': 8000}, 'emp3': {'name': 'Brad', 'salary': 8500}}

keyboard_arrow_down Python Set Exercise with Solutions


Exercise 1: Add a list of elements to a set

sample_set = {"Yellow", "Orange", "Black"}


sample_list = ["Blue", "Green", "Red"]
sample_set.update(sample_list)
print(sample_set)

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 39/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

{'Yellow', 'Green', 'Black', 'Blue', 'Red', 'Orange'}

Exercise 2: Return a new set of identical items from two sets

set1 = {10, 20, 30, 40, 50}


set2 = {30, 40, 50, 60, 70}
print(set1.intersection(set2))

{40, 50, 30}

Exercise 3: Get Only unique items from two sets

Write a Python program to return a new set with unique items from both sets by removing duplicates.

set1 = {10, 20, 30, 40, 50}


set2 = {30, 40, 50, 60, 70}
print(set1.union(set2))

{70, 40, 10, 50, 20, 60, 30}

Exercise 4: Update the first set with items that don’t exist in the second set

Given two Python sets, write a Python program to update the first set with items that exist only in the first set and not in the second set.

set1 = {10, 20, 30}


set2 = {20, 40, 50}
set1.difference_update(set2)
print(set1)

{10, 30}

Exercise 5: Remove items from the set at once

Write a Python program to remove items 10, 20, 30 from the following set at once.

set1 = {10, 20, 30, 40, 50}


set1.difference_update({10, 20, 30})
print(set1)

{50, 40}

Exercise 6: Return a set of elements present in Set A or B, but not both


https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 40/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

set1 = {10, 20, 30, 40, 50}


set2 = {30, 40, 50, 60, 70}
print(set1.symmetric_difference(set2))

{20, 70, 10, 60}

Exercise 7: Check if two sets have any elements in common. If yes, display the common elements

set1 = {10, 20, 30, 40, 50}


set2 = {60, 70, 80, 90, 10}
if set1.isdisjoint(set2):
print("Two sets have no items in common")
else :
print(set1.intersection(set2))

{10}

Exercise 8: Update set1 by adding items from set2, except common items

set1 = {10, 20, 30, 40, 50}


set2 = {30, 40, 50, 60, 70}
set1.symmetric_difference_update(set2)
print(set1)

{20, 70, 10, 60}

Exercise 9: Remove items from set1 that are not common to both set1 and set2

set1 = {10, 20, 30, 40, 50}


set2 = {30, 40, 50, 60, 70}
set1.intersection_update(set2)
print(set1)

{40, 50, 30}

keyboard_arrow_down Python Tuple Exercise with Solutions


Exercise 1: Reverse the tuple

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 41/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

tuple1 = (10, 20, 30, 40, 50)


list1 = tuple(tuple1)
reverse_list = []
for i in range(len(list1)-1,-1,-1):
reverse_list.append(list1[i])
tuple_1 = tuple(reverse_list)
print(tuple_1)

(50, 40, 30, 20, 10)

Exercise 2: Access value 20 from the tuple

The given tuple is a nested tuple. write a Python program to print the value 20.

tuple1 = ("Orange", [10, 20, 30], (5, 15, 25))


print(tuple1[1][1])

20

Exercise 3: Create a tuple with single item 50

tupl1= (50,)
print(tupl1)

(50,)

Exercise 4: Unpack the tuple into 4 variables

Write a program to unpack the following tuple into four variables and display each variable.

tuple1 = (10, 20, 30, 40)


a,b,c,d = tuple1
print(a)
print(b)
print(c)
print(d)

10
20
30
40

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 42/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

Exercise 5: Swap two tuples in Python

tuple1 = (11, 22)


tuple2 = (99, 88)
tuple1,tuple2 = tuple2,tuple1
print(tuple1)
print(tuple2)

(99, 88)
(11, 22)

Exercise 6: Copy specific elements from one tuple to a new tuple

Write a program to copy elements 44 and 55 from the following tuple into a new tuple.

tuple1 = (11, 22, 33, 44, 55, 66)


tuple2 = tuple1[3:len(tuple1)-1]
print(tuple2)

(44, 55)

Exercise 7: Modify the tuple

Given is a nested tuple. Write a program to modify the first item (22) of a list inside a following tuple to 222

tuple1 = (11, [22, 33], 44, 55)


tuple1[1][0] = 222
print(tuple1)

(11, [222, 33], 44, 55)

Exercise 8: Sort a tuple of tuples by 2nd item

tuple1 = (('a', 23),('b', 37),('c', 11), ('d',29))

tuple1 = tuple(sorted(list(tuple1), key=lambda x: x[1]))


print(tuple1)

(('c', 11), ('a', 23), ('d', 29), ('b', 37))

Exercise 9: Counts the number of occurrences of item 50 from a tuple

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 43/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

tuple1 = (50, 10, 60, 70, 50)


list_t = list(tuple1)
tpl2 =[]
for i in list_t:
if i == 50:
tpl2.append(i)
tpl2 = list(tpl2)
print(tpl2)
print(len(tpl2))

[50, 50]
2

Exercise 10: Check if all items in the tuple are the same

tuple1 = (45, 45, 45, 45)


if all(i == tuple1[0] for i in tuple1):
print("All items in the tuple are same")

All items in the tuple are same

keyboard_arrow_down Python Date and Time Exercise with Solutions


Exercise 1: Print current date and time in Python

import datetime
print(datetime.datetime.now())

2025-01-06 12:48:34.642580

Exercise 2: Convert string into a datetime object

from datetime import datetime


date_string = "Jan 06 2025 4:20PM"
time = datetime.strptime(date_string, '%b %d %Y %I:%M%p')
print(time)

2025-01-06 16:20:00

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 44/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab

Exercise 3: Subtract a week (7 days) from a given date in Python

from datetime import datetime,timedelta


given_date = datetime(2025, 1, 6)
subtract_days = 7
res = given_date - timedelta(days = subtract_days)
print(res)

2024-12-30 00:00:00

Exercise 4: Print a date in a the following format

Day_name Day_number Month_name Year

given_date = datetime(2025, 1, 6)
print(given_date.strftime('%A %d %B %Y'))

Monday 06 January 2025

Exercise 5: Find the day of the week of a given date

given_date = datetime(2025, 1, 6)
print(given_date.today().weekday())
print(given_date.strftime('%A'))

0
Monday

Exercise 6: Add a week (7 days) and 12 hours to a given date

from datetime import datetime,timedelta


given_date = datetime(2025,1,6)
add_days = 7
new_time = given_date + timedelta(days = 7,hours = 10)
print(new_time)

2025-01-13 10:00:00

Exercise 7: Print current time in milliseconds

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 45/46
2/18/25, 2:27 AM pythonexcercise.ipynb - Colab
import time

milliseconds = int(round(time.time() * 1000))


print(milliseconds)

1736170092404

Exercise 8: Convert the following datetime into a string

given_date = datetime(2020, 2, 25)


string_date = given_date.strftime("%Y-%m-%d %H:%M:%S")
print(string_date)

2020-02-25 00:00:00

Exercise 9: Calculate the date 4 months from the current date

from datetime import datetime

from dateutil.relativedelta import relativedelta

https://colab.research.google.com/drive/1nxEXJIHERtz6ZsAyQetpNTnXANK_yKjw#scrollTo=QIyuUAigYERh&printMode=true 46/46

You might also like