Practice set 5
1. Create a list containing several strings. Take input from the
user (search string); display whether entered string is
available in the list or not.
list_of_strings = ["apple", "banana", "orange", "grape", "kiwi"]
search_string = input("Enter a string to search for in the list: ")
if search_string in list_of_strings:
print("The entered string is available in the list.")
else:
print("The entered string is not available in the list.")
Output:
Enter a string to search for in the list: banana
The entered string is available in the list.
Enter a string to search for in the list: pomogranet
The entered string is not available in the list.
2. Accept the string from the user; display the message whether
the entered string is palindrome
or not.
# Accept input from user
string = input("Enter a string: ")
# Check if the string is a palindrome
if string == string[::-1]:
print("The entered string is a palindrome.")
else:
print("The entered string is not a palindrome.")
Output:
Enter a string: atmiya
The entered string is not a palindrome.
Enter a string: eye
The entered string is a palindrome.
3. Accept the string from the user; display the string in the
reverse order.
# Accept input from the user
user_input = input("Enter a string: ")
# Display the string in reverse order
reverse_string = user_input[::-1]
print("Reverse string:", reverse_string)
Output:
Enter a string: atmiya university
Reverse string: ytisrevinu ayimta
4. Accept the string from the user; allow user to choose from
the following options and perform
the task as per user’s choice.
i). Convert to the upper case,
ii). Convert to the lower case,
iii).Convert to the swap case,
iv). Convert to the title case
# Accept input from user
string = input("Enter a string: ")
# Display options to the user
print("Choose an option:")
print("1) Convert to the upper case")
print("2) Convert to the lower case")
print("3) Convert to the swap case")
print("4) Convert to the title case")
# Accept user's choice
choice = input("Enter your choice (1/2/3/4): ")
# Perform task based on user's choice
if choice == '1':
print("Upper case:", string.upper())
elif choice == '2':
print("Lower case:", string.lower())
elif choice == '3':
print("Swap case:", string.swapcase())
elif choice == '4':
print("Title case:", string.title())
else:
print("Invalid choice. Please choose from 1,2,3 or 4.")
Output:
Enter a string: hello studentsssss
Choose an option:
1) Convert to the upper case
2) Convert to the lower case
3) Convert to the swap case
4) Convert to the title case
Enter your choice (1/2/3/4): 1
Upper case: HELLO STUDENTSSSSS
Enter your choice (1/2/3/4): 2
Lower case: hello studentsssss
Enter your choice (1/2/3/4): 3
Swap case: HELLO STUDENTSSSSS
Enter your choice (1/2/3/4): 4
Title case: Hello Studentsssss
5. Allow users to enter multiple strings in the list; arrange
the entered string into alphabetical order and display.
# Accept multiple strings from the user
strings = input("Enter multiple strings separated by spaces:
").split()
# Sort the list in alphabetical order
strings.sort()
# Display the sorted list
print("Sorted strings:")
for string in strings:
print(string)
Output:
Enter multiple strings separated by spaces: HELLO STUDENTS , WELCOME
TO MCA , IN ATMIYA UNIVERSITY
Sorted strings:
,
,
ATMIYA
HELLO
IN
MCA
STUDENTS
TO
UNIVERSITY
WELCOME
6. Create a tuple and display it. Enter 25 at the third position
and display it again.
# Create a tuple
my_tuple = (10, 15, 20)
# Display the tuple
print(my_tuple)
# Update the tuple with 25 at the third position
my_tuple = my_tuple[:2] + (25,) + my_tuple[2:]
# Display the updated tuple
print(my_tuple)
Output:
(10, 15, 20)
(10, 15, 25, 20)
7. Create a dictionary named library with following keys
(Bookid, Title, Author, Price, Publisher).
a. Display the dictionary,
b. Display the name of Author,
c. Display the Bookid
d. Display the length of the dictionary,
e. Update the price,
f. Insert year as the new key
and display the dictionary again.
library = {"Bookid": 1234, "Title": "Python Programming", "Author":
"John Smith", "Price": 25.99, "Publisher": "Penguin"}
print(library)
print("Author:", library["Author"])
print("Bookid:", library["Bookid"])
print("Length of dictionary:", len(library))
library["Price"] = 29.99
library["Year"] = 2022
print(library)
Output:
{'Bookid': 1234, 'Title': 'Python Programming', 'Author': 'John
Smith', 'Price': 25.99, 'Publisher': 'Penguin'}
Author: John Smith
Bookid: 1234
Length of dictionary: 5
{'Bookid': 1234, 'Title': 'Python Programming', 'Author': 'John
Smith', 'Price': 29.99, 'Publisher': 'Penguin', 'Year': 2022}
8. Create a numeric array and perform following operations on it: Add
2 to each elements,Subtract 3 from each element, Multiply each element
with 3, Divide each element by 2, Find max and min, find the average
of all elements.
from numpy import*
a=array([7,8,2,6,4,5,9])
print(a)
print("After adding 2 to each element updated values are:",a+2)
print("After subtrscting 3 element updated values are:",a-3)
print("After a multiplying 3 to each element updated values are:",a*3)
print("After dividing 2 to each element updated values are:",a/2)
print("Maximum element:",max(a))
print("Minimum element:",min(a))
print("Average:",average(a))
Output:
[7 8 2 6 4 5 9]
After adding 2 to each element updated values are: [ 9 10 4 8 6 7
11]
After subtrscting 3 element updated values are: [ 4 5 -1 3 1 2 6]
After a multiplying 3 to each element updated values are: [21 24 6 18
12 15 27]
After dividing 2 to each element updated values are: [3.5 4. 1. 3.
2. 2.5 4.5]
Maximum element: 9
Minimum element: 2
Average: 5.857142857142857
9. Create a numeric array and do the following: append the element,
pop the element, insert an element at the desired postion, reverse the
elements in the array, convert the array to list.
numeric_array = [1, 2, 3, 4, 5]
numeric_array.append(6)
print(numeric_array)
numeric_array.pop()
print(numeric_array)
numeric_array.insert(2, 10)
print(numeric_array)
numeric_array.reverse()
print(numeric_array)
numeric_list = list(numeric_array)
print(numeric_list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5]
[1, 2, 10, 3, 4, 5]
[5, 4, 3, 10, 2, 1]
[5, 4, 3, 10, 2, 1]
10. Accept numeric elements from the user, store it to the array and
display. Ask user to enter search element. Display the position of the
searched element.
# Accepting numeric elements from the user and storing it in an array
array = []
n = int(input("Enter the number of elements in the array: "))
for i in range(n):
num = int(input("Enter element: "))
array.append(num)
# Displaying the array
print("Array:", array)
# Asking user to enter search element
search_element = int(input("Enter the element to search: "))
# Displaying the position of the searched element
if search_element in array:
print("Position of", search_element, "in array is:",
array.index(search_element))
else:
print(search_element, "not found in array")
Output:
Enter the number of elements in the array: 6
Enter element: 21
Enter element: 36
Enter element: 48
Enter element: 92
Enter element: 67
Enter element: 81
Array: [21, 36, 48, 92, 67, 81]
Enter the element to search: 94
94 not found in array
11. Take two arrays enter 5 digits in both arrays. Compare the
corresponding element from each array and display only the bigger
number.
from numpy import *
a=array([1,5,6,7,8])
a2=array([4,8,9,7,4])
c=where(a>a2,a,a2)
print(c)
Output:
[4 8 9 7 8]
12. Accept dimension of the array and its values from the user, create
an array as desired.
# Accepting dimensions and values from the user
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
# Creating an empty array
array = []
# Accepting values for the array
for i in range(rows):
row = []
for j in range(cols):
value = int(input(f"Enter the value for row {i+1} column
{j+1}: "))
row.append(value)
array.append(row)
# Displaying the created array
print("Array:")
for row in array:
print(row)
Output:
Enter the number of rows: 5
Enter the number of columns: 2
Enter the value for row 1 column 1: 15
Enter the value for row 1 column 2: 68
Enter the value for row 2 column 1: 49
Enter the value for row 2 column 2: 85
Enter the value for row 3 column 1: 15
Enter the value for row 3 column 2: 21
Enter the value for row 4 column 1: 45
Enter the value for row 4 column 2: 54
Enter the value for row 5 column 1: 54
Enter the value for row 5 column 2: 98
Array:
[15, 68]
[49, 85]
[15, 21]
[45, 54]
[54, 98]
13. Create a function to calculate the simple interest.
def calculate_simple_interest(principal, rate, time):
# Calculate simple interest formula: P * R * T
interest = principal * rate * time
return interest
# Test the function with sample data
principal = 1000
rate = 0.05
time = 2
interest = calculate_simple_interest(principal, rate, time)
print("Simple Interest:", interest)
Output:
Simple Interest: 100.0
14. Create a function to perform basic arithmetic operations on the
number.
def arithmetic_operation(num1, num2, operation):
if operation == '+':
return num1 + num2
elif operation == '-':
return num1 - num2
elif operation == '*':
return num1 * num2
elif operation == '/':
if num2 != 0:
return num1 / num2
else:
return "Cannot divide by zero"
else:
return "Invalid operation"
# Example usage
result = arithmetic_operation(10, 5, '+')
print(result) # Output: 15
result = arithmetic_operation(10, 5, '-')
print(result) # Output: 5
result = arithmetic_operation(10, 5, '*')
print(result) # Output: 50
result = arithmetic_operation(10, 5, '/')
print(result) # Output: 2.0
result = arithmetic_operation(10, 0, '/')
print(result) # Output: Cannot divide by zero
result = arithmetic_operation(10, 5, '^')
print(result) # Output: Invalid operation
Output:
15
5
50
2.0
Cannot divide by zero
Invalid operation
15. Accept multiple strings and store it into the list using function.
def store_strings(*args):
string_list = []
for string in args:
string_list.append(string)
return string_list
strings = store_strings("hello", "world", "python")
print(strings)
Output:
['hello', 'world', 'python']
16. Find the biggest number from three values using lambda.
nums = [10, 5, 20]
max_num = max(nums, key=lambda x: x)
print(max_num) # Output: 20
Output:
20
17. Demonstrate the use of:
i). break and
# Using break statement to stop the loop when number is found
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number == 3:
print("Number found: ", number)
break
print("Checking number:", number)
Output:
Checking number: 1
Checking number: 2
Number found: 3
ii). Pass.
# Using pass statement to do nothing in a block of code
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number == 3:
pass
print("Number:", number)
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5