0% found this document useful (0 votes)
16 views

Python Lab Practicles-2

Uploaded by

netflixbasic500
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Python Lab Practicles-2

Uploaded by

netflixbasic500
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

LAB PROGRAMS

Prof. Kuljeet Singh


UNIT 1
BASIC DATA TYPES AND CONTROL STRUCTURES
Program 1
Write a Python program to do arithmetical operations addition and subtraction.

# Addition
num1 = float(input("Enter the first number for addition: "))
num2 = float(input("Enter the second number for addition: "))
sum_result = num1 + num2
print(f"sum: {num1} + {num2} = {sum_result}")

Output:
Enter the first number for addition: 5
Enter the second number for addition: 6
sum: 5.0 + 6.0 = 11.0
Program 2
Write a Python program to find the area of a triangle.

# Input the base and height from the user


base = float(input("Enter the length of the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
# Calculate the area of the triangle
area = 0.5 * base * height
# Display the result
print(f"The area of the triangle is: {area}")

Enter the length of the base of the triangle: 10


Enter the height of the triangle: 15
The area of the triangle is: 75.0
Program 3
Write a Python program to do arithmetic operation division using ‘if else’ condition

# Division
num3 = float(input("Enter the dividend for division: "))
num4 = float(input("Enter the divisor for division: "))
if num4 == 0:
print("Error: Division by zero is not allowed.")
else:
div_result = num3 / num4
print(f"Division: {num3} / {num4} = {div_result}")

Enter the dividend for division: 25


Enter the divisor for division: 5
Division: 25.0 / 5.0 = 5.0
Program 4
Write a Python program to swap two variables.

# Input two variables


a = input("Enter the value of the first variable (a): ")
b = input("Enter the value of the second variable (b): ")
# Display the original values
print(f"Original values: a = {a}, b = {b}")
# Swap the values using a temporary variable
temp = a
a=b
b = temp
# Display the swapped values
print(f"Swapped values: a = {a}, b = {b}") Enter the value of the first variable (a): 5
Enter the value of the second variable (b):
9
Original values: a = 5, b = 9
Program 5
Write a Python program to generate a random number.

import random
print(f"Random number: {random.randint(1, 100)}")

Random number: 89
Program 6
Write a Python program to convert kilometers to meters.

kilometers = float(input("Enter distance in kilometers: "))


# Conversion factor: 1 kilometer = 1000 meters
conversion_factor = 1000
meters = kilometers * conversion_factor
print(f"{kilometers} kilometers is equal to {meters} meters")

Enter distance in kilometers: 5


5.0 kilometers is equal to 5000 meters
Program 7
Write a Python program to display calendar.

import calendar
year = int(input("Enter year: "))
month = int(input("Enter month: "))
cal = calendar.month(year, month)
print(cal)

Enter year: 2024


Enter month: 8
August 2024
Mo Tu We Th Fr Sa Su
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Program 8
Write a Python program to swap two variables without temp variable.
a=5
b = 10
# Swapping without a temporary variable
a, b = b, a
print("After swapping:")
print("a =", a)
print("b =", b)

After swapping:
a = 10
b=5
Program 9
Write a Python Program to Check if a Number is Positive, Negative or Zero.

num = float(input("Enter a number: "))


if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Enter a number: 9
Positive number
Program 10
Write a Python Program to Check if a Number is Odd or Even.

num = int(input("Enter a number: "))


if num%2 == 0:
print("This is a even number")
else:
print("This is a odd number")

Enter a number: 7
This is a odd number
Program 11
Check if a number is positive, negative, or zero

num = float(input("Enter a number: "))

if num > 0:
print(f"{num} is a positive number.")
elif num < 0:
print(f"{num} is a negative number.")
else:
print("The number is zero.")
Program 12
Sum of elements in a list

numbers = [1, 2, 3, 4, 5]
total = 0

for number in numbers:


total += number

print(f"The sum of the list elements is {total}.")


Program 13
Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))

# first two terms


n1, n2 = 0, 1
count = 0 # generate fibonacci sequence
else:
# check if the number of terms is valid print("Fibonacci sequence:")
if nterms <= 0: while count < nterms:
print("Please enter a positive integer") print(n1)
# if there is only one term, return n1 nth = n1 + n2
elif nterms == 1: # update values
print("Fibonacci sequence n1 = n2
upto",nterms,":") n2 = nth
print(n1) count += 1
Program 14

Print numbers from 1 to 10

i=1

while i <= 10:


print(i)
i += 1
Program 15
Find the factorial of a number

num = int(input("Enter a number: "))


factorial = 1
i=1

while i <= num:


factorial *= i
i += 1

print(f"The factorial of {num} is


{factorial}.")
Program 16
Find the first number in a list that is divisible by 5

numbers = [3, 8, 6, 10, 14, 5, 20]

for number in numbers:


if number % 5 == 0:
print(f"The first number divisible by 5 is {number}.")
break
Program 17
Print odd numbers only

# Program to print odd numbers in a range


for i in range(1, 20):
if i % 2 == 0:
continue
print(i)
UNIT 2
LISTS AND TUPLES
Program 1
Implementing Lists in Python Programs

1. Program to Sum Elements in a List

numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(f"Sum of list: {total}")

def sum_of_list(lst):
total = sum(lst)
return total

numbers = [1, 2, 3, 4, 5]
print(f"Sum of list: {sum_of_list(numbers)}")
Program 2
2. Program to Find the Maximum and Minimum in a List

numbers = [10, 20, 5, 30, 15]


max_num = max(numbers)
min_num = min(numbers)
print(f"Maximum: {max_num}, Minimum: {min_num}")

def find_max_min(lst):
return max(lst), min(lst)

numbers = [10, 20, 5, 30, 15]


max_num, min_num = find_max_min(numbers)
print(f"Maximum: {max_num}, Minimum: {min_num}")
Program 3
3. Program to Count Occurrences of Each Element

items = ['apple', 'banana', 'apple', 'orange', 'banana']


occurrences = {item: items.count(item) for item in set(items)}
print("Occurrences:", occurrences)

def count_occurrences(lst):
return {item: lst.count(item) for item in set(lst)}

items = ['apple', 'banana', 'apple', 'orange', 'banana']


occurrences = count_occurrences(items)
print("Occurrences:", occurrences)
Program 4
4. Program to Merge Two Lists

list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print(f"Merged list: {merged_list}")

def merge_lists(list1, list2):


return list1 + list2

list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = merge_lists(list1, list2)
print(f"Merged list: {merged_list}")
Program 5
5. Program to Remove Duplicates from a List

items = [1, 2, 2, 3, 4, 4, 5]
unique_items = list(set(items))
print(f"List without duplicates: {unique_items}")

def remove_duplicates(lst):
return list(set(lst))

items = [1, 2, 2, 3, 4, 4, 5]
unique_items = remove_duplicates(items)
print(f"List without duplicates: {unique_items}")
Program 6
6. Program to Generate a List of Squares

n=5
squares = [i**2 for i in range(n)] Output: List of squares: [0, 1, 4, 9, 16]
print(f"List of squares: {squares}")

def generate_squares(n):
return [i**2 for i in range(n)]

squares = generate_squares(5)
print(f"List of squares: {squares}")
Program 7
7. Accessing elements, slicing, and iterating through a tuple

# Defining a tuple
my_tuple = (10, 20, 30, 40, 50)

# Accessing elements using index


print(my_tuple[0]) # Output: 10
print(my_tuple[2]) # Output: 30

# Slicing a tuple (from index 1 to 3, exclusive)


print(my_tuple[1:4]) # Output: (20, 30, 40)

# Iterating through a tuple


for item in my_tuple:
print(item)
Program 8
8. WAP on basic operations like concatenation, repetition, and membership test.
# Concatenation of tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
tuple3 = tuple1 + tuple2
print(f"Concatenated Tuple: {tuple3}") # Output: (1, 2, 3, 4, 5, 6)

# Repeating a tuple
repeated_tuple = tuple1 * 3
print(f"Repeated Tuple: {repeated_tuple}") # Output: (1, 2, 3, 1, 2, 3,
1, 2, 3)

# Checking if an element exists in a tuple (membership test)


print(2 in tuple1) # Output: True
print(7 in tuple1) # Output: False
Program 9
9. WAP to use tuple methods - count() and index()

# Tuple with duplicate elements


my_tuple = (1, 2, 3, 2, 4, 2, 5)

# count(): Returns the number of occurrences of an element


count_of_twos = my_tuple.count(2)
print(f"Count of 2 in tuple: {count_of_twos}") # Output: 3

# index(): Returns the first index of an element


index_of_three = my_tuple.index(3)
print(f"Index of 3 in tuple: {index_of_three}") # Output: 2
Program 10
10. WAP to use mixed tuples and nested tuples

# Tuple with mixed data types


mixed_tuple = (10, "Python", 3.14)
print(f"Mixed Tuple: {mixed_tuple}") # Output: (10, 'Python', 3.14)

# Nested tuple
nested_tuple = (1, (2, 3), (4, 5, 6))
print(f"Nested Tuple: {nested_tuple}") # Output: (1, (2, 3), (4, 5, 6))

# Accessing elements in a nested tuple


print(nested_tuple[1]) # Output: (2, 3)
print(nested_tuple[1][1]) # Output: 3
UNIT 3
SETS AND DICTIONARIES
Program 1
1. WAP for Creating a Set and Accessing Elements

Creating a set and displaying elements


my_set = {1, 2, 3, 4, 5}
print("Set:", my_set)

# Iterating through the set


for item in my_set:
print(item)
Program 2
2. WAP for Adding Elements to a Set

# Adding elements to a set


my_set = {1, 2, 3}
print("Original Set:", my_set)

# Adding a single element


my_set.add(4)
print("Set after adding 4:", my_set)

# Adding multiple elements using update()


my_set.update([5, 6, 7])
print("Set after adding multiple elements:", my_set)
Program 3
3. WAP for Removing Elements from a Set

# Removing elements from a set


my_set = {1, 2, 3, 4, 5}
print("Original Set:", my_set)

# Removing an element using remove() - Raises error if not found


my_set.remove(3)
print("Set after removing 3:", my_set)

# Removing an element using discard() - No error if not found


my_set.discard(6) # No error even though 6 is not in the set
print("Set after discarding 6:", my_set)
Program 4
4. WAP for Clearing a Set

# Clearing all elements from a set


my_set = {1, 2, 3, 4, 5}
print("Original Set:", my_set)

# Clear the set


my_set.clear()
print("Set after clearing:", my_set) # Output: set()
Program 5
5. WAP to implement Set Union Operation

# Performing union of two sets


set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Union of two sets


union_set = set1.union(set2)
print("Union of set1 and set2:", union_set) # Output: {1, 2, 3, 4, 5}
Program 6
6. WAP to implement Set Intersection Operation

# Performing intersection of two sets


set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Intersection of two sets


intersection_set = set1.intersection(set2)
print("Intersection of set1 and set2:", intersection_set) # Output: {3}
Program 7
7. WAP to implement Set Difference Operation

# Performing difference of two sets


set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Difference of two sets


difference_set = set1.difference(set2)
print("Difference of set1 and set2 (set1 - set2):", difference_set) # Output: {1, 2}
Program 8
8. WAP to implement Set Symmetric Difference Operation

# Performing symmetric difference of two sets


set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Symmetric difference of two sets


sym_diff_set = set1.symmetric_difference(set2)
print("Symmetric Difference of set1 and set2:", sym_diff_set) # Output: {1, 2, 4, 5}
Program 9
9. WAP to implement Checking Subset and Superset

# Checking subset and superset relationships


set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}

# Checking if set1 is a subset of set2


is_subset = set1.issubset(set2)
print("Is set1 a subset of set2?", is_subset) # Output: True

# Checking if set2 is a superset of set1


is_superset = set2.issuperset(set1)
print("Is set2 a superset of set1?", is_superset) # Output: True
Program 10
10. WAP to implement Frozen Sets (Immutable Sets)

# Creating and using a frozenset


my_set = {1, 2, 3}
frozen = frozenset(my_set)
print("Frozen Set:", frozen)

# Trying to modify frozen set (raises error)

frozen.add(4) # This will raise an AttributeError as frozenset is immutable


Program 11
11. Defining and Accessing a Dictionary

# Defining a dictionary
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# Printing the dictionary


print("Dictionary:", my_dict)

# Accessing elements in a dictionary


my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# Accessing elements by keys


print("Name:", my_dict['name']) # Output: John
print("Age:", my_dict['age']) # Output: 25
Program 12
12. Adding and Updating Elements in a Dictionary

# Adding and updating elements in a dictionary


my_dict = {'name': 'John', 'age': 25}

# Adding a new key-value pair


my_dict['city'] = 'New York'
print("Dictionary after adding 'city':", my_dict)

# Updating an existing value


my_dict['age'] = 26
print("Dictionary after updating 'age':", my_dict)
Program 13
13. Removing Elements from a Dictionary

# Removing elements from a dictionary


my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# Removing an element using pop()


removed_value = my_dict.pop('age')
print("Removed value:", removed_value) # Output: 25
print("Dictionary after removal:", my_dict)

# Removing an element using del


del my_dict['city']
print("Dictionary after deleting 'city':", my_dict)
Program 14
14. Iterating Through a Dictionary
# Iterating through a dictionary
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# Iterating through keys


print("Keys:")
for key in my_dict:
print(key)

# Iterating through values


print("\nValues:")
for value in my_dict.values():
print(value)

# Iterating through key-value pairs


print("\nKey-Value Pairs:")
for key, value in my_dict.items():
print(f"{key}: {value}")
Program 15
15. Dictionary Methods - keys(), values(), items(), get()
# Using dictionary methods keys(), values(), and items()
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# Getting all keys


keys = my_dict.keys()
print("Keys:", keys) # Using get() to access values safely
age = my_dict.get('age')
# Getting all values print("Age:", age) # Output: 25
values = my_dict.values()
print("Values:", values) # Using get() with a default value if key is not found
salary = my_dict.get('salary', 50000)
# Getting all key-value pairs print("Salary (default):", salary) # Output: 50000
items = my_dict.items()
print("Key-Value Pairs:", items)
Thank You

You might also like