CSCSEC151: Python Programming (Lab Notes)

Lab Objectives

This practical part aims to:

Laboratory Programming Assignments

Assignment 1: Celsius/Fahrenheit Table

Task: Using a loop, print a table of Celsius/Fahrenheit equivalences from 0 to 100.

Logic

The formula is F = (C * 9/5) + 32.

print("Celsius  |  Fahrenheit")
print("-----------------------")
for c in range(0, 101):
    f = (c * 9/5) + 32
    print(f"{c:7}  |  {f:10.1f}")

Assignment 2: Sin/Cos/Tan Table

Task: Using a while loop, produce a table of sins, cosines, and tangents for x from 0 to 10 in steps of 0.2.

Logic

You must import the math module.

import math

print("x    |  sin(x)  |  cos(x)  |  tan(x)")
print("--------------------------------------")
x = 0.0
while x <= 10.0:
    s = math.sin(x)
    c = math.cos(x)
    t = math.tan(x)
    print(f"{x:.1f}  |  {s:+.4f}  |  {c:+.4f}  |  {t:+.4f}")
    x += 0.2

Assignment 3: Leap Year

Task: Read an integer and print "leap year" or "not a leap year".

Logic

A leap year is divisible by 4, except for years divisible by 100, unless they are also divisible by 400.

year = int(input("Enter a year: "))

if (year % 400 == 0) or (year % 100 != 0 and year % 4 == 0):
    print(f"{year} is a leap year.")
else:
    print(f"{year} is not a leap year.")

Assignments 4 & 5: Pattern Printing [cite: 383, 385-389]

Task: Take a number n and print a pattern (e.g., a triangle of stars).

Logic

This uses nested loops. The outer loop controls the rows, the inner loop controls the columns.

n = 5
for i in range(1, n + 1):
    for j in range(i):
        print("*", end="")
    print() # Newline

Assignment 6: Series Calculation [cite: 390-391]

Task: Write a function that takes n and calculates 1 + 1/1! + 1/2! + ... + 1/n!

Logic

import math

def calculate_series(n):
    total_sum = 1.0
    for i in range(1, n + 1):
        total_sum += 1 / math.factorial(i)
    return total_sum

print(calculate_series(5))

Assignments 7 & 8: Factorial & Palindrome [cite: 392-393]

Task 7: Write a function to calculate the factorial of an integer.

Task 8: Write a function to check if a string is a palindrome.

Logic

def factorial(n):
    if n == 0:
        return 1
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result

def is_palindrome(s):
    # s[::-1] creates a reversed copy of the string
    return s == s[::-1]

print(factorial(5))
print(is_palindrome("racecar"))
print(is_palindrome("hello"))

Assignments 9-14: Basic Problems [cite: 394-399]

Assignment 15: Sorting

Task: Sort a list using Insertion, Bubble, and Selection sort.

Logic

def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

# (Implement selection_sort and insertion_sort similarly)

Assignments 16 & 17: File/Exception Handling & Strings [cite: 401-402]

Task 16: Problems related to file handling and exceptions.

Task 17: Problems related to string manipulations.

Logic

# Exception Handling
try:
    f = open("non_existent_file.txt", "r")
    print(f.read())
except FileNotFoundError:
    print("Error: The file was not found.")
except Exception as e:
    print(f"An error occurred: {e}")

# String Manipulation
s = "   Hello, World!   "
print(s.strip())         # "Hello, World!"
print(s.split(','))      # ['   Hello', ' World!   ']
print(s.upper())         # "   HELLO, WORLD!   "

Assignment 18: Plotting

Task: Write a program to draw a line, bar, histogram, pie chart, etc.

Logic

Requires matplotlib. (Run pip install matplotlib first).

import matplotlib.pyplot as plt

# --- Bar Chart ---
labels = ['A', 'B', 'C']
values = [10, 40, 20]
plt.bar(labels, values)
plt.title("Bar Chart")
plt.show()

# --- Pie Chart ---
sizes = [15, 30, 45, 10]
plt.pie(sizes, labels=['Frogs', 'Hogs', 'Dogs', 'Logs'], autopct='%1.1f%%')
plt.title("Pie Chart")
plt.show()