-1

If I wanted to add a user-friendly message that says "No mode found" if the statistics.mode does not find a mode?
The program is for analyzing statistics. Here is the code.

import statistics

list = [1, 2, 3]
print(statistics.mode(list))

Edit: This question has been solved. Thanks for the help, everyone. I fixed it by adding:

if len(list)==len(set(list)):
    print('No mode found')

My thanks to Kevin Wang for the answer.

  • What is needing this error message? Are you using a tkinter GUI, a matplotlib plot, a console output?? You need to provide code and be more specific! – Reedinationer Feb 21 '19 at 00:45

1 Answers1

0

This is called "exception handling". Python-specific docs can be found here.

For your example, you could do

import statistics

list = [1, 2, 3]
try:
  print(statistics.mode(list))
except statistics.StatisticsError:
  print('No mode found')

(Alternatively, you could be pre-emptive about checking for the lack of mode: check if all elements in a list are unique. This would amount to

import statistics

list = [1, 2, 3]
if len(list)==len(set(list)):
  print('No mode found')
else:
  print(statistics.mode(list))

)

Kevin Wang
  • 2,673
  • 2
  • 10
  • 18