This practical part aims to:
Task: Using a loop, print a table of Celsius/Fahrenheit equivalences from 0 to 100.
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}")
Task: Using a while loop, produce a table of sins, cosines, and tangents for x from 0 to 10 in steps of 0.2.
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
Task: Read an integer and print "leap year" or "not a leap year".
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.")
Task: Take a number n and print a pattern (e.g., a triangle of stars).
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
Task: Write a function that takes n and calculates 1 + 1/1! + 1/2! + ... + 1/n!
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))
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.
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"))
list('abc') gives ['a', 'b', 'c'].if num % 2 == 0:if/elif/else.n, check if n % i == 0.
def gcd(a, b):
while b:
a, b = b, a % b
return a
print(gcd(48, 18))
Task: Sort a list using Insertion, Bubble, and Selection sort.
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)
Task 16: Problems related to file handling and exceptions.
Task 17: Problems related to string manipulations.
# 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! "
Task: Write a program to draw a line, bar, histogram, pie chart, etc.
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()