Submitted to: Submitted by:
Dr. Sudhanshu Gaur Kunal
Department of CSE 220010130100
B.Tech CSE(Batch-2)
How to install python and IDE
Installing Python
1. **Download Python**:
- Go to the [official Python website](https://www.python.org/downloads/)¹.
- Click on the download button for the latest version of Python.
2. **Run the Installer**:
- Open the downloaded file to start the installation process.
- Make sure to check the box that says **"Add Python to PATH"** before clicking "Install
Now"¹¹.
3. **Verify the Installation**:
- Open Command Prompt and type `python --version` to check if Python is installed correctly.
Installing an IDE
There are several IDEs you can choose from. Here are a few popular ones:
**PyCharm**:
1. **Download PyCharm**:
- Visit the [PyCharm website](https://www.jetbrains.com/pycharm/download/).
- Download the Community edition (free) or Professional edition (paid).
2. **Run the Installer**:
- Open the downloaded file and follow the installation instructions.
**Visual Studio Code**:
1. **Download VS Code**:
- Go to the [Visual Studio Code website](https://code.visualstudio.com/Download).
- Download the installer for your operating system.
2. **Install Python Extension**:
- Open VS Code, go to the Extensions view by clicking on the Extensions icon in the Activity
Bar on the side of the window.
- Search for "Python" and install the official Python extension by Microsoft.
Program 1 :Assignments to perform various number operations
1) Find maximum from a list of numbers:
print(“Kunal 220010130100”)
numbers = [10, 5, 7, 12, 3]
maximum = max(numbers)
print("The maximum number is: {maximum}")
2) GCD of two numbers:
print(“Kunal 220010130100”)
import math
a = 60
b = 48
gcd = math.gcd(a, b)
print(f"The GCD of {a} and {b} is: {gcd}")
3) Square Root of a Number
print(“Kunal 220010130100”)
import math
num = 16
sqrt = math.sqrt(num)
print(f"The square root of {num} is: {sqrt}")
4) Check number is prime or not:
print(“Kunal 220010130100”)
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
num = 29
print(f"{num} is a prime number: {is_prime(num)}")
5) Print First N prime Numbers:
print(“Kunal 220010130100”)
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def print_first_n_primes(n):
count = 0
num = 2
while count < n:
if is_prime(num):
print(num, end=" ")
count += 1
num += 1
n = 10
print_first_n_primes(n)
6) Remove duplicate numbers from list:
print(“Kunal 220010130100”)
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(f"List after removing duplicates: {unique_numbers}")
7) Print the Fibonacci series:
print(“Kunal 220010130100”)
def fibonacci(n):
fib_series = [0, 1]
while len(fib_series) < n:
fib_series.append(fib_series[-1] + fib_series[-2])
return fib_series
n = 10
print(f"First {n} Fibonacci numbers: {fibonacci(n)}")
Program 2:- Program to perform operations on Strings like
creation, deletion , concatenation:
print(“Kunal 220010130100”)
# String Creation
string1 = "Hello"
string2 = 'World'
print("String 1:", string1)
print("String 2:", string2)
# String Concatenation
concatenated_string = string1 + ", " + string2 + "!"
print("Concatenated String:", concatenated_string)
# String Slicing
sliced_string = concatenated_string[7:12]
print("Sliced String:", sliced_string)
# String Replacement
replaced_string = concatenated_string.replace("World", "Python")
print("Replaced String:", replaced_string)
# String Formatting
name = "Alice"
age = 25
formatted_string = f"My name is {name} and I am {age} years old."
print("Formatted String:", formatted_string)
# String Deletion
del string1
# Uppercase and Lowercase
uppercase_string = concatenated_string.upper()
lowercase_string = concatenated_string.lower()
print("Uppercase String:", uppercase_string)
print("Lowercase String:", lowercase_string)
Program 3:- Create a List L = [10,20,30].Write programs to
perform following operations:
a) Insert new numbers to list L
b) Delete numbers from list L
c) Sum all numbers in list L
d) Sum all prime numbers in list L
e) Delete the list L
print(“Kunal 220010130100”)
# Initial list
L = [10, 20, 30]
# a) Insert new numbers to list L
L.append(40)
L.append(50)
print("List after insertion:", L)
# b) Delete numbers from list L
L.remove(20) # Remove specific number
print("List after deletion:", L)
# c) Sum all numbers in list L
sum_all = sum(L)
print("Sum of all numbers:", sum_all)
# d) Sum all prime numbers in list L
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
sum_primes = sum(filter(is_prime, L))
print("Sum of all prime numbers:", sum_primes)
# e) Delete the list L
del L
Program 4:- Create a Dictionary D ={‘Name’:’Allen , ’Age’:27,
5:123456}.Write programs to perform following operations :
A. Insert new entry in D
B. Delete an entry from D
C. Check whether a key present in D
D. Update the value of a key
E. Clear Dictionary D
print(“Kunal 220010130100”)
# Initial dictionary
D = {'Name': 'Allen', 'Age': 27, 5: 123456}
# A. Insert new entry in D
D['Address'] = '123 Main St'
print("Dictionary after insertion:", D)
# B. Delete an entry from D
del D[5]
print("Dictionary after deletion:", D)
# C. Check whether a key is present in D
key_to_check = 'Age'
is_present = key_to_check in D
print(f"Is '{key_to_check}' present in the dictionary?: {is_present}")
# D. Update the value of a key
D['Age'] = 28
print("Dictionary after updating 'Age':", D)
# E. Clear Dictionary D
D.clear()
print("Dictionary after clearing:", D)
Program 5:- Program on Sets to perform various operation like
union ,intersection ,difference etc.
# Creating sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(“Kunal 220010130100”)
print("Set 1:", set1)
print("Set 2:", set2)
# Adding elements to a set
set1.add(6)
print("Set 1 after adding an element:", set1)
# Removing elements from a set
set1.remove(6)
print("Set 1 after removing an element:", set1)
# Union of sets
union_set = set1.union(set2)
print("Union of Set 1 and Set 2:", union_set)
# Intersection of sets
intersection_set = set1.intersection(set2)
print("Intersection of Set 1 and Set 2:", intersection_set)
# Difference of sets
difference_set = set1.difference(set2)
print("Difference of Set 1 and Set 2:", difference_set)
# Symmetric difference of sets
symmetric_difference_set = set1.symmetric_difference(set2)
print("Symmetric Difference of Set 1 and Set 2:", symmetric_difference_set)
# Checking membership
print("Is 3 in Set 1?", 3 in set1)
print("Is 10 in Set 2?", 10 in set2)
# Clearing a set
set1.clear()
print("Set 1 after clearing:", set1)
Program 6: - Program to perform Linear search and Binary search
Linear Search
print(“Kunal 220010130100”)
def linear_search(arr, target):
for index, element in enumerate(arr):
if element == target:
return index
return -1
arr = [4, 2, 7, 1, 9, 3]
target = 7
index = linear_search(arr, target)
if index != -1:
print(f"Element {target} found at index {index}")
else:
print(f"Element {target} not found in the array")
Binary Search
print(“Kunal 220010130100”)
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
arr = [1, 2, 3, 4, 7, 9]
target = 7
index = binary_search(arr, target)
if index != -1:
print(f"Element {target} found at index {index}")
else:
print(f"Element {target} not found in the array")
Program7:- Program to perform selection sort,
bubble sort and insertion sort
Selection sort
print(“Kunal 220010130100”)
def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
# Example usage
arr = [64, 25, 12, 22, 11]
print("Selection Sort:", selection_sort(arr))
Bubble sort
print(“Kunal 220010130100”)
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
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
print("Bubble Sort:", bubble_sort(arr))
Insertion sort
print(“Kunal 220010130100”)
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
# Example usage
arr = [12, 11, 13, 5, 6]
print("Insertion Sort:", insertion_sort(arr))
Program 8:-Demonstrate the use of dictionary for measuring
students marks in five subjects. Also find the student
having maximum and minimum average marks
print(“Kunal 220010130100”)
# Dictionary to store students' marks
students_marks = { 'Alice': {'Math': 85, 'Science': 92, 'English': 78, 'History': 88, 'Geography': 90},
'Bob': {'Math': 75, 'Science': 85, 'English': 80, 'History': 70, 'Geography': 75},
'Charlie': {'Math': 95, 'Science': 90, 'English': 85, 'History': 95, 'Geography': 100},
'David': {'Math': 65, 'Science': 70, 'English': 60, 'History': 55, 'Geography': 60},
'Eve': {'Math': 88, 'Science': 82, 'English': 90, 'History': 85, 'Geography': 87}}
# Function to calculate average marks
def calculate_average(marks):
return sum(marks.values()) / len(marks)
# Calculate average marks for each student
average_marks = {student: calculate_average(marks) for student, marks in
students_marks.items()}
# Find the student with maximum and minimum average marks
max_avg_student = max(average_marks, key=average_marks.get)
min_avg_student = min(average_marks, key=average_marks.get)
print(f"Student with maximum average marks: {max_avg_student}
({average_marks[max_avg_student]:.2f})")
print(f"Student with minimum average marks: {min_avg_student}
({average_marks[min_avg_student]:.2f})")
Program 9:- Programs to perform usage of Random package
Print N random numbers ranging from 50 to 250
import random
print(“Kunal 220010130100”)
def generate_random_numbers(N, lower_bound=50, upper_bound=250):
random_numbers = [random.randint(lower_bound, upper_bound) for _ in range(N)]
return random_numbers
# Example usage
N = 10
random_numbers = generate_random_numbers(N)
print(f"{N} random numbers between 50 and 250: {random_numbers}")
Print 10 random strings whose length between 2 and 7
import random
import string
print(“Kunal 220010130100”)
def generate_random_string(length):
letters = string.ascii_letters
return ''.join(random.choice(letters) for _ in range(length))
def generate_random_strings(n, min_length, max_length):
random_strings = [generate_random_string(random.randint(min_length, max_length)) for _ in
range(n)]
return random_strings
# Example usage
n = 10
min_length = 2
max_length = 7
random_strings = generate_random_strings(n, min_length, max_length)
print("Random strings:", random_strings)
Program 10:- Program on usage of packages : Numpy and
Pandas
import numpy as np
import pandas as pd
print(“Kunal 220010130100”)
# Using NumPy to create an array
array = np.array([1, 2, 3, 4, 5])
print("NumPy Array:")
print(array)
# Performing basic operations with NumPy
array_sum = np.sum(array)
array_mean = np.mean(array)
print("\nSum of NumPy Array:", array_sum)
print("Mean of NumPy Array:", array_mean)
# Using Pandas to create a DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'Age': [24, 27, 22, 32, 29],
'Score': [85, 90, 78, 88, 92]}
df = pd.DataFrame(data)
print("\nPandas DataFrame:")
print(df)
# Performing basic operations with Pandas
mean_age = df['Age'].mean()
max_score = df['Score'].max()
print("\nMean Age:", mean_age)
print("Max Score:", max_score)
Program 11:- Implement and Demonstrate the functions of a
simple calculator
print(“Kunal 220010130100”)
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Error! Division by zero."
return x / y
def calculator():
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
while True:
choice = input("Enter choice (1/2/3/4): ")
if choice in ['1', '2', '3', '4']:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}")
elif choice == '2':
print(f"{num1} - {num2} = {subtract(num1, num2)}")
elif choice == '3':
print(f"{num1} * {num2} = {multiply(num1, num2)}")
elif choice == '4':
print(f"{num1} / {num2} = {divide(num1, num2)}")
next_calculation = input("Do you want to perform another calculation? (yes/no): ")
if next_calculation.lower() != 'yes':
break
else:
print("Invalid Input")
calculator()
Program 12:- Program to implement object
oriented concept :classes, inheritance, and polymorphism
print(“Kunal 220010130100”)
# Base class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement abstract method")
# Derived class 1
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
# Derived class 2
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
# Derived class 3
class Cow(Animal):
def speak(self):
return f"{self.name} says Moo!"
# Function to demonstrate polymorphism
def animal_sound(animal):
print(animal.speak())
# Creating objects of derived classes
dog = Dog("Buddy")
cat = Cat("Whiskers")
cow = Cow("Bessie")
# Demonstrating polymorphism
animal_sound(dog)
animal_sound(cat)
animal_sound(cow)
Program13: Program to implement file handling
print(“Kunal 220010130100”)
# Creating and writing to a file
with open('example.txt', 'w') as file:
file.write("Hello, this is a test file.\n")
file.write("This file is used to demonstrate file handling in Python.\n")
print("File created and written successfully.")
# Reading from a file
with open('example.txt', 'r') as file:
content = file.read()
print("\nContent of the file:")
print(content)
# Appending to a file
with open('example.txt', 'a') as file:
file.write("Appending a new line to the file.\n")
print("New line appended successfully.")
# Reading the updated file
with open('example.txt', 'r') as file:
updated_content = file.read()
print("\nUpdated content of the file:")
print(updated_content)
# Deleting the file
import os
os.remove('example.txt')
print("File deleted successfully.")