Python Practical Lab

14 experiments · Copy-ready Python programs · Indentation preserved

Important: Use the Copy Code button for each program. It copies the original code with its spaces and line breaks. Run the code in Python 3. Some programs ask for input.
Showing 14 experiments

1. Base Conversion of an Integer

Number system

Converts a decimal integer into binary, octal and hexadecimal forms.

Python 3
number = int(input("Enter a decimal integer: "))

print("Binary      :", bin(number))
print("Octal       :", oct(number))
print("Hexadecimal :", hex(number))

2. Type Conversion of Different Data Types

Data types

Demonstrates conversion to int, float, complex, bool and string.

Python 3
integer_value = 10
float_value = 12.5
complex_value = 3 + 4j
bool_value = True
string_value = "25"

print("Integer to float:", float(integer_value))
print("Float to integer:", int(float_value))
print("Integer to complex:", complex(integer_value))
print("Integer to boolean:", bool(integer_value))
print("String to integer:", int(string_value))
print("Integer to string:", str(integer_value))

print("Type of complex_value:", type(complex_value))
print("Type of bool_value:", type(bool_value))

3. String Manipulation Using Slicing and Negative Index

String

Shows positive indexing, negative indexing and slicing.

Python 3
text = input("Enter a string: ")

print("Original string:", text)
print("First character:", text[0])
print("Last character:", text[-1])
print("First five characters:", text[:5])
print("Characters from index 2 to 5:", text[2:6])
print("String in reverse:", text[::-1])

4. Swap Two Variables With and Without a Temporary Variable

Variables

Demonstrates both swapping methods.

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

print("Before swapping: a =", a, "b =", b)

# Method 1: Using a temporary variable
temp = a
a = b
b = temp

print("After swapping with temporary variable:")
print("a =", a, "b =", b)

# Method 2: Without a temporary variable
a, b = b, a

print("After swapping again without temporary variable:")
print("a =", a, "b =", b)

5. Linear Search in a List

Searching

Checks each element one by one until the target is found.

Python 3
numbers = [10, 20, 30, 40, 50]
target = int(input("Enter the number to search: "))

found = False

for index in range(len(numbers)):
    if numbers[index] == target:
        print("Element found at index:", index)
        found = True
        break

if not found:
    print("Element not found")

6. Binary Search in a List

Searching

Searches a sorted list by repeatedly dividing the search range into half.

Python 3
numbers = [10, 20, 30, 40, 50, 60, 70]
target = int(input("Enter the number to search: "))

low = 0
high = len(numbers) - 1
found = False

while low <= high:
    mid = (low + high) // 2

    if numbers[mid] == target:
        print("Element found at index:", mid)
        found = True
        break
    elif numbers[mid] < target:
        low = mid + 1
    else:
        high = mid - 1

if not found:
    print("Element not found")

7. Matrix Addition and Matrix Multiplication

Matrices

Adds two 2×2 matrices and multiplies them using nested loops.

Python 3
A = [[1, 2],
     [3, 4]]

B = [[5, 6],
     [7, 8]]

# Matrix addition
addition = [[0, 0],
            [0, 0]]

for i in range(2):
    for j in range(2):
        addition[i][j] = A[i][j] + B[i][j]

print("Matrix Addition:")
for row in addition:
    print(row)

# Matrix multiplication
multiplication = [[0, 0],
                  [0, 0]]

for i in range(2):
    for j in range(2):
        for k in range(2):
            multiplication[i][j] += A[i][k] * B[k][j]

print("Matrix Multiplication:")
for row in multiplication:
    print(row)

8. Calculate HCF and LCM

Mathematics

Uses the Euclidean algorithm to calculate HCF, then calculates LCM.

Python 3
a = int(input("Enter first positive integer: "))
b = int(input("Enter second positive integer: "))

x = a
y = b

while y != 0:
    x, y = y, x % y

hcf = x

if hcf != 0:
    lcm = abs(a * b) // hcf
else:
    lcm = 0

print("HCF =", hcf)
print("LCM =", lcm)

9. Egg Dropping Problem – Minimum Trials

Dynamic programming

Finds the minimum number of trials needed in the worst case for a given number of eggs and floors.

Python 3
eggs = int(input("Enter number of eggs: "))
floors = int(input("Enter number of floors: "))

dp = [[0 for _ in range(floors + 1)]
      for _ in range(eggs + 1)]

for e in range(1, eggs + 1):
    dp[e][0] = 0
    if floors >= 1:
        dp[e][1] = 1

for f in range(1, floors + 1):
    dp[1][f] = f

for e in range(2, eggs + 1):
    for f in range(2, floors + 1):
        dp[e][f] = float("inf")

        for x in range(1, f + 1):
            trials = 1 + max(
                dp[e - 1][x - 1],
                dp[e][f - x]
            )
            dp[e][f] = min(dp[e][f], trials)

print("Minimum number of trials:", dp[eggs][floors])

10. Remove Palindrome Words, Punctuation Marks and Symbols

String processing

Cleans a string by removing punctuation/symbols and palindrome words. Enter at least 50 characters.

Python 3
import string

text = input("Enter a string (at least 50 characters): ")

if len(text) < 50:
    print("Please enter at least 50 characters.")
else:
    # Remove punctuation marks and symbols
    cleaned = ""
    for char in text:
        if char.isalnum() or char.isspace():
            cleaned += char

    # Remove palindrome words
    words = cleaned.split()
    result = []

    for word in words:
        if word.lower() != word.lower()[::-1]:
            result.append(word)

    final_text = " ".join(result)

    print("Original string:", text)
    print("Final string:", final_text)

11. Sorting a Collection – Insertion Sort and Selection Sort

Sorting

Sorts the same list using insertion sort and selection sort.

Python 3
numbers = [64, 25, 12, 22, 11]

# Insertion Sort
insertion = numbers.copy()

for i in range(1, len(insertion)):
    key = insertion[i]
    j = i - 1

    while j >= 0 and insertion[j] > key:
        insertion[j + 1] = insertion[j]
        j -= 1

    insertion[j + 1] = key

print("Insertion Sort:", insertion)

# Selection Sort
selection = numbers.copy()

for i in range(len(selection)):
    min_index = i

    for j in range(i + 1, len(selection)):
        if selection[j] < selection[min_index]:
            min_index = j

    selection[i], selection[min_index] = selection[min_index], selection[i]

print("Selection Sort:", selection)

12. Demonstrate Different Types of Parameter Passing

Functions

Demonstrates positional, keyword, default and variable-length arguments.

Python 3
# 1. Positional arguments
def student(name, age):
    print("Name:", name)
    print("Age:", age)

student("Rahul", 20)

# 2. Keyword arguments
student(age=21, name="Aman")

# 3. Default argument
def greet(name="Student"):
    print("Hello", name)

greet()
greet("Rahul")

# 4. Variable-length positional arguments
def add_numbers(*numbers):
    print("Sum:", sum(numbers))

add_numbers(10, 20, 30)

# 5. Variable-length keyword arguments
def show_details(**details):
    for key, value in details.items():
        print(key, ":", value)

show_details(name="Rahul", age=20, city="Agartala")

13. Exception Handling of Five Well-Known Errors

Error handling

Demonstrates ZeroDivisionError, ValueError, TypeError, IndexError and KeyError.

Python 3
# 1. ZeroDivisionError
try:
    print(10 / 0)
except ZeroDivisionError:
    print("Error: Cannot divide by zero")

# 2. ValueError
try:
    number = int("hello")
except ValueError:
    print("Error: Invalid value")

# 3. TypeError
try:
    print("Age: " + 20)
except TypeError:
    print("Error: Incompatible data types")

# 4. IndexError
try:
    values = [10, 20, 30]
    print(values[5])
except IndexError:
    print("Error: List index out of range")

# 5. KeyError
try:
    student = {"name": "Rahul"}
    print(student["age"])
except KeyError:
    print("Error: Dictionary key not found")

14. Create a Custom Exception Class for an Egg Dropping Application

Custom exception

Defines a custom exception and validates the number of eggs and floors before solving the egg-dropping problem.

Python 3
class InvalidInputError(Exception):
    pass


def egg_drop(eggs, floors):
    if eggs <= 0 or floors < 0:
        raise InvalidInputError(
            "Eggs must be positive and floors cannot be negative."
        )

    if floors == 0:
        return 0

    if eggs == 1:
        return floors

    dp = [[0 for _ in range(floors + 1)]
          for _ in range(eggs + 1)]

    for e in range(1, eggs + 1):
        dp[e][1] = 1

    for f in range(1, floors + 1):
        dp[1][f] = f

    for e in range(2, eggs + 1):
        for f in range(2, floors + 1):
            dp[e][f] = float("inf")

            for x in range(1, f + 1):
                trials = 1 + max(
                    dp[e - 1][x - 1],
                    dp[e][f - x]
                )
                dp[e][f] = min(dp[e][f], trials)

    return dp[eggs][floors]


try:
    eggs = int(input("Enter number of eggs: "))
    floors = int(input("Enter number of floors: "))

    result = egg_drop(eggs, floors)
    print("Minimum trials required:", result)

except InvalidInputError as error:
    print("Custom Exception:", error)

except ValueError:
    print("Please enter valid integer values.")