
Python 101 - Lesson 3 - Chapter 5
By:
evita_gr on
Oct 10th, 2011 | syntax:
Python | size: 1.39 KB | hits: 35 | expires: Never
# 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.
total = 0
count = 0
average = 0
while count >= 0 :
input_b = raw_input('Enter a number:')
if input_b == 'done':
print int(total), count, average
break
try:
input = float(input_b)
count = count + 1
total = total + input
average = total / count
except:
print 'Invalid input'
# Exercise 5.2
# Write another program that prompts
# for a list of numbers as above and
# at the end prints out both the maximum
# and minimum of the numbers instead of the average.
number = None
numbers = []
count = 0
total = 0
maximum = None
minimum = None
while count >= 0 :
number = raw_input('Enter a number:')
if number == 'done':
break
try:
number = int(number)
count += 1
numbers.append(number)
except:
print 'Invalid number'
continue
for number in numbers:
total += number
if maximum is None or maximum < number:
maximum = number
if minimum is None or minimum > number:
minimum = number
print count, total, maximum, minimum