Python Lab - Programs
Python Lab - Programs
Arithmetic Operators:
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulus (%)
Exponentiation (**)
a = 10
b=3
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)
Comparison Operators:
Equal to (==)
1
x=5
y = 10
print("Equal to:", x == y)
Logical Operators:
Logical OR (or)
p = True
q = False
print("Logical OR:", p or q)
2
Assignment Operators:
Assignment (=)
x=5
x += 3 # Equivalent to x = x + 3
print("Addition assignment:", x)
x -= 2 # Equivalent to x = x - 2
print("Subtraction assignment:", x)
x *= 4 # Equivalent to x = x * 4
print("Multiplication assignment:", x)
x /= 2 # Equivalent to x = x / 2
print("Division assignment:", x)
Bitwise Operators:
Bitwise OR (|)
3
a = 10 # Binary: 1010
b = 5 # Binary: 0101
num = 10
if num > 0:
print("Number is positive")
elif num == 0:
print("Number is zero")
else:
print("Number is negative")
4
Iterative Statements with for loop:
print(fruit)
count = 0
print("Count:", count)
count += 1
# define string
substring = "is"
count = string.count(substring)
# print count
5
Example Using Replace():
# Define a string
print(sentence)
# Define a string
uppercase_string = original_string.upper()
6
Example using Lower():
# Define a string
lowercase_string = original_string.lower()
capitalized_string = sentence.capitalize()
import os
print(file.read())
file.close()
7
#Read the first 7 characters of my file
import os
print(file.read(7))
file.close()
import os
print(file.readline())1
file.close()
import os
print(file.readlines())
file.close()
#Write function
import os
file.write("Sunday")
file.write("Monday")
file.close()
8
#Remove a file
import os
os.remove("C:\pdapython\operations4.txt")
#create a file
import os
file.write("sunshine")
file.close()
list1.reverse()
print(list1)
print(list3)
numbers = [1, 2, 3, 4, 5, 6, 7]
# result list
res = []
for i in numbers:
9
res.append(i * i)
print(res)
print(x, y)
print(res)
Write a program to extend it by adding the sublist ["h", "i", "j"] in such a way that
it will look like the following list.
list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
# understand indexing
# solution
10
list1[2][1][2].extend(sub_list)
print(list1)
tuple1 = tuple1[::-1]
print(tuple1)
print(tuple1[1][1])
tuple1= (50, )
print(tuple1)
Write a program to unpack the following tuple into four variables and display each
variable.
a, b, c, d = tuple1
print(a)
print(b)
print(c)
print(d)
11
tuple1 = (11, 22)
print(tuple2)
print(tuple1)
Write a program to copy elements 44 and 55 from the following tuple into a new
tuple.
tuple2 = tuple1[3:-1]
print(tuple2)
print(tuple1)
sample_set.update(sample_list)
print(sample_set)
write a program to Return a new set of identical items from two set
12
set2 =set1 = {10, 20, 30, 40, 50}
print(set1.intersection(set2))
write a program to Updqate the first set with items that don’t exist in the second set
set1.difference_update(set2)
print(set1)
write a program to Check if two sets have any elements in common. If yes, display
the common elements
if set1.isdisjoint(set2):
else:
print(set1.intersection(set2)
write a program to Update set1 by adding items from set2, except common items
set1.symmetric_difference_update(set2)
print(set1)
13
write a program to Remove items from set1 that are not common to both set1 and
set2
set1.intersection_update(set2)
print(set1)
print(res_dict)
print(dict3)
print(res)
#Individual data
14
print(res["Kelly"])
sampleDict = {
"name": "Kelly",
"age":25,
"salary": 8000,
print(newDict)
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
# Keys to remove
for k in keys:
sample_dict.pop(k)
print(sample_dict)
15
sample_dict = {
sample_dict['emp3']['salary'] = 8500
print(sample_dict)
Positional Parameters:
print(f"{greeting}, {name}!")
greet("Alice", "Hello")
Default Parameters:
print(f"{greeting}, {name}!")
# Calling the function with and without providing the default parameter
16
Variable-Length Positional Parameters (args):
def greet(*names):
print(f"Hello, {name}!")
Keyword Parameters:
print(f"{greeting}, {name}!")
greet(name="David", greeting="Hi")
def greet(**kwargs):
print(f"{key}: {value}")
10. Demonstrate creation and use of Functions in python with all kinds of
“parameters” used with functions
17
import time
import random
# Bubble Sort
def bubble_sort(arr):
n = len(arr)
for i in range(n):
# Merge Sort
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i=j=k=0
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
18
j += 1
k += 1
arr[k] = L[i]
i += 1
k += 1
arr[k] = R[j]
j += 1
k += 1
# Quick Sort
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
start_time = time.time()
19
bubble_sort(random_list.copy())
start_time = time.time()
merge_sort(random_list.copy())
start_time = time.time()
quick_sort(random_list.copy())
Creating Objects:
# Define a class
class Person:
# Constructor
self.name = name
self.age = age
def display_info(self):
20
print(f"Name: {self.name}, Age: {self.age}")
person1.display_info()
Inheritance:
class Animal:
self.name = name
def speak(self):
class Dog(Animal):
def speak(self):
class Cat(Animal):
def speak(self):
dog = Dog("Buddy")
cat = Cat("Whiskers")
21
print(dog.speak()) # Output: Buddy says Woof!
import numpy as np
# Creating arrays
# Array Operations
print("Array Operations:")
print()
# Mathematical Functions
print("Mathematical Functions:")
22
print("Sine of arr1:", np.sin(arr1)) # Sine of array elements
print()
# Sorting
print("Sorting:")
print()
# Searching
print("Searching:")
print("Array:", arr5)
print()
# Counting
print("Counting:")
print("Array:", arr6)
23
count = np.count_nonzero(arr6 == unique_val) # Count occurrences of each unique
element
Array Operations: Basic operations like sum, mean, max, min, and dot product.
Counting: Counting unique elements and occurrences of each unique element in an array.
These functionalities make NumPy a powerful library for array manipulation and
mathematical operations in Python.
plt.plot(xpoints, ypoints)
plt.show()
24
import numpy as np
import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.plot(x, y)
plt.grid()
plt.show()
iv)Draw 2 plots
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
25
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.show()
v) Draw 4 bars
plt.bar(x,y)
plt.show()
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
plt.show()
plt.pie(y)
plt.show()
26
Using the Pyplot API to create plots.
Creating different types of plots such as line plots, scatter plots, and histograms.
Performing I/O operations with NumPy arrays, saving and loading data to/from files
using NumPy's functions.
Matplotlib is a versatile library for creating static, animated, and interactive visualizations
in Python, making it an essential tool for data analysis and exploration.
27