EXERCISE-2
1. Write a program to define function with multiple return values
def name():
return "john","armin"
print(name())
name_1,name_2=name()
print(name_1,name_2)
Output:
('john', 'armin')
john armin
2. Write a program to define function using default arguments
Case1:
def add_numbers(a,b):
sum=a+b
print('sum:',sum)
add_numbers(2,3)
Output:
sum:5
Case 2:
def add_numbers(a=7,b=8):
sum=a+b
print('sum:',sum)
add_numbers(2,3)
add_numbers(a=2)
add_numbers()
Output:
sum:5
sum:10
sum:15
3. Write a program to find the length of the string without using any library
functions
my_string="Hi will"
print("The string is:")
print(my_string)
my_counter=0
for i in my_string:
my_counter=my_counter+1
print("The length of the string is:")
print(my_counter)
Output:
The string is :
Hi Will
The length of the string is
7
4. Write a program to check if the substring is present in a given string or not
my_string="I love python"
print(my_string[2:6])
print(my_string[2:])
print(my_string[:-1])
Output:
love
love python
I love pytho
5. Write a program to perform the given operations on a list:
def perform_operations():
# Initial list
my_list = [10, 20, 30, 40, 50]
print("original list:",my_list)
# Addition operation
my_list.append(60)
print("after addition:",my_list)
# Insertion operation
my_list.insert(2, 25) # Insert 25 at index 2
print("after insertion:",my_list)
# Slicing operation
sliced_list = my_list[1:4] # Extract elements from index 1 to 3 (4 is excluded)
print("after sliced operation:",sliced_list)
# Execute the function
perform_operations()
Output:
original list: [10, 20, 30, 40, 50]
after addition: [10, 20, 30, 40, 50, 60]
after insertion: [10, 20, 25, 30, 40, 50, 60]
after sliced operation: [20, 25, 30]
6. write a program to perform any 5 built in functions by taking any list
def main():
# Sample list
numbers = [3, 1, 7, 4, 2, 5]
# 1. len() - Returns the length of the list
print("length:",len(numbers))
# 2. sum() - Returns the sum of all elements in the list
print("Sum of elements:",sum(numbers))
# 3. max() - Returns the maximum element in the list
print("Maximum value:",max(numbers))
# 4. min() - Returns the minimum element in the list
print("Minimum value:",min(numbers))
# 5. sorted() - Returns a sorted version of the list
print("Sorted list:",sorted(numbers))
main()
Output:
length: 6
Sum of elements: 22
Maximum value: 7
Minimum value: 1
Sorted list: [1, 2, 3, 4, 5, 7]