PYTHON PROGRAMMING FILE
Task 1: Write a program to demonstrate different
number data types in Python.
# Program to demonstrate different number data types in Python
# Integer type
a = 10
print("a =", a, "is of type", type(a))
# Float type
b = 10.5
print("b =", b, "is of type", type(b))
# Complex type
c = 3 + 4j
print("c =", c, "is of type", type(c))
# Boolean type (a subtype of integers)
d = True
print("d =", d, "is of type", type(d))
# Demonstrating operations
print("\nSome operations:")
print("a + b =", a + b)
print("b * 2 =", b * 2)
print("Real part of c:", [Link])
print("Imaginary part of c:", [Link])
print("Boolean as integer:", int(d))
OUTPUT:
a = 10 is of type <class 'int'>
b = 10.5 is of type <class 'float'>
pg. 1
PYTHON PROGRAMMING FILE
c = (3+4j) is of type <class 'complex'>
d = True is of type <class 'bool'>
Some operations:
a + b = 20.5
b * 2 = 21.0
Real part of c: 3.0
Imaginary part of c: 4.0
Boolean as integer: 1
pg. 2
PYTHON PROGRAMMING FILE
TASK 2: Write a program to perform different Arithmetic
Operations on numbers in Python.
# Program to perform different Arithmetic Operations on numbers in Python
# Taking two numbers
a = 15
b=4
# Performing arithmetic operations
print("a =", a, "b =", b)
print("Addition: a + b =", a + b)
print("Subtraction: a - b =", a - b)
print("Multiplication: a * b =", a * b)
print("Division (float): a / b =", a / b)
print("Floor Division: a // b =", a // b)
print("Modulus (remainder): a % b =", a % b)
print("Exponentiation: a ** b =", a ** b)
OUTPUT:
a = 15 b = 4
Addition: a + b = 19
Subtraction: a - b = 11
Multiplication: a * b = 60
Division (float): a / b = 3.75
Floor Division: a // b = 3
Modulus (remainder): a % b = 3
Exponentiation: a ** b = 50625
pg. 3
PYTHON PROGRAMMING FILE
Task 3: Write a program to create, concatenate and
print a string and accessing sub-string from a given
string.
# Program to create, concatenate and print a string
# and access sub-strings from a given string
# Creating strings
str1 = "Hello"
str2 = "World"
# Concatenation of strings
concatenated_str = str1 + " " + str2
print("Concatenated String:", concatenated_str)
# Accessing substrings
print("First character of str1:", str1[0])
print("Last character of str2:", str2[-1])
print("Substring of concatenated string (0 to 4):", concatenated_str[0:5])
print("Substring of concatenated string (6 to end):", concatenated_str[6:])
OUTPUT:
Concatenated String: Hello World
First character of str1: H
Last character of str2: d
Substring of concatenated string (0 to 4): Hello
Substring of concatenated string (6 to end): World
pg. 4
PYTHON PROGRAMMING FILE
Task 4: Write a python script to print the current date in
the following format “Sun May 29 02:26:23 IST 2017”
# Program to print the current date and time in the format:
# “Sun May 29 02:26:23 IST 2017”
from datetime import datetime
import time
# Get current local time
current_time = [Link]()
# Format it
formatted_time = current_time.strftime("%a %b %d %H:%M:%S %Z %Y")
# If timezone info is missing, manually append IST
if not formatted_time.endswith("IST 2025"): # Fallback for systems without TZ
formatted_time = current_time.strftime("%a %b %d %H:%M:%S") + " IST " +
current_time.strftime("%Y")
print("Current Date and Time:", formatted_time)
OUTPUT:
Current Date and Time: Tue Nov 11 12:48:23 IST 2025
pg. 5
PYTHON PROGRAMMING FILE
Task 5: Write a program to create, append, and remove
lists in python.
# Program to create, append, and remove elements in a list
# Creating a list
my_list = [10, 20, 30, 40]
print("Initial List:", my_list)
# Appending elements to the list
my_list.append(50)
my_list.append(60)
print("List after appending elements:", my_list)
# Removing specific elements from the list
my_list.remove(30)
print("List after removing 30:", my_list)
# Removing element by index using pop()
removed_element = my_list.pop(2) # Removes the element at index 2
print("Removed element using pop():", removed_element)
print("List after using pop():", my_list)
# Creating an empty list and adding elements dynamically
new_list = []
new_list.append("Apple")
new_list.append("Banana")
print("New List:", new_list)
# Deleting the entire list
del my_list
print("my_list deleted successfully!")
pg. 6
PYTHON PROGRAMMING FILE
OUTPUT:
Initial List: [10, 20, 30, 40]
List after appending elements: [10, 20, 30, 40, 50, 60]
List after removing 30: [10, 20, 40, 50, 60]
Removed element using pop(): 40
List after using pop(): [10, 20, 50, 60]
New List: ['Apple', 'Banana']
my_list deleted successfully!
pg. 7
PYTHON PROGRAMMING FILE
Task 6: Write a program to demonstrate working with
tuples in python.
# Program to demonstrate working with tuples in Python
# Creating a tuple
my_tuple = (10, 20, 30, 40, 50)
print("Tuple:", my_tuple)
# Accessing elements
print("First element:", my_tuple[0])
print("Last element:", my_tuple[-1])
# Slicing a tuple
print("Elements from index 1 to 3:", my_tuple[1:4])
# Length of tuple
print("Length of tuple:", len(my_tuple))
# Concatenation of tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5)
tuple3 = tuple1 + tuple2
print("Concatenated Tuple:", tuple3)
# Repetition of tuple
print("Repeated Tuple:", tuple1 * 2)
# Checking for an element
print("Is 20 in my_tuple?", 20 in my_tuple)
# Traversing through tuple
pg. 8
PYTHON PROGRAMMING FILE
print("Elements in my_tuple:")
for item in my_tuple:
print(item)
# Tuple with mixed data types
mixed_tuple = ("Apple", 3.14, 100, True)
print("Mixed Tuple:", mixed_tuple)
OUTPUT:
Tuple: (10, 20, 30, 40, 50)
First element: 10
Last element: 50
Elements from index 1 to 3: (20, 30, 40)
Length of tuple: 5
Concatenated Tuple: (1, 2, 3, 4, 5)
Repeated Tuple: (1, 2, 3, 1, 2, 3)
Is 20 in my_tuple? True
Elements in my_tuple:
10
20
30
40
50
Mixed Tuple: ('Apple', 3.14, 100, True)
pg. 9
PYTHON PROGRAMMING FILE
Task 7: Write a program to demonstrate working with
dictionaries in python.
# Program to demonstrate working with dictionaries in Python
# Creating a dictionary
student = {
"name": "Paras",
"age": 20,
"course": "AI & ML"
print("Initial Dictionary:", student)
# Accessing values
print("Name:", student["name"])
print("Course:", [Link]("course"))
# Adding a new key-value pair
student["college"] = "Tech University"
print("After adding new item:", student)
# Updating an existing key
student["age"] = 21
print("After updating age:", student)
# Removing an item using pop()
[Link]("course")
print("After removing 'course':", student)
# Removing the last inserted item using popitem()
[Link]()
print("After popitem():", student)
pg. 10
PYTHON PROGRAMMING FILE
# Traversing through dictionary
print("\nTraversing the dictionary:")
for key, value in [Link]():
print(key, ":", value)
# Checking if a key exists
if "name" in student:
print("\nKey 'name' exists in the dictionary.")
# Getting all keys and values
print("All Keys:", [Link]())
print("All Values:", [Link]())
OUTPUT:
Initial Dictionary: {'name': 'Paras', 'age': 20, 'course': 'AI & ML'}
Name: Paras
Course: AI & ML
After adding new item: {'name': 'Paras', 'age': 20, 'course': 'AI & ML', 'college': 'Tech University'}
After updating age: {'name': 'Paras', 'age': 21, 'course': 'AI & ML', 'college': 'Tech University'}
After removing 'course': {'name': 'Paras', 'age': 21, 'college': 'Tech University'}
After popitem(): {'name': 'Paras', 'age': 21'}
Traversing the dictionary:
name : Paras
age : 21
Key 'name' exists in the dictionary.
All Keys: dict_keys(['name', 'age'])
All Values: dict_values(['Paras', 21])
pg. 11
PYTHON PROGRAMMING FILE
Task 8: Write a python program to find largest of three
numbers.
# Program to find the largest of three numbers
# Taking three numbers as input from the user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
# Using if-elif-else to find the largest number
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
# Display the result
print("The largest number is:", largest)
OUTPUT:
Enter first number: 12
Enter second number: 45
Enter third number: 27
The largest number is: 45.0
pg. 12
PYTHON PROGRAMMING FILE
Task 9: Write a Python program to convert
temperatures to and from Celsius, Fahrenheit.
[ Formula: c/5 = f-32/9]
# Program to convert temperatures to and from Celsius and Fahrenheit
# Formula: c/5 = (f - 32)/9
print("Temperature Conversion Program")
print("1. Convert Celsius to Fahrenheit")
print("2. Convert Fahrenheit to Celsius")
# Taking user choice
choice = int(input("Enter your choice (1 or 2): "))
if choice == 1:
# Celsius to Fahrenheit
c = float(input("Enter temperature in Celsius: "))
f = (c * 9/5) + 32
print(f"{c}°C = {f}°F")
elif choice == 2:
# Fahrenheit to Celsius
f = float(input("Enter temperature in Fahrenheit: "))
c = (f - 32) * 5/9
print(f"{f}°F = {c}°C")
else:
print("Invalid choice! Please enter 1 or 2.")
OUTPUT:
Temperature Conversion Program
1. Convert Celsius to Fahrenheit
pg. 13
PYTHON PROGRAMMING FILE
2. Convert Fahrenheit to Celsius
Enter your choice (1 or 2): 1
Enter temperature in Celsius: 37
37.0°C = 98.6°F
pg. 14
PYTHON PROGRAMMING FILE
Task 10: Write a Python program to construct the
following pattern, using a nested for loop
*
**
***
****
***
**
*
# Program to print a star pattern
for i in range(1, 5):
print("* " * i)
for i in range(3, 0, -1):
print("* " * i)
OUTPUT:
*
**
***
****
***
**
pg. 15
PYTHON PROGRAMMING FILE
Task 11: Write a Python script that prints prime
numbers less than 20.
# Program to print prime numbers less than 20
print("Prime numbers less than 20 are:")
for num in range(2, 20): # numbers from 2 to 19
for i in range(2, num):
if num % i == 0:
break
else:
print(num)
OUTPUT:
Prime numbers less than 20 are:
11
13
17
19
pg. 16
PYTHON PROGRAMMING FILE
Task 12: Write a python program to find factorial of a
number using Recursion.
# Program to find factorial of a number using recursion
# Recursive function to find factorial
def factorial(n):
if n == 0 or n == 1: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive call
# Taking input from user
num = int(input("Enter a number: "))
# Checking if the number is negative
if num < 0:
print("Factorial does not exist for negative numbers.")
else:
print(f"The factorial of {num} is {factorial(num)}")
OUTPUT:
Enter a number: 5
The factorial of 5 is 120
pg. 17
PYTHON PROGRAMMING FILE
Task 13: Write a program that accepts the lengths of
three sides of a triangle as inputs. The program output
should indicate whether or not the triangle is a right
triangle (Recall from the Pythagorean Theorem that in a
right triangle, the square of one side equals the sum of
the squares of the other two sides).
# Program to check whether a triangle is a right triangle
# Taking input for sides of the triangle
a = float(input("Enter the length of first side: "))
b = float(input("Enter the length of second side: "))
c = float(input("Enter the length of third side: "))
# Find the largest side (hypotenuse)
sides = sorted([a, b, c]) # sorts sides in ascending order
x, y, z = sides # x and y are smaller sides, z is largest
# Check Pythagoras theorem: z² = x² + y²
if abs(z**2 - (x**2 + y**2)) < 1e-6: # small tolerance for float precision
print("The triangle is a RIGHT triangle.")
else:
print("The triangle is NOT a right triangle.")
OUTPUT:
Enter the length of first side: 3
Enter the length of second side: 4
Enter the length of third side: 5
The triangle is a RIGHT triangle.
pg. 18
PYTHON PROGRAMMING FILE
Task 14: Write a python program to define a module to
find Fibonacci Numbers and import the module to
another program.
# fibonacci_module.py
# This module contains a function to generate Fibonacci numbers
def fibonacci(n):
"""Return a list of Fibonacci numbers up to n terms."""
fib_series = []
a, b = 0, 1
for i in range(n):
fib_series.append(a)
a, b = b, a + b
return fib_series
OUTPUT:
Enter the number of terms for Fibonacci series: 8
Fibonacci series with 8 terms:
[0, 1, 1, 2, 3, 5, 8, 13]
pg. 19
PYTHON PROGRAMMING FILE
Task 15: Write a python program to define a module
and import a specific function in that module to another
program.
🧩 Step 1 — Create module file: my_module.py
# my_module.py
# Module containing math functions
def add(a, b):
return a + b
def subtract(a, b):
return a - b
🧮 Step 2 — Main program file: main_program.py
# main_program.py
# Importing a specific function from the module
from my_module import add # importing only 'add' function
# Taking user input
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
# Using imported function
result = add(x, y)
print(f"The sum of {x} and {y} is: {result}")
OUTPUT:
Enter first number: 10
Enter second number: 20
pg. 20
PYTHON PROGRAMMING FILE
The sum of 10 and 20 is: 30
Task 16: Write a script named [Link]. This script
should prompt the user for the names of two text files.
The contents of the first file should be input and written
to the second file.
# [Link]
# Program to copy contents from one text file to another
# Ask user for file names
source_file = input("Enter the name of the source file: ")
destination_file = input("Enter the name of the destination file: ")
try:
# Open source file in read mode
with open(source_file, 'r') as file1:
content = [Link]()
# Open destination file in write mode and copy content
with open(destination_file, 'w') as file2:
[Link](content)
print(f"\nContents of '{source_file}' have been copied to '{destination_file}' successfully!")
except FileNotFoundError:
print("\nError: The source file does not exist. Please check the file name and try again.")
except Exception as e:
print(f"\nAn error occurred: {e}")
OUTPUT:
Enter the name of the source file: [Link]
Enter the name of the destination file: [Link]
pg. 21
PYTHON PROGRAMMING FILE
Contents of '[Link]' have been copied to '[Link]' successfully!
pg. 22
PYTHON PROGRAMMING FILE
Task 17: Write a program that inputs a text file. The
program should print all of the unique words in the file
in alphabetical order.
# Program to print all unique words from a text file in alphabetical order
# Ask user for file name
file_name = input("Enter the name of the text file: ")
try:
# Open the file and read its contents
with open(file_name, 'r') as file:
text = [Link]()
# Split the text into words
words = [Link]()
# Convert to lowercase to avoid duplicates (like "The" and "the")
words = [[Link]() for word in words]
# Remove punctuation (optional improvement)
words = [[Link]('.,!?()[]{}":;') for word in words]
# Create a set for unique words
unique_words = set(words)
# Sort the words alphabetically
sorted_words = sorted(unique_words)
# Print each unique word
print("\nUnique words in alphabetical order:\n")
pg. 23
PYTHON PROGRAMMING FILE
for word in sorted_words:
print(word)
except FileNotFoundError:
print("\nError: The file does not exist. Please check the file name and try again.")
except Exception as e:
print(f"\nAn error occurred: {e}")
OUTPUT:
Unique words in alphabetical order:
hello
is
python
test
this
world
pg. 24
PYTHON PROGRAMMING FILE
Task 18: Write a Python class to convert an integer to a
roman numeral.
# Program to convert an integer to a Roman numeral using a class
class IntToRoman:
def __init__(self):
# Dictionary of Roman numerals and their integer values
[Link] = [
(1000, 'M'), (900, 'CM'),
(500, 'D'), (400, 'CD'),
(100, 'C'), (90, 'XC'),
(50, 'L'), (40, 'XL'),
(10, 'X'), (9, 'IX'),
(5, 'V'), (4, 'IV'),
(1, 'I')
def convert(self, num):
roman_num = ''
for (value, symbol) in [Link]:
while num >= value:
roman_num += symbol
num -= value
return roman_num
# --- Main Program ---
number = int(input("Enter an integer (1 - 3999): "))
converter = IntToRoman()
print(f"Roman numeral for {number} is: {[Link](number)}")
pg. 25
PYTHON PROGRAMMING FILE
OUTPUT:
Enter an integer (1 - 3999): 1999
Roman numeral for 1999 is: MCMXCIX
pg. 26
PYTHON PROGRAMMING FILE
Task 19: Write a Python class to implement pow(x, n)
# Program to implement power function pow(x, n) using a class
class Power:
def pow(self, x, n):
result = 1
for i in range(abs(n)):
result *= x
if n < 0:
return 1 / result
return result
# --- Main Program ---
x = float(input("Enter the base (x): "))
n = int(input("Enter the exponent (n): "))
p = Power()
print(f"{x} raised to the power {n} is: {[Link](x, n)}")
OUTPUT:
Enter the base (x): 2
Enter the exponent (n): 5
2.0 raised to the power 5 is: 32.0
pg. 27
PYTHON PROGRAMMING FILE
Task 20: Write a Python class to reverse a string word
by word.
# Program to reverse a string word by word using a class
class StringReverser:
def reverse_words(self, sentence):
# Split the sentence into words
words = [Link]()
# Reverse the list of words
reversed_words = words[::-1]
# Join them back into a single string
return ' '.join(reversed_words)
# --- Main Program ---
text = input("Enter a sentence: ")
reverser = StringReverser()
print("Reversed sentence (word by word):", reverser.reverse_words(text))
OUTPUT:
Enter a sentence: Python is very easy
Reversed sentence (word by word): easy very is Python
pg. 28