COMPUTER PROGRAMMING
PRACTILE FILE
NETAJI SUBHASH UNIVERSITY OF TECHNOLOGY
SESSION- 2025-26
NAME:Janmajay Sharma
ROLL NO:2024UCD2122
BRANCH:CSDS
SUBMITTED TO:[Link]
TASK-1 Install Python and set up the development environment.
A. Write a Python program to print "Hello, World!"
B. Write a Python program to calculate the area of a circle given the radius.
TASK-2
A. Write a Python program to check if a number is even or odd.
B. Implement a simple calculator using conditional statements.
C. Write a Python program to print the Fibonacci series using a for loop.
TASK-3
A. Implement a function to check if a given string is a palindrome.
B. Perform various operations on lists (e.g., sorting, slicing).
C. Use dictionaries to store and retrieve student grades.
TASK-4
A. Create a class to represent a book with attributes and methods.
B. Implement inheritance by creating subclasses for different types of books.
C. Write a generator function to generate the Fibonacci series.
TASK-5
A. Use lambda functions, map, and lter to perform operations on a list.
B. Create a module that contains functions for mathematical operations.
C. Import and use functions from external packages (e.g., math, random).
TASK-6
A. Create and manipulate NumPy arrays.
fi
B. Perform basic operations and indexing on arrays.
Steps to install python :
1. Go to the Official Python
Website:
Open your browser and
go to: https://
[Link].
Then click on the
“Downloads” tab.
2. Download Python Installer for Windows
The website automatically shows a download button for your operating system.
👉 Click the "Download Python 3.x.x" button (you’ll see the latest version, e.g.,
Python 3.12.2).
3. Run the Installer
Once the .exe file is downloaded, double-click it to run the installer. Before
clicking “Install Now”:✅ Check the box that says:✔ "Add Python 3.x to PATH"
Then click "Install Now”
4. Step 4: Installation Progress
You’ll see the installation progress bar. It takes a minute or two.
5. Step 5: Installation Successful
Once it’s done, you’ll see a screen that says:✔ Setup was successful
Click “Close” to finish.
6. Step 6: Verify the Installation
Open Command Prompt: Press Windows + R, type cmd, and hit Enter.
Then type:
TASK-1 Install Python and set up the development environment.; Write a Python program to
print "Hello, World!”;
Write a Python program to calculate the area of a circle given the radius.
1)Write a Python program to print "Hello, World!”
INPUT:
print(“hello world”)
OUTPUT:
2)Write a Python program to calculate the area of a circle given the radius.
INPUT:
from math import *
radius=eval(input("Enter the radius of circle:"))
area=pi*(radius**2)
print("Area of the given circle :",area,"sq. units”)
OUTPUT:
TASK-2 Write a Python program to check if a number is even or odd.; Implement a simple
calculator using conditional statements; Write a Python program to print the Fibonacci series
using a for loop.
A) Write a Python program to check if a number is even or odd.
INPUT:
num=eval(input("Enter the number:"))
#conditions
if num%2==0: #condition to check even
print("The given number is even!!")
else:
print("The given number is odd!!”)
OUTPUT:
B) Implement a simple calculator using conditional statements
INPUT:
#simple calculator
numl=int(input("Enter the number :"))
num2=int(input("Enter the number :"))
operator=input("Enter the operator:")
if operator=="+":
print("Result:",numl+num2)
elif operator=="-":
print("Result:", numl-num2)
elif operator=="*":
print("Result:", numl*num2)
elif operator=="/":
print("Result:",numl/num2)
else:
print("OPERATOR NOT RECOGNIZED”)
OUTPUT:
C) Write a Python program to print the Fibonacci series using a for loop.
INPUT:
#Fibonacci series
n= int(input("How many Fibonacci numbers do you want? "))
a, b = 0, 1
if n > 0:
print("Fibonacci series:")
for i in range(n):
print(a, end=" ")
a, b = b, a + b
print( )
OUTPUT:
TASK-3 Implement a function to check if a given string is a palindrome.; Perform
various operations on lists (e.g., sorting, slicing).; Use dictionaries to store and
retrieve student grades.
A) Implement a function to check if a given string is a palindrome.
INPUT:
#PALINDROME ANALYSIS
s1 = input("Enter a string: ")
l1 = len(s1)
s2 = s1[::-1]
if s1 == s2:
print("Given string is a palindrome!!!")
else:
print("Given string is not a palindrome!!!")
OUTPUT:
B) Perform various operations on lists (e.g., sorting, slicing)
INPUT:
# List Operations in Python
# 1. Create lists
numbers = [5, 2, 9, 1, 7]
fruits = ["apple", "banana", "cherry",
"mango"]
print("Original numbers:", numbers)
print("Original fruits:", fruits)
# 2. Sorting
[Link]()
print("\nSorted (ascending):", numbers)
[Link](reverse=True)
print("Sorted (descending):", numbers)
sorted_numbers = sorted(numbers)
print("Sorted copy (ascending):",
sorted_numbers)
print("Original after sorted():", numbers)
# 3. Slicing
print("\nSlice fruits[1:3]:", fruits[1:3])
print("Slice fruits[:2]:", fruits[:2])
print("Slice fruits[2:]:", fruits[2:])
print("Last two fruits:", fruits[-2:])
# 4. Adding items
[Link]("orange")
print("\nAfter append:", fruits)
[Link](1, "grape")
print("After insert at index 1:", fruits)
# 5. Removing items
[Link]("banana")
print("After remove banana:", fruits)
popped_item = [Link]()
print("Popped item:", popped_item)
print("After pop:", fruits)
C) Use dictionaries to store and retrieve student grades.
INPUT :
# Use dictionaries to store and retrieve student grades.
d1={}
n=int(input("Enter the number of pairs:"))
for i in range(n):
name=input("Enter the name of student:")
grade=input("Enter the grade:")
d1[name]=grade
print("Dictionary:",d1)
search=input("Enter the name to be retreived:")
l1=[Link]()
for i in d1:
if i==search:
print(“GRADE=",d1[i])
OUTPUT:
TASK-4: Create a class to represent a book with attributes and methods.;
Implement inheritance by creating subclasses for different types of books.;
Write a generator function to generate the Fibonacci series.
A) Create a class to represent a book with attributes and methods
INPUT:
class Book:
def __init__(self, title, author, pages, price):
# Attributes
[Link] = title
[Link] = author
[Link] = pages
[Link] = price
# Method to display book details
def display_info(self):
print(f"Title: {[Link]}")
print(f"Author: {[Link]}")
print(f"Pages: {[Link]}")
print(f"Price: ₹{[Link]}")
# Method to apply discount
def apply_discount(self, percentage):
discount_amount = [Link] * (percentage / 100)
[Link] -= discount_amount
print(f"Discount applied! New price: ₹{[Link]}")
# Example usage
my_book = Book("Python Basics", "PREETI ARORA", 250, 499)
my_book.display_info() # Show details
my_book.apply_discount(10) # Apply 10% discount
my_book.display_info() # Show updated details
OUTPUT:
B) Implement inheritance by creating subclasses for different types of books.
INPUT:
class Book:
def __init__(self, title, author, pages, price):
[Link] = title
[Link] = author
[Link] = pages
[Link] = price
def display_info(self):
print(f"{[Link]} by {[Link]}, {[Link]} pages, ₹{[Link]}")
def apply_discount(self, pct):
[Link] -= [Link] * pct / 100
class FictionBook(Book):
def __init__(self, title, author, pages, price, genre):
super().__init__(title, author, pages, price)
[Link] = genre
def display_info(self):
super().display_info()
print(f"Genre: {[Link]}")
class TextBook(Book):
def __init__(self, title, author, pages, price, subject, grade):
super().__init__(title, author, pages, price)
[Link] = subject
[Link] = grade
def display_info(self):
super().display_info()
print(f"{[Link]} for {[Link]}")
# Example usage
f = FictionBook("LORD OF THE RINGS", "J.R.R. TOLKIEN", 180, 350,
"Classic")
t = TextBook("Mathematics", "R.D. Sharma", 500, 750, "Math", "10th
Grade")
f.display_info()
f.apply_discount(15)
print("After discount:")
f.display_info()
print()
t.display_info()
t.apply_discount(20)
print("After discount:")
t.display_info()
OUTPUT:
C) Write a generator function to generate the Fibonacci series.
INPUT:
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a # yield sends value out without ending the function
a, b = b, a + b
# Example usage
a = int(input("Enter range: "))
for num in fibonacci(a):
print(num, end=" ")
OUTPUT:
TASK-5 Use lambda functions, map, and filter to perform operations on a list.;
Create a module that contains functions for mathematical operations.; Import
and use functions from external packages (e.g., math, random).
A) Use lambda functions, map, and filter to perform operations on a list
INPUT:
# Sample list
numbers = []
n = int(input("Enter the number of elements: "))
for i in range(n):
entry = int(input("Enter the number: "))
[Link](entry)
# Square each number (map + lambda)
squares = list(map(lambda x: x**2, numbers))
# Filter even numbers (filter + lambda)
evens = list(filter(lambda x: x % 2 == 0, numbers))
# Double the even numbers (map + filter + lambda)
doubled_evens = list(map(lambda x: x * 2, filter(lambda x: x % 2 == 0,
numbers)))
print("Original:", numbers)
print("Squares:", squares)
print("Evens:", evens)
print("Doubled Evens:", doubled_evens)
OUTPUT:
B) Create a module that contains functions for mathematical operations
# maths_jj.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
else:
raise ValueError("Division by zero is not allowed.")
def power(a, b):
return a ** b
def factorial(n):
if n < 0:
raise ValueError("Factorial is not defined for negative numbers.")
return 1 if n == 0 else n * factorial(n - 1)
INPUT:
from maths_jj import *
print("Add:", add(5, 3))
print("Subtract:", subtract(10, 4))
print("Multiply:", multiply(6, 7))
print("Divide:", divide(8, 2))
print("Power:", power(2, 5))
print("Factorial:", factorial(5))
OUTPUT:
C) Import and use functions from external packages (e.g., math, random).
INPUT:
# Importing specific functions from external packages
import math
import random
# Using math module
num = int(input("Enter a number:"))
sqrt_value = [Link](num) # Square root
pi_value = [Link] # Value of pi
factorial_value = [Link](num) # Factorial
# Using random module
random_number = [Link](1, 10) # Random integer between 1
and 10
random_float = [Link]()# Random float between 0.0 and 1.0
fruits=["Apple", "Banana", "Cherry"]
choice_value = [Link](fruits) # Random choice from a list
# Displaying results
print(f"Square root of {num}:", sqrt_value)
print("Value of pi:", pi_value)
print("Factorial of 5:", factorial_value)
print("Random integer (1-10):", random_number)
print("Random float (0-1):", random_float)
print("Random fruit:", choice_value)
OUTPUT:
TASK-6 Create and manipulate NumPy arrays.; Perform basic operations and
indexing on arrays.
A) Create and manipulate NumPy arrays.
INPUT:
import numpy as np
# 1. Creating NumPy arrays
arr1 = [Link]([1, 2, 3, 4, 5]) # 1D array
arr2 = [Link]([[1, 2, 3], [4, 5, 6]]) # 2D array
# 2. Creating arrays with special values
zeros_arr = [Link]((2, 3)) # 2x3 array of zeros
ones_arr = [Link]((3, 3)) # 3x3 array of ones
range_arr = [Link](0, 10, 2) # Values from 0 to 8, step 2
linspace_arr = [Link](0, 1, 5) # 5 values evenly spaced between 0 and
1
# 3. Array operations
sum_arr = arr1 + 10 # Add scalar to array
product_arr = arr1 * 2 # Multiply array by scalar
elementwise_sum = arr1 + [Link]([10, 20, 30, 40, 50]) # Element-wise
addition
square_arr = arr1 ** 2 # Square each element
# 4. Array properties
print("arr1 shape:", [Link])
print("arr2 dimensions:", [Link])
print("arr1 data type:", [Link])
# 5. Indexing and slicing
print("First element of arr1:", arr1[0])
print("Last two elements of arr1:", arr1[-2:])
print("First row of arr2:", arr2[0])
print("Second column of arr2:", arr2[:, 1])
# 6. Boolean indexing
greater_than_two = arr1[arr1 > 2]
print("Elements greater than 2:", greater_than_two)
# 7. Output arrays
print("Original arr1:", arr1)
print("Zeros array:\n", zeros_arr)
print("Ones array:\n", ones_arr)
print("Range array:", range_arr)
print("Linspace array:", linspace_arr)
print("Sum array:", sum_arr)
print("Product array:", product_arr)
print("Element-wise sum:", elementwise_sum)
print("Squared array:", square_arr)
OUTPUT:
B) Perform basic operations and indexing on arrays.
INPUT:
import numpy as np
# Create an array
arr = [Link]([10, 20, 30, 40, 50])
# ===== Basic Operations =====
print("Original array:", arr)
# Arithmetic operations
print("Add 5:", arr + 5) # Add scalar
print("Multiply by 2:", arr * 2) # Multiply scalar
print("Square each element:", arr ** 2) # Power
print("Sum of all elements:", [Link]()) # Total sum
print("Mean value:", [Link]()) # Average
# Element-wise operations
arr2 = [Link]([1, 2, 3, 4, 5])
print("Element-wise addition:", arr + arr2)
print("Element-wise multiplication:", arr * arr2)
# ===== Indexing & Slicing =====
print("First element:", arr[0]) # Index 0
print("Last element:", arr[-1]) # Negative index
print("First three elements:", arr[:3]) # Slice
print("Elements from index 2 to 4:", arr[2:5])
print("Every second element:", arr[::2])
# ===== Boolean Indexing =====
print("Elements greater than 25:", arr[arr > 25])
# ===== Modifying array elements =====
arr[0] = 99
arr[1:3] = [77, 88]
print("Modified array:", arr)
OUTPUT: