0% found this document useful (0 votes)
2 views11 pages

Python Program List For Autonomous

list

Uploaded by

rashmi.cse-cs
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)
2 views11 pages

Python Program List For Autonomous

list

Uploaded by

rashmi.cse-cs
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/ 11

CSE-152L: Programming with Python Lab

(Prerequisite: Problem solving using “C” - Theory & Lab)


(Lab based on the theory subject - Programming with Python)

List of Experiments

1. Write a Python program to find the largest among the three numbers.
2. Write a python program to accept three sides of a triangle as the input and print whether
the triangle is valid or not.
3. Write a program to check if the given number is a palindrome number.
4. Write a program to reverse a user entered no and determine whether the original and
reversed no’s are equal or not.
5. Write a program to count the no of alphabets and no of digits in a string.
6. Write a program to accept a string from the user, delete all vowels from the string and
display the result.
7. Given a string, write a Python program to find the largest substring of uppercase
characters and print the length of that substring.
8. Write a program to create the following 3 lists:
 A list of names.
 A list of employee’s ids.
 A list of salaries.
From these lists, generate 3 tuples - one containing all names, another containing all ids
and third containing all salaries. Also, from the three created lists, generate and print a
list of tuples containing name, ids and salaries.
9. Write a program to create a set containing 10 randomly generated nos in the range 15 to
40. Count how many of these nos are less than 30. Delete all nos greater than 35.
10. Create a dictionary of 10 usernames and passwords. Receive the username and password
from the keyboard and search for them in the dictionary. Based on whether a match is
found, print an appropriate message on the screen.
11. Write a program that defines a function compute ( ) that calculates the value of n + nn +
nnn + nnnn, where n is digit received by the function. Test the function for digits 4 and 7.
12. Write a Python program to demonstrate the use of lambda functions with map, filter, and
reduce.
13. Write a Python program to handle a Zero Division Error exception when dividing a
number by zero.
14. Write a Python program that prompts the user to input an integer and raises a Value Error
exception if the input is not a valid integer.
15. Write a Python program to create a numpy array of given shapes and perform basic
mathematical operations.
16. Write a Python program to perform group by and aggregation on a Pandas data frame.
17. Create Box plot, Scatter Plot and Histogram with Matplotlib.
18. Create Pair plot, Heatmap and Distribution plot with Seaborn.
1. Write a Python program to find the largest among the three numbers.

Logic Explanation:
To determine the largest of three numbers, we compare them using conditional statements.
We take input for three numbers separately and then compare them. We use if-elif-else
conditions to check which number is the greatest.
Example:
Input: 10, 25, 15
Comparison: 25 is greater than 10 and 15
Output: 25

# Taking input from the user for three numbers


print("Enter three numbers:")
a = int(input()) # Reads first number from user and converts to integer
b = int(input()) # Reads second number from user and converts to integer
c = int(input()) # Reads third number from user and converts to integer

# Finding the largest number using conditional statements


if a >= b and a >= c: # Checks if 'a' is greater than or equal to both 'b' and 'c'
largest = a
elif b >= a and b >= c: # If 'a' is not the largest, checks if 'b' is greater than or equal to 'a' and
'c'
largest = b
else:
largest = c # If neither 'a' nor 'b' is the largest, 'c' must be the largest

# Printing the largest number


print("Largest number:", largest)
Output:
Enter three numbers:
10
25
15
Largest number: 25

2. Write a python program to accept three sides of a triangle as the input and print
whether the triangle is valid or not.
Logic of the program:
# 1. Take three integer inputs representing the sides of a triangle.
# 2. Check the triangle validity condition: The sum of any two sides must be greater than the
third side.
# 3. If the condition is met, print that the triangle is valid; otherwise, print that it is invalid.

# Example:
# Input: 3, 4, 5
# Output: The given sides form a valid triangle.

# Input: 1, 2, 3
# Output: The given sides do not form a valid triangle.

a = int(input("Enter first side: "))


b = int(input("Enter second side: "))
c = int(input("Enter third side: "))

# Check if the sides form a valid triangle


if a + b > c and a + c > b and b + c > a:
print("The given sides form a valid triangle.")
else:
print("The given sides do not form a valid triangle.")

3. Write a program to check if the given number is a palindrome number.

Logic Explanation:
A palindrome number reads the same forward and backward. We convert the number to a
string, reverse it, and check if it matches the original.
Example:
Input: 121
Reversed: 121
Output: Palindrome

# Taking input from the user


n = int(input("Enter a number: ")) # Reads a number and converts it to an integer

# Convert number to string to check palindrome property


n_str = str(n) # Converts number to string for easy reversal

# Check if the string is the same when reversed


if n_str == n_str[::-1]: # Uses string slicing to reverse and compare with original
print("Palindrome")
else:
print("Not a palindrome")

4. Write a program to reverse a user entered no and determine whether the original and
reversed no’s are equal or not.
Logic of the program:
1. Take an integer input from the user.
2. Extract digits one by one from the number using modulus and division.
3. Construct the reversed number by multiplying the current reversed number by 10 and
adding the extracted digit.
4. Compare the original number with the reversed number to check if it is a palindrome.
5. Display the reversed number and the result.

# Example:
# Input: 121
# Reversed: 121
# Output: The original and reversed numbers are the same (Palindrome).

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

# Reverse the number


reversed_num = 0
temp = num
while temp > 0:
digit = temp % 10
reversed_num = reversed_num * 10 + digit
temp //= 10

print("Reversed number:", reversed_num)

# Check for palindrome


if num == reversed_num:
print("The original and reversed numbers are the same (Palindrome).")
else:
print("The original and reversed numbers are different.")

5. Write a program to count the no of alphabets and no of digits in a string.


Logic of the program:
# 1. Take a string input from the user.
# 2. Initialize counters for alphabets and digits.
# 3. Iterate through each character in the string and check if it is an alphabet or a digit.
# 4. Increase the respective counter accordingly.
# 5. Print the total count of alphabets and digits.

# Example:
# Input: "Hello123"
# Output: Alphabets: 5, Digits: 3

string = input("Enter a string: ")

alphabet_count = 0
digit_count = 0

for char in string:


if char.isalpha():
alphabet_count += 1
elif char.isdigit():
digit_count += 1
print("Alphabets:", alphabet_count)
print("Digits:", digit_count)

6. Write a program to accept a string from the user, delete all vowels from the string and
display the result.

We iterate over the string and remove characters that are vowels by checking against a
predefined set of vowels.
Example:
Input: Hello World
Vowels removed: Hll Wrld
Output: Hll Wrld

# Taking input string from the user


s = input("Enter a string: ")

# Defining vowels
vowels = "aeiouAEIOU" # String containing all vowels (both lowercase and uppercase)

# Creating an empty string to store result


result = ""

# Iterating through each character in input string


for char in s:
if char not in vowels: # Check if the character is not a vowel
result += char # Add non-vowel characters to result

# Printing the modified string


print("String without vowels:", result)

Output:
Enter a string: Hello World
String without vowels: Hll Wrld

7. Given a string, write a Python program to find the largest substring of uppercase
characters and print the length of that substring.

Logic Explanation:
We traverse the string and count the length of contiguous uppercase letters to find the largest
uppercase sequence.
Example:
Input: abcDEFghIJ
Longest Uppercase Substring: DEF (length: 3)
Output: 3

# Taking input string from user


s = input("Enter a string: ")
# Initializing variables to track longest uppercase sequence
max_len = 0 # Stores maximum length of uppercase sequence found
curr_len = 0 # Tracks current sequence length

# Iterating through each character in string


for char in s:
if char.isupper(): # Checks if character is uppercase
curr_len += 1 # Increment current uppercase sequence length
if curr_len > max_len:
max_len = curr_len # Update max length if current sequence is longer
else:
curr_len = 0 # Reset count when a lowercase character is found

# Printing the length of longest uppercase sequence


print("Longest uppercase substring length:", max_len)

Output:
Enter a string: abcDEFghIJ
Longest uppercase substring length: 3

8. Write a program to create the following 3 lists:


 A list of names.
 A list of employee’s ids.
 A list of salaries.
From these lists, generate 3 tuples - one containing all names, another containing all ids
and third containing all salaries. Also, from the three created lists, generate and print a
list of tuples containing name, ids and salaries.

Logic Explanation:
We store employee data in lists, then convert them into tuples and a list of tuples.
Example:
Input: Alice (101, 50000), Bob (102, 60000), Charlie (103, 70000)
Tuples: ('Alice', 'Bob', 'Charlie'), (101, 102, 103), (50000, 60000, 70000)
List of Tuples: [('Alice', 101, 50000), ('Bob', 102, 60000), ('Charlie', 103, 70000)]

# Initializing empty lists


names = []
ids = []
salaries = []

# Taking number of employees as input


n = int(input("Enter number of employees: "))
for i in range(n):
name = input("Enter name: ")
emp_id = int(input("Enter ID: "))
salary = float(input("Enter salary: "))

names.append(name) # Storing names in list


ids.append(emp_id) # Storing employee IDs
salaries.append(salary) # Storing salaries

# Converting lists to tuples


name_tuple = tuple(names)
id_tuple = tuple(ids)
salary_tuple = tuple(salaries)

# Creating a list of tuples


employee_data = []
for i in range(n):
employee_data.append((names[i], ids[i], salaries[i])) # Creating tuple for each employee

# Printing results
print("Tuples:", name_tuple, id_tuple, salary_tuple)
print("Employee Data:", employee_data)

9. Write a program to create a set containing 10 randomly generated nos in the range 15
to 40. Count how many of these nos are less than 30. Delete all nos greater than 35.
Logic:
# 1. Generate a set of 10 unique random numbers between 15 and 40.
# 2. Count how many numbers are less than 30.
# 3. Remove numbers greater than 35.
# 4. Display the results: the original set, count of numbers < 30, and the modified set.

# Example:
# Generated Set: {18, 22, 35, 40, 27, 29, 33, 19, 38, 25}
# Count of numbers less than 30: 6
# Set after deleting numbers greater than 35: {18, 22, 35, 27, 29, 33, 19, 25}

import random
# Generate a set of 10 unique random numbers between 15 and 40
# However, since a set only keeps unique values, it may not always end up with exactly 20
elements (some numbers may repeat and get discarded).
random_numbers = {random.randint(15, 40) for _ in range(20)}
print("Generated Set:", random_numbers)

# Count numbers less than 30


# When passed to sum(), True values contribute 1 to the total count, while False contributes
0.
count_less_than_30 = sum(num < 30 for num in random_numbers)
print("Count of numbers less than 30:", count_less_than_30)

# Remove numbers greater than 35


random_numbers = {num for num in random_numbers if num <= 35}
print("Set after deleting numbers greater than 35:", random_numbers)
10. Create a dictionary of 10 usernames and passwords. Receive the username and
password from keyboard and search for them in the dictionary. Print appropriate
message on the screen based on whether a match is found or not.

Logic Explanation:
We store usernames and passwords in a dictionary and check user input against it.
Example:
Input: username=user1, password=pass1
Dictionary: {"user1": "pass1", "user2": "pass2"}
Output: Login successful

Initializing an empty dictionary


credentials = {}

# Taking input for multiple users


n = int(input("Enter number of users: "))
for i in range(n):
username = input("Enter username: ")
password = input("Enter password: ")
credentials[username] = password # Storing username-password pair in dictionary

# Taking login input


username = input("Enter username: ")
password = input("Enter password: ")

# Checking credentials in dictionary


if username in credentials and credentials[username] == password:
print("Login successful")
else:
print("Invalid credentials")

11. Write a program that defines a function compute ( ) that calculates the value of n + nn +
nnn + nnnn, where n is digit received by the function. Test the function for digits 4 and
7.

Logic Explanation:
We define a function compute() that generates terms by converting the number to a string and
repeating it to form nn, nnn, and nnnn. We then convert them back to integers and sum them
up.
Example:
Input: 4
Computation: 4 + 44 + 444 + 4444 = 4936
Output: 4936

# Function to compute the required sum


def compute(n):
# Creating the terms using string repetition
n1 = int(n) # First term (n)
n2 = int(n * 2) # Second term (nn)
n3 = int(n * 3) # Third term (nnn)
n4 = int(n * 4) # Fourth term (nnnn)

# Calculating the sum


return n1 + n2 + n3 + n4

# Taking input from the user


n = input("Enter a digit: ") # Reads input as string
result = compute(n) # Calls the function with user input

# Printing the result


print("Computed value:", result)

Output:
Enter a digit: 4
Computed value: 4936

12. Write a Python program to demonstrate the use of lambda functions with map, filter,
and reduce.
lambda functions are small, anonymous functions defined using the lambda keyword. They
are often used in conjunction with functions like map(), filter(), and reduce() to write concise
and readable code.

The map() Function:


map() applies a given function to all items in an input list (or any iterable) and returns an
iterator with the results. The syntax is:
map(function, iterable, ...)

The filter() Function:


filter() constructs an iterator from elements of an iterable for which a function returns true.
The syntax is:
filter(function, iterable)

The reduce() Function:


reduce() applies a rolling computation to sequential pairs of values in a list (or any iterable)
and returns a single value. It's part of the functools module. The syntax is:
from functools import reduce
reduce(function, iterable)

from functools import reduce

# List of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Squaring each number using map()


squares = list(map(lambda x: x ** 2, numbers))
print("Squared Numbers:", squares)
# Filtering even numbers using filter()
evens = list(filter(lambda x: x % 2 == 0, numbers))
print("Even Numbers:", evens)

# Summing all numbers using reduce()


total = reduce(lambda x, y: x + y, numbers)
print("Sum of Numbers:", total)

Output
Squared Numbers: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Even Numbers: [2, 4, 6, 8, 10]
Sum of Numbers: 55

13. Write a Python program to handle a Zero Division Error exception when dividing a
number by zero.
Logic:
1. Take two numbers as input – a numerator and a denominator.
2. Try to divide the numerator by the denominator using the / operator.
3. Use a try-except block to handle the division.
4. If the denominator is zero, catch the ZeroDivisionError and print an appropriate
message.
5. Otherwise, print the result of the division.
Example:
 Input: numerator = 10, denominator = 0
 Expected Output: "Error: Cannot divide by zero!"

try:
# Taking input values
numerator = int(input("Enter numerator: "))
denominator = int(input("Enter denominator: "))

# Attempting division
result = numerator / denominator

# Printing result if no exception occurs


print("Result:", result)

except ZeroDivisionError:
print("Error: Cannot divide by zero!")

Enter numerator: 10
Enter denominator: 2
Output
Result: 5.0

Enter numerator: 10
Enter denominator: 0

Output
Error: Cannot divide by zero!

14. Write a Python program that prompts the user to input an integer and raises a Value
Error exception if the input is not a valid integer

Prompt the user to enter an integer.


Check if the input consists only of digits (for positive numbers).
Allow negative numbers by checking if the input starts with - and the remaining part consists
of digits.
If the input does not meet these conditions, raise a ValueError.
Convert the input to an integer and return it.
Handle exceptions using try-except and display an appropriate error message if the input is
invalid.

You might also like