ByteBoard Notes Notes

Write a function that returns the maximum, minimum and mean of a list

Computer Science XII · Experiment 03 of 29 · Python

12-CSPython programs
Expt. No.03
Page No.6

Returning multiple values

Aim

To write a Python program with a function that takes a list of numbers and returns the largest, smallest and mean values together.

Concepts used

Algorithm

  1. Define analyse(numbers): find the largest and smallest with a loop and the mean as total ÷ count.
  2. Return the three values separated by commas.
  3. Input the numbers into a list.
  4. Unpack the returned values into three variables and display them.
  5. Also display the returned value itself and its type.

Program

# Function returning the maximum, minimum and mean of a list def analyse(numbers):    largest = numbers[0]    smallest = numbers[0]    total = 0    for x in numbers:        if x > largest:            largest = x        if x < smallest:            smallest = x        total = total + x    mean = total / len(numbers)    return largest, smallest, mean marks = []n = int(input("How many numbers? "))for i in range(n):    marks.append(int(input("Enter a number: "))) big, small, avg = analyse(marks)print("Largest:", big, " Smallest:", small, " Mean:", avg) result = analyse(marks)print("Value returned:", result, type(result))

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python returning_multiple_values.py
How many numbers? 5 Enter a number: 67 Enter a number: 82 Enter a number: 45 Enter a number: 91 Enter a number: 73 Largest: 91 Smallest: 45 Mean: 71.6 Value returned: (91, 45, 71.6) <class 'tuple'>

✓ Printed by running this program, not typed by hand.

Result

For 67, 82, 45, 91 and 73 the function returned 91, 45 and 71.6. Printed directly, the returned value was the tuple (91, 45, 71.6).

Viva voce: what the examiner may ask

01How can a function return more than one value?

By writing them separated by commas after return; Python packs them into a tuple.

02What is unpacking?

Assigning the items of a tuple to several variables at once, as in big, small, avg = analyse(marks).

03What happens if the number of variables does not match the number of returned values?

Python raises ValueError (too many or not enough values to unpack).

Variations for the lab test

  1. Also return the range (largest − smallest).
  2. Return the count of numbers above the mean.
  3. Write a function that returns both the quotient and the remainder of two numbers.
! Common mistake Writing two return statements, return largest then return smallest: the function stops at the first one, so the second never runs.
Back to the 12-CS index