How can you extend the program to return both the largest and the smallest numbers in a list?
Answers:
To extend a program to return both the largest and the smallest numbers in a list, you can use built-in functions in Python such as
max()
andmin()
to achieve this. Below is a simple example of how you can implement such a program:def find_largest_and_smallest(numbers): if not numbers: # Check if the list is empty return None, None largest = max(numbers) # Find the largest number smallest = min(numbers) # Find the smallest number return largest, smallest # Example usage: num_list = [3, 5, 1, 9, 2, -4, 7] largest, smallest = find_largest_and_smallest(num_list) print("Largest number:", largest) print("Smallest number:", smallest)
Explanation:
- Function Definition: We defined a function
find_largest_and_smallest
that takes a list of numbers as input. - Empty List Check: We check if the list is empty to avoid errors when using
max()
andmin()
. If it is empty, we return(None, None)
. - Finding Largest and Smallest: We use the
max()
function to find the largest number and themin()
function to find the smallest number in the list. - Return Values: The function returns both the largest and smallest numbers.
- Example Usage: We created an example list, called the function, and printed the results.
This code will work correctly for any list of numbers you provide to it.
- Function Definition: We defined a function