Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/env python3.2
- # -*- coding: utf-8 -*-
- # main.py
- """ Task: Exercise 5.1
- Write a program which repeatedly reads numbers until the user enters 'done'.
- Once 'done' is entered, print out the total, count, and average of the
- numbers. If the user enters anything other than a number, detect their
- mistake using try and except and print an error message and skip to the
- next number.
- Enter a number: 4
- Enter a number: 5
- Enter a number: bad data
- Invalid input
- Enter a number: 7
- Enter a number: done
- 16 3 5.33333333333
- """
- # Main
- number = None
- numbers = []
- count = 0
- total = 0
- while number != "done":
- try:
- number = input("Enter a number: ")
- if number == "done":
- break
- try:
- number = float(number)
- except ValueError:
- print("Invalid input")
- continue # skip code below
- except:
- print("Error")
- continue # skip code below
- numbers.append(number) # appends the number at the end of a list 'numbers'
- count += 1
- # Calculate total
- for num in numbers:
- total += num
- # Calculate average
- average = total / count
- print(str(total) + " " + str(count) + " " + str(average))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement