Python Lab Questions


 Here is the complete blog post in English, formatted for your Blogger website.


Python Lab VIVA Notes: 28+  Programs (Beginner to Advanced)

Here are some of the most essential programs and their solutions for your Python lab practicals. This list covers everything from basic loops, strings, functions, and data structures (Lists, Tuples, Dictionaries).


1. Find the Largest of Three Numbers

Question: Write a Python program to find the largest of three numbers.

 Code:

Python
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

if a >= b and a >= c:
    print("Largest number is", a)
elif b >= a and b >= c:
    print("Largest number is", b)
else:
    print("Largest number is", c)

Output:

Plaintext
Enter first number: 12
Enter second number: 35
Enter third number: 9
Largest number is 35

Question:2 Python program to print half pyramid, inverted half pyramid, full and right angled pyramid


Code:

# Half Pyramid def half_pyramid(n): for i in range(1, n + 1): print('*' * i) # Inverted Half Pyramid def inverted_half_pyramid(n): for i in range(n, 0, -1): print('*' * i) # Full Pyramid def full_pyramid(n): for i in range(1, n + 1): print(' ' * (n - i) + '*' * (2 * i - 1)) # Right Angled Pyramid (Triangle) def right_angled_pyramid(n): for i in range(1, n + 1): print(' ' * (n - i) + '*' * i) # Main function to call all pyramids def main(): n = int(input("Enter the number of rows: ")) print("\nHalf Pyramid:") half_pyramid(n) print("\nInverted Half Pyramid:") inverted_half_pyramid(n) print("\nFull Pyramid:") full_pyramid(n) print("\nRight Angled Pyramid:") right_angled_pyramid(n) # Run the program if __name__ == "__main__": main()

Sample Output for n = 5:

Enter the number of rows: 5 Half Pyramid: * ** *** **** ***** Inverted Half Pyramid: ***** **** *** ** * Full Pyramid: * *** ***** ******* ********* Right Angled Pyramid: * ** *** **** *****


Question:3. Check if a Number is Even or Odd


Question: Write a program to check whether a given number is even or odd.
Plaintext
### Python Code:
```python
num = int(input("Enter a number: "))

if num % 2 == 0:
    print("Even")
else:
    print("Odd")

Output:

Plaintext
Enter a number: 7
Odd

4. Calculate the Factorial of a Number

Question: Write a Python program to calculate the factorial of a number using a loop.

Code:

Python
num = int(input("Enter a number: "))
fact = 1

for i in range(1, num + 1):
    fact *= i

print("Factorial:", fact)

Output:

Plaintext
Enter a number: 5
Factorial: 120

5. Display the Multiplication Table

Question: Write a program to display the multiplication table of a given number.

Code:

Python
n = int(input("Enter a number: "))

for i in range(1, 11):
    print(f"{n} x {i} = {n * i}")

Output:

Plaintext
Enter a number: 7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

6. Sum of Even Numbers from 1 to N

Question: Write a program to find the sum of all even numbers between 1 and N using a for loop.

Code:

Python
N = int(input("Enter N: "))
total = 0

for i in range(2, N + 1, 2):
    total += i

print("Sum of even numbers:", total)

Output:

Plaintext
Enter N: 10
Sum of even numbers: 30

7. Demonstrate break, continue, and pass

Question: Write a program to demonstrate the use of break, continue, and pass statements.

Code:

Python
for i in range(1, 6):
    if i == 3:
        pass  # Does nothing, just a placeholder
    elif i == 4:
        continue  # Skips this iteration
    elif i == 5:
        break  # Exits the loop
    print(i)

Output:

Plaintext
1
2
3

8. GCD with Euclid’s Algorithm

Question: Write a program to check GCD (Greatest Common Divisor) with Euclid’s algorithm.

Code:

Python
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

print("GCD:", gcd(48, 18))

Output:

Plaintext
GCD: 6

9. Print Even Powers of 2

Question: Write a program to print even powers of 2.

Code:

Python
# Prints even powers from 0 up to 10
for i in range(0, 11, 2):
    print(2 ** i)

Output:

Plaintext
1
4
16
64
256
1024

10. Nested For Loop with Jumping Statements

Question: Write a program for a nested for loop using jumping statements (continue).

Code:

Python
for i in range(3):
    for j in range(3):
        if j == 1:
            continue  # Skips the rest of the inner loop
        print(f"{i}, {j}")

Output:

Plaintext
0, 0
0, 2
1, 0
1, 2
2, 0
2, 2

11. Check Armstrong and Palindrome

Question: Write a program to check if a number is an Armstrong number and a Palindrome simultaneously.

Code:

Python
def is_armstrong(n):
    # Assuming 3-digit Armstrong number
    return n == sum(int(d) ** 3 for d in str(n))

def is_palindrome(n):
    return str(n) == str(n)[::-1]

num = int(input("Enter a number: "))
print("Armstrong:", is_armstrong(num))
print("Palindrome:", is_palindrome(num))

Output:

Plaintext
Enter a number: 153
Armstrong: True
Palindrome: False

12. Return Nth Value in Fibonacci Series

Question: Write a program to return the Nth value in a Fibonacci series.

Code:

Python
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

n = int(input("Enter n: "))
print("Fibonacci value:", fibonacci(n))
or 
def fibonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        a, b = 0, 1
        for _ in range(2, n+1):
            a, b = b, a + b
        return b

n = int(input("Enter n: "))
print("Fibonacci value:", fibonacci(n))

Output:

Plaintext
Enter n: 7
Fibonacci value: 13

13. Multiply Matrices and Check for Identity Matrix

Question: Write a program to multiply two matrices and check if the resulting matrix is an identity matrix.

Code:

Python
def multiply_matrices(A, B):
    result = []
    for i in range(len(A)):
        row = []
        for j in range(len(B[0])):
            s = 0
            for k in range(len(B)):
                s += A[i][k] * B[k][j]
            row.append(s)
        result.append(row)
    return result

def is_identity(matrix):
    for i in range(len(matrix)):
        for j in range(len(matrix)):
            if i == j and matrix[i][j] != 1:
                return False
            elif i != j and matrix[i][j] != 0:
                return False
    return True

A = [[1, 0], [0, 1]]
B = [[1, 0], [0, 1]]
result = multiply_matrices(A, B)

print("Result:", result)
print("Is identity matrix:", is_identity(result))

Output:

Plaintext
Result: [[1, 0], [0, 1]]
Is identity matrix: True

14. Count Vowels and Consonants in a String

Question: Write a program to count the number of vowels and consonants in a given string.

Code:

Python
s = input("Enter string: ").lower()
vowels = 0
consonants = 0

for ch in s:
    if ch.isalpha():  # Checks if the character is an alphabet
        if ch in 'aeiou':
            vowels += 1
        else:
            consonants += 1

print("Vowels:", vowels)
print("Consonants:", consonants)

Output:

Plaintext
Enter string: hello world
Vowels: 3
Consonants: 7

15. Check if a String is a Palindrome

Question: Write a program to check whether a string is a palindrome or not.

Code:

Python
s = input("Enter string: ")

if s == s[::-1]:
    print("Palindrome")
else:
    print("Not Palindrome")

Output:

Plaintext
Enter string: madam
Palindrome

Note: You have to write only up to question no. 15 for the lab observation book

16. Remove Duplicates from a List

Question: Write a program to remove duplicates from a list (and preserve order).

Code:

Python
lst = [1, 2, 2, 3, 4, 1]
unique_lst = []

for item in lst:
    if item not in unique_lst:
        unique_lst.append(item)

print(unique_lst)

Output:

Plaintext
[1, 2, 3, 4]

17. Convert Numeric Words to Numbers

Question: Write a Python program to convert numeric words to numbers using a loop, list, and dictionary.

Code:

Python
words = ['one', 'three', 'five']
mapping = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
numbers = []

for word in words:
    if word in mapping:
        numbers.append(mapping[word])

print(numbers)

Output:

Plaintext
[1, 3, 5]

18. Reverse Sort a String

Question: Write a program to reverse sort a string (Z to A).

Code:

Python
s = input("Enter string: ")
sorted_str = "".join(sorted(s, reverse=True))
print(sorted_str)

Output:

Plaintext
Enter string: python
ytphon

19. Check for Duplicate Letters in Words

Question: Write a function that accepts a sentence. The function should return True if the sentence has any word with duplicate letters, else return False.

Code:

Python
def has_duplicate_letters(sentence):
    for word in sentence.split():
        if len(set(word)) != len(word):
            return True  # Found a word with duplicates
    return False

sentence = input("Enter sentence: ")
print(has_duplicate_letters(sentence))

Output:

Plaintext
Enter sentence: hello world
True

20-22. Student Record Management (Multiple Functions)

Question: Write a Python program using multiple functions to manage student records. Input details for n students, calculate total/average, and determine the grade.

Code:

Python
def input_students(n):
    students = []
    for _ in range(n):
        name = input("Enter name: ")
        roll = int(input("Enter roll number: "))
        marks = [int(input(f"Enter mark {i+1}: ")) for i in range(3)]
        students.append((name, roll, marks))
    return students

def calc_total_avg(marks):
    total = sum(marks)
    avg = total / len(marks)
    return total, avg

def determine_grade(avg):
    if avg >= 90:
        return 'A'
    elif avg >= 75:
        return 'B'
    elif avg >= 50:
        return 'C'
    else:
        return 'D'

n = int(input("Enter number of students: "))
students = input_students(n)

for student in students:
    total, avg = calc_total_avg(student[2])
    grade = determine_grade(avg)
    print(f"Name: {student[0]}, Roll: {student[1]}, Total: {total}, Average: {avg:.2f}, Grade: {grade}")

Output (Example):

Plaintext
Enter number of students: 1
Enter name: John
Enter roll number: 101
Enter mark 1: 85
Enter mark 2: 90
Enter mark 3: 78
Name: John, Roll: 101, Total: 253, Average: 84.33, Grade: B

23. Create and Display a Tuple

Question: Write a program to create a tuple and display its elements using a for loop.

Python Code:

Python
tup = (1, 2, 3, 4, 5)

for item in tup:
    print(item)

Output:

Plaintext
1
2
3
4
5

24. Count Word Frequency in a Sentence

Question: Write a program to count the frequency of each word in a given sentence using a dictionary.

Code:

Python
sentence = input("Enter sentence: ")
freq = {}

for word in sentence.split():
    freq[word] = freq.get(word, 0) + 1

print(freq)

Output:

Plaintext
Enter sentence: python is fun python is easy
{'python': 2, 'is': 2, 'fun': 1, 'easy': 1}

25. Dictionary Operations (Sum, Remove, Merge)

Question: Write a program to find the sum of all items, remove a key, and merge two dictionaries.

Code:

Python
d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 4}

# Sum of all values in d1
total_sum = sum(d1.values())

# Remove key 'a'
d1.pop('a', None)

# Merge d1 and d2 (d2 values overwrite d1)
merged = d1.copy()
merged.update(d2)

print("Sum:", total_sum)
print("After removing 'a':", d1)
print("Merged dictionary:", merged)

Output:

Plaintext
Sum: 3
After removing 'a': {'b': 2}
Merged dictionary: {'b': 3, 'c': 4}

26. Find Maximum and Minimum in a List

Question: Write a Python function that accepts a list of numbers and returns the maximum and minimum values.

Code:

Python
def max_min(lst):
    return max(lst), min(lst)

numbers = [2, 6, 3, 1]
maximum, minimum = max_min(numbers)

print("Max:", maximum)
print("Min:", minimum)

Output:

Plaintext
Max: 6
Min: 1

27. Join Tuples with Similar Initial Element

Question: Write a program to join tuples if they have a similar initial element.

Code:

Python
tuples = [(1, 'a'), (1, 'b'), (2, 'c'), (2, 'd')]
joined = {}

for t in tuples:
    if t[0] in joined:
        joined[t[0]] += t[1]  # 'a' + 'b' = 'ab'
    else:
        joined[t[0]] = t[1]

print(joined)

Output:

Plaintext
{1: 'ab', 2: 'cd'}

28. Stats Function with Variable Arguments

Question: Write a program that uses a function accepting a variable number of numeric arguments (*args) and returns the sum, average, maximum, and minimum.

Code:

Python
def stats(*args):
    total = sum(args)
    avg = total / len(args) if args else 0
    maximum = max(args) if args else None
    minimum = min(args) if args else None
    return total, avg, maximum, minimum

print(stats(1, 2, 3, 4, 5))

Output:

Plaintext
(15, 3.0, 5, 1)

Hope these notes help you with your lab exam. Happy Coding! 🐍

Author : Rahul Choudhary

Previous Post Next Post

Contact Form