Page 523 - ComputerScience_Class_11
P. 523
Program 10: Write a program to modify a dictionary inside a function by adding a new key-value pair.
Program 10.py
File Edit Format Run Options Window Help
def add_to_dict(my_dict):
my_dict['age'] = 25
person = {'name': 'Alice', 'city': 'New York'}
add_to_dict(person)
print("Modified dictionary:", person)
Output
Modified dictionary: {'name': 'Alice', 'city': 'New York', 'age': 25}
SOME MORE PROGRAMS
Program 1: Write a program to traverse a list and sum all elements using a function.
Program 1.py
File Edit Format Run Options Window Help
def sum_list_elements(my_list):
total = 0
for element in my_list:
total += element
return total
numbers = [10, 20, 30, 40, 50]
Output
sum_result = sum_list_elements(numbers)
print("Sum of the list elements:", sum_result) Sum of the list elements: 150
Program 2: Write a program to find the largest element in a list using a function.
Program 2.py
File Edit Format Run Options Window Help
def find_largest(my_list):
largest = my_list[0]
for element in my_list:
if element > largest:
largest = element
return largest
numbers = [10, 20, 4, 45, 99, 32]
largest_number = find_largest(numbers)
print("The largest element in the list is:", largest_number)
Output
The largest element in the list is: 99
For Advance Learners: Functions in Python 521

