Python Fundamentals – Lab Exercises with Solutions
1: Getting Started with Python
Exercise 1:
Write a program to display a welcome message.
Solution:
print("Welcome to Python Programming")
Exercise 2:
Add two numbers and display the result.
Solution:
a = 10
b = 20
print(a + b)
2: Variables and Data Types
Exercise 3:
Create variables of different data types and display their types.
Solution:
x = 25
y = 3.5
z = 'Python'
print(type(x), type(y), type(z))
Exercise 4:
Demonstrate dynamic typing.
Solution:
a = 10
print(type(a))
a = 'DS'
print(type(a))
3: Variable Operations and Casting
Exercise 5:
Multiple assignment.
Solution:
a, b, c = 'Apple', 'Banana', 'Cherry'
print(a, b, c)
Exercise 6:
Type casting.
Solution:
num = '50'
print(int(num))
print(float(num))
4: Data Structures
Exercise 7:
List operations.
Solution:
nums = [10, 20, 30]
[Link](40)
[Link](20)
print(nums)
Exercise 8:
Tuple immutability demonstration.
Solution:
t = (1, 2, 3)
print(t)
Exercise 9:
Dictionary iteration.
Solution:
stu = {'name': 'Rahul', 'age': 21}
for k, v in [Link]():
print(k, v)
Exercise 10:
Remove duplicates using set.
Solution:
vals = [1, 2, 2, 3]
print(set(vals))
5: Operators
Exercise 11:
Arithmetic operators.
Solution:
a = 15
b=4
print(a + b, a - b, a * b, a / b, a // b, a % b, a ** b)
Exercise 12:
Logical operators.
Solution:
num = 25
print(num > 10 and num < 50)
6: Control Flow
Exercise 13:
Even or odd.
Solution:
num = 7
print('Even' if num % 2 == 0 else 'Odd')
Exercise 14:
Grade calculation.
Solution:
m = 78
if m >= 90:
print('A')
elif m >= 75:
print('B')
elif m >= 60:
print('C')
else:
print('Fail')
7: Loops
Exercise 15:
For loop.
Solution:
for i in range(1, 11):
print(i)
Exercise 16:
While loop.
Solution:
i=5
while i > 0:
print(i)
i -= 1
Exercise 17:
Continue example.
Solution:
for i in range(1, 11):
if i == 5:
continue
print(i)
Exercise 18:
Loop else.
Solution:
nums = [2, 4, 6]
for n in nums:
if n == 6:
print('Found')
break
else:
print('Not found')
8: Safe Iteration
Exercise 19:
Remove negative numbers safely.
Solution:
vals = [10, -5, 20]
for v in [Link]():
if v < 0:
[Link](v)
print(vals)