Python Lab Manual (With Code)
Program 1
Objective: Find factorial using recursion
Code:
def factorial(n):
return 1 if n == 0 else n * factorial(n - 1)
print("Factorial of 5 is", factorial(5))
Expected Output:
Factorial of 5 is 120
Program 2
Objective: Simple calculator using functions
Code:
def add(a, b): return a + b
print("Sum is", add(2, 3))
Expected Output:
Sum is 5
Program 3
Objective: Check palindrome string
Code:
s = "madam"
print("Palindrome" if s == s[::-1] else "Not Palindrome")
Expected Output:
Palindrome
Program 4
Objective: Fibonacci series
Code:
a, b = 0, 1
for _ in range(6):
print(a, end=' ')
a, b = b, a + b
Expected Output:
011235
Program 5
Objective: Prime number check
Code:
num = 7
if all(num % i != 0 for i in range(2, int(num ** 0.5) + 1)):
print("Prime")
else:
print("Not Prime")
Expected Output:
Prime
Program 6
Objective: Sum of list elements
Code:
nums = [1, 2, 3]
print("Sum is", sum(nums))
Expected Output:
Sum is 6
Program 7
Objective: String reverse
Code:
s = "hello"
print(s[::-1])
Expected Output:
olleh
Program 8
Objective: Armstrong number
Code:
n = 153
print("Armstrong" if sum(int(d)**3 for d in str(n)) == n else "Not Armstrong")
Expected Output:
Armstrong
Program 9
Objective: Find largest of three numbers
Code:
a, b, c = 4, 7, 1
print("Largest is", max(a, b, c))
Expected Output:
Largest is 7
Program 10
Objective: Simple file read/write
Code:
with open("file.txt", "w") as f:
f.write("Hello World")
with open("file.txt", "r") as f:
print(f.read())
Expected Output:
Hello World