Exercise
5.1 – Write a program which repeatedly reads numbers until the user enter
‘done’. Once ‘done’ is entered, print out the total, count, and average of the
number. If the user enters anything other then a number, detect their mistake
using try and except and print an error
total = 0 count = 0 while True: value = raw_input("Enter a number: " ) try: if value == 'done': print 'Total:' + str(total) print 'Count:' + str(count) average = total/count print 'Average:' + str(average) break x = int(value) count = count + 1 total = total + x except: print 'Invalid input'
OUTPUT
Enter a number: 5 Enter a number: 6 Enter a number: 7 Enter a number: exit Invalid input Enter a number: done Total:18 Count:3 Average:6
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.
total = 0 count = 0 largest=None smallest=None while True: value = raw_input("Etner a number: " ) try: if value == 'done': print 'Total:' + str(total) print 'Count:' + str(count) average = float(total/float(count)) print 'Average: ' + str(average) print 'Largest: ' + str(largest) print 'Smallest: ' + str(smallest) break x = float(value) count = count + 1 total = total + x if largest is None or x > largest: largest = x if smallest is None or x < smallest: smallest = x except: print 'Invalid input'
OUTPUT
Enter a number: 5 Enter a number: 6.5 Enter a number: 4.5 Enter a number: 7. Enter a number: done Total:23.0 Count:4 Average: 5.75 Largest: 7.0 Smallest: 4.5
Nema komentara:
Objavi komentar