Advertisement
Mars83

5-1

Oct 4th, 2011
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.25 KB | None | 0 0
  1. #! /usr/bin/env python3.2
  2. # -*- coding: utf-8 -*-
  3.  
  4. # main.py
  5. """ Task: Exercise 5.1
  6.    Write a program which repeatedly reads numbers until the user enters 'done'.
  7.    Once 'done' is entered, print out the total, count, and average of the
  8.    numbers. If the user enters anything other than a number, detect their
  9.    mistake using try and except and print an error message and skip to the
  10.    next number.
  11.    Enter a number: 4
  12.    Enter a number: 5
  13.    Enter a number: bad data
  14.    Invalid input
  15.    Enter a number: 7
  16.    Enter a number: done
  17.    16 3 5.33333333333
  18. """
  19.  
  20. # Main
  21. number = None
  22. numbers = []
  23. count = 0
  24. total = 0
  25. while number != "done":
  26.     try:
  27.         number = input("Enter a number: ")
  28.         if number == "done":
  29.             break
  30.         try:
  31.             number = float(number)
  32.         except ValueError:
  33.             print("Invalid input")
  34.             continue    # skip code below
  35.     except:
  36.         print("Error")
  37.         continue    # skip code below
  38.     numbers.append(number)  # appends the number at the end of a list 'numbers'
  39.     count += 1
  40.  
  41. # Calculate total
  42. for num in numbers:
  43.     total += num
  44.  
  45. # Calculate average
  46. average = total / count
  47.  
  48. print(str(total) + " " + str(count) + " " + str(average))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement