Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
54 views

Python Lab - Programs

The document demonstrates various operators, control structures, and data structures in Python including arithmetic, comparison, logical, assignment, and bitwise operators as well as if/else statements, for and while loops, strings, lists, tuples, sets, and dictionaries. A variety of methods are shown for each data structure type including creation, accessing/updating elements, sorting, and more.

Uploaded by

pdacollege9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

Python Lab - Programs

The document demonstrates various operators, control structures, and data structures in Python including arithmetic, comparison, logical, assignment, and bitwise operators as well as if/else statements, for and while loops, strings, lists, tuples, sets, and dictionaries. A variety of methods are shown for each data structure type including creation, accessing/updating elements, sorting, and more.

Uploaded by

pdacollege9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

1 - Demonstrate the working of all kinds of operators.

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 (==)

Not equal to (!=)

Greater than (>)

Less than (<)

Greater than or equal to (>=)

Less than or equal to (<=)

1
x=5

y = 10

print("Equal to:", x == y)

print("Not equal to:", x != y)

print("Greater than:", x > y)

print("Less than:", x < y)

print("Greater than or equal to:", x >= y)

print("Less than or equal to:", x <= y)

Logical Operators:

Logical AND (and)

Logical OR (or)

Logical NOT (not)

p = True

q = False

print("Logical AND:", p and q)

print("Logical OR:", p or q)

print("Logical NOT:", not p)

2
Assignment Operators:

Assignment (=)

Addition assignment (+=)

Subtraction assignment (-=)

Multiplication assignment (*=)

Division 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 AND (&)

Bitwise OR (|)

Bitwise XOR (^)

Bitwise NOT (~)

Left shift (<<)

Right shift (>>)

3
a = 10 # Binary: 1010

b = 5 # Binary: 0101

print("Bitwise AND:", a & b) # Result: 0000

print("Bitwise OR:", a | b) # Result: 1111

print("Bitwise XOR:", a ^ b) # Result: 1111

print("Bitwise NOT of a:", ~a) # Result: -11

print("Left shift of a by 1:", a << 1) # Result: 10100

print("Right shift of a by 1:", a >> 1) # Result: 0101

2 - Demonstrate the decision making and Iterative statements in Python

i) “if” and its variants ii) while and for loops.

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:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:

print(fruit)

Iterative Statements with while loop:

count = 0

while count < 5:

print("Count:", count)

count += 1

3 - Demonstrate the use of various string functions like count (),

Replace () join (), upper(), lower (), capitalize ()

Example Count () : Count number of occurrences of a given substring

# define string

string = "Python is awesome, isn't it?"

substring = "is"

count = string.count(substring)

# print count

print("The count is:", count)

5
Example Using Replace():

# Define a string

original_string = "Hello, World! Hello, Python!"

# Replace all occurrences of "Hello" with "Hi"

new_string = original_string.replace("Hello", "Hi")

# Print the original and modified strings

print("Original string:", original_string)

print("Modified string:", new_string)

Example Using Join():

# Define a list of strings

words = ["Hello", "world", "how", "are", "you?"]

# Join the strings in the list with a space delimiter

sentence = " ".join(words)

# Print the resulting sentence

print(sentence)

Example using Upper():

# Define a string

original_string = "hello, world!"

# Convert the string to uppercase

uppercase_string = original_string.upper()

# Print the original and uppercase strings

print("Original string:", original_string)

print("Uppercase string:", uppercase_string)

6
Example using Lower():

# Define a string

original_string = "Hello, World!"

# Convert the string to lowercase

lowercase_string = original_string.lower()

# Print the original and lowercase strings

print("Original string:", original_string)

print("Lowercase string:", lowercase_string)

Example Using Capitalize():

sentence = "i am learning PYTHON."

# capitalize the first character

capitalized_string = sentence.capitalize()

# the sentence string is not modified

print('Before capitalize():', sentence)

print('After capitalize():', capitalized_string)

4 - Demonstrate the file operations in python

#Read the entire file

import os

file = open("C:\pdapython\operations1.txt", "r")

print(file.read())

file.close()

7
#Read the first 7 characters of my file

import os

file = open("C:\pdapython\operations1.txt", "r")

print(file.read(7))

file.close()

#Read line by line

import os

file = open("C:\pdapython\operations1.txt", "r")

print(file.readline())1

file.close()

#Read line by line all lines

import os

file = open("C:\pdapython\operations1.txt", "r")

print(file.readlines())

file.close()

#Write function

#overwrite it with new content

import os

file = open("C:\pdapython\operations2.txt", "w")

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 = open("C:\pdapython\operations6.txt", "x")

file.write("sunshine")

file.close()

Demonstrate creation and different operations on List data structure in python

Write a program to Reverse a list in Python:

list1 = [100, 200, 300, 400, 500]

list1.reverse()

print(list1)

Write a program to Concatenate two lists index-wise:

list1 = ["M", "na", "i", "Ke"]

list2 = ["y", "me", "s", "lly"]

list3 = [i + j for i, j in zip(list1, list2)]

print(list3)

Write a program to Turn every item of a list into its square:

numbers = [1, 2, 3, 4, 5, 6, 7]

# result list

res = []

for i in numbers:

# calculate square and add to the result list

9
res.append(i * i)

print(res)

Write a program to Iterate both lists simultaneously:

list1 = [10, 20, 30, 40]

list2 = [100, 200, 300, 400]

for x, y in zip(list1, list2[::-1]):

print(x, y)

Write a program to Remove empty strings from the list of strings:

list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]

# remove None from list1 and convert result into list

res = list(filter(None, list1))

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"]

sub_list = ["h", "i", "j"]

# understand indexing

# list1[2] = ['c', ['d', 'e', ['f', 'g'], 'k'], 'l']

# list1[2][1] = ['d', 'e', ['f', 'g'], 'k']

# list1[2][1][2] = ['f', 'g']

# solution

10
list1[2][1][2].extend(sub_list)

print(list1)

Demonstrate creation and different operations on Tuple data structure in python

write a program to Reverse the tuple:

tuple1 = (10, 20, 30, 40, 50)

tuple1 = tuple1[::-1]

print(tuple1)

write a program to Access value 20 from the tuple:

tuple1 = ("Orange", [10, 20, 30], (5, 15, 25))

print(tuple1[1][1])

write a program to Create a tuple with single item 50:

tuple1= (50, )

print(tuple1)

Write a program to unpack the following tuple into four variables and display each
variable.

tuple1 = (10, 20, 30, 40)

# unpack tuple into 4 variables

a, b, c, d = tuple1

print(a)

print(b)

print(c)

print(d)

write a program to Swap two tuples in Python:

11
tuple1 = (11, 22)

tuple2 = (99, 88)

tuple1, tuple2 = tuple2, tuple1

print(tuple2)

print(tuple1)

Write a program to copy elements 44 and 55 from the following tuple into a new
tuple.

tuple1 = (11, 22, 33, 44, 55, 66)

tuple2 = tuple1[3:-1]

print(tuple2)

write a program to Sort a tuple of tuples by 2nd item:

tuple1 = (('a', 23), ('b', 37), ('c', 11), ('d', 29))

tuple1 = tuple(sorted(list(tuple1), key=lambda x: x[1]))

print(tuple1)

7. Demonstrate creation and different operations on Set data structure in python

write a program to Add a list of elements to a set

sample_set = {"Yellow", "Orange", "Black"}

sample_list = ["Blue", "Green", "Red"]

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}

{30, 40, 50, 60, 70}

print(set1.intersection(set2))

write a program to Updqate the first set with items that don’t exist in the second set

set1 = {10, 20, 30}

set2 = {20, 40, 50}

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

set1 = {10, 20, 30, 40, 50}

set2 = {60, 70, 80, 90, 10}

if set1.isdisjoint(set2):

print("Two sets have no items in common")

else:

print("Two sets have items in common")

print(set1.intersection(set2)

write a program to Update set1 by adding items from set2, except common items

set1 = {10, 20, 30, 40, 50}

set2 = {30, 40, 50, 60, 70}

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 = {10, 20, 30, 40, 50}

set2 = {30, 40, 50, 60, 70}

set1.intersection_update(set2)

print(set1)

8. Demonstrate creation and different operations on Dictionary data structure in


python

write a program to Convert two lists into a dictionary

keys = ['Ten', 'Twenty', 'Thirty']

values = [10, 20, 30]

res_dict = dict(zip(keys, values))

print(res_dict)

write a program to Merge two Python dictionaries into one

dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}

dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

dict3 = {**dict1, **dict2}

print(dict3)

write a program to Initialize dictionary with default values

employees = ['Kelly', 'Emma']

defaults = {"designation": 'Developer', "salary": 8000}

res = dict.fromkeys(employees, defaults)

print(res)

#Individual data
14
print(res["Kelly"])

write a program to Create a dictionary by extracting the keys from a given


dictionary

sampleDict = {

"name": "Kelly",

"age":25,

"salary": 8000,

"city": "New york" }

keys = ["name", "salary"]

newDict = {k: sampleDict[k] for k in keys}

print(newDict)

write a program to Delete a list of keys from a dictionary

sample_dict = {

"name": "Kelly",

"age": 25,

"salary": 8000,

"city": "New york"

# Keys to remove

keys = ["name", "salary"]

for k in keys:

sample_dict.pop(k)

print(sample_dict)

write a program Change value of a key in a nested dictionary

15
sample_dict = {

'emp1': {'name': 'Jhon', 'salary': 7500},

'emp2': {'name': 'Emma', 'salary': 8000},

'emp3': {'name': 'Brad', 'salary': 6500}

sample_dict['emp3']['salary'] = 8500

print(sample_dict)

9. Demonstrate creation and use of Functions in python with all kinds of


“parameters” used with functions

Positional Parameters:

# Function with positional parameters

def greet(name, greeting):

print(f"{greeting}, {name}!")

# Calling the function with positional arguments

greet("Alice", "Hello")

Default Parameters:

# Function with default parameters

def greet(name, greeting="Hello"):

print(f"{greeting}, {name}!")

# Calling the function with and without providing the default parameter

greet("Bob") # Output: Hello, Bob!

greet("Charlie", "Hi") # Output: Hi, Charlie!

16
Variable-Length Positional Parameters (args):

# Function with variable-length positional parameters

def greet(*names):

for name in names:

print(f"Hello, {name}!")

# Calling the function with multiple arguments

greet("Alice", "Bob", "Charlie")

Keyword Parameters:

# Function with keyword parameters

def greet(name, greeting):

print(f"{greeting}, {name}!")

# Calling the function with keyword arguments

greet(name="David", greeting="Hi")

Variable-Length Keyword Parameters (kwargs):

# Function with variable-length keyword parameters

def greet(**kwargs):

for key, value in kwargs.items():

print(f"{key}: {value}")

# Calling the function with multiple keyword arguments

greet(name="Emily", greeting="Bonjour", age=30)

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):

for j in range(0, n-i-1):

if arr[j] > arr[j+1]:

arr[j], arr[j+1] = arr[j+1], arr[j]

# 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

while i < len(L) and j < len(R):

if L[i] < R[j]:

arr[k] = L[i]

i += 1

else:

arr[k] = R[j]

18
j += 1

k += 1

while i < len(L):

arr[k] = L[i]

i += 1

k += 1

while j < len(R):

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]

left = [x for x in arr if x < pivot]

middle = [x for x in arr if x == pivot]

right = [x for x in arr if x > pivot]

return quick_sort(left) + middle + quick_sort(right)

# Generate a random list of numbers

random_list = random.sample(range(1, 10000), 1000)

# Measure time taken by Bubble Sort

start_time = time.time()

19
bubble_sort(random_list.copy())

bubble_sort_time = time.time() - start_time

# Measure time taken by Merge Sort

start_time = time.time()

merge_sort(random_list.copy())

merge_sort_time = time.time() - start_time

# Measure time taken by Quick Sort

start_time = time.time()

quick_sort(random_list.copy())

quick_sort_time = time.time() - start_time

print("Time taken by Bubble Sort:", bubble_sort_time)

print("Time taken by Merge Sort:", merge_sort_time)

print("Time taken by Quick Sort:", quick_sort_time)

11. Demonstrate creating objects and inheritance

Creating Objects:

# Define a class

class Person:

# Constructor

def __init__(self, name, age):

self.name = name

self.age = age

# Method to display information

def display_info(self):

20
print(f"Name: {self.name}, Age: {self.age}")

# Create an object of the Person class

person1 = Person("Alice", 30)

# Call the display_info method of the object

person1.display_info()

Inheritance:

# Define a base class

class Animal:

def __init__(self, name):

self.name = name

def speak(self):

raise NotImplementedError("Subclass must implement abstract method")

# Define a subclass inheriting from Animal

class Dog(Animal):

def speak(self):

return f"{self.name} says Woof!"

# Define another subclass inheriting from Animal

class Cat(Animal):

def speak(self):

return f"{self.name} says Meow!"

# Create objects of the subclasses

dog = Dog("Buddy")

cat = Cat("Whiskers")

# Call the speak method of the objects

21
print(dog.speak()) # Output: Buddy says Woof!

print(cat.speak()) # Output: Whiskers says Meow!

12. Demonstrate NumPY library – Array Operations, Mathematical Functions,


Sort, Search and Counting Functions.

import numpy as np

# Creating arrays

arr1 = np.array([1, 2, 3, 4, 5])

arr2 = np.array([6, 7, 8, 9, 10])

# Array Operations

print("Array Operations:")

print("Array 1:", arr1)

print("Array 2:", arr2)

print("Sum:", np.sum(arr1)) # Sum of array elements

print("Mean:", np.mean(arr1)) # Mean of array elements

print("Max:", np.max(arr1)) # Maximum value in the array

print("Min:", np.min(arr1)) # Minimum value in the array

print("Dot Product:", np.dot(arr1, arr2))# Dot product of two arrays

print()

# Mathematical Functions

print("Mathematical Functions:")

arr3 = np.array([1, 4, 9, 16, 25])

print("Square root of arr3:", np.sqrt(arr3)) # Square root of array elements

print("Exponential of arr1:", np.exp(arr1)) # Exponential of array elements

22
print("Sine of arr1:", np.sin(arr1)) # Sine of array elements

print()

# Sorting

print("Sorting:")

arr4 = np.array([3, 1, 4, 1, 5, 9, 2, 6, 5])

print("Unsorted array:", arr4)

arr4_sorted = np.sort(arr4) # Sort array

print("Sorted array:", arr4_sorted)

print()

# Searching

print("Searching:")

arr5 = np.array([2, 4, 6, 8, 10])

print("Array:", arr5)

index = np.where(arr5 == 6) # Find index where value is 6

print("Index of 6:", index[0])

print()

# Counting

print("Counting:")

arr6 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5])

print("Array:", arr6)

count_unique = np.unique(arr6) # Count unique elements

print("Unique elements:", count_unique)

print("Count of each unique element:")

for unique_val in count_unique:

23
count = np.count_nonzero(arr6 == unique_val) # Count occurrences of each unique
element

print(unique_val, ":", count)

This code snippet demonstrates various functionalities of NumPy:

Array Operations: Basic operations like sum, mean, max, min, and dot product.

Mathematical Functions: Applying mathematical functions like square root, exponential,


and sine to array elements.

Sorting: Sorting arrays.

Searching: Finding indices of specific values in arrays.

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.

13. Demonstrate Matplotlib Library – Introduction, Pyplot API, Types of Plots,


Histogram Using Matplotlib , I/O With Numpy.

i) Draw a line in a diagram from position (1, 3) to position (8, 10)

import matplotlib.pyplot as plt


import numpy as np

xpoints = np.array([1, 8])


ypoints = np.array([3, 10])

plt.plot(xpoints, ypoints)
plt.show()

ii) Mark each point with a circle

import matplotlib.pyplot as plt

24
import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, marker = 'o')


plt.show()

iii) Add grid lines to the plot

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.title("Sports Watch Data")


plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.plot(x, y)

plt.grid()

plt.show()

iv)Draw 2 plots

import matplotlib.pyplot as plt


import numpy as np

#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

import matplotlib.pyplot as plt


import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

plt.bar(x,y)
plt.show()

vi) A simple scatter plot

import matplotlib.pyplot as plt


import numpy as np

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()

vii) A simple pie chart

import matplotlib.pyplot as plt


import numpy as np

y = np.array([35, 25, 25, 15])

plt.pie(y)
plt.show()

Introduction to Matplotlib and its usage.

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

You might also like