Python 101 - Lesson 3 - Chapter 5

By: evita_gr on Oct 10th, 2011  |  syntax: Python  |  size: 1.39 KB  |  hits: 35  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1. # Exercise 5.1
2. # Write a program which repeatedly
3. # reads numbers until the user enters “done”.
4. # Once “done” is entered, print out the total,
5. # count, and average of the numbers. If the user
6. # enters anything other than a number, detect
7. # their mistake using try and except and print
9.
10. total = 0
11. count = 0
12. average = 0
13.
14. while count >= 0 :
15.   input_b = raw_input('Enter a number:')
16.   if input_b == 'done':
17.     print int(total), count, average
18.     break
19.   try:
20.     input = float(input_b)
21.     count = count + 1
22.     total = total + input
23.     average =  total / count
24.   except:
25.     print 'Invalid input'
26.
27.
28. # Exercise 5.2
29. # Write another program that prompts
30. # for a list of numbers as above and
31. # at the end prints out both the maximum
32. # and minimum of the numbers instead of the average.
33.
34. number = None
35. numbers = []
36. count = 0
37. total = 0
38.
39. maximum = None
40. minimum = None
41.
42. while count >= 0 :
43.   number = raw_input('Enter a number:')
44.   if number == 'done':
45.     break
46.   try:
47.     number = int(number)
48.     count += 1
49.     numbers.append(number)
50.   except:
51.     print 'Invalid number'
52.     continue
53.
54. for number in numbers:
55.   total += number
56.   if maximum is None or maximum < number:
57.     maximum = number
58.   if minimum is None or minimum > number:
59.     minimum = number
60.
61. print count, total, maximum, minimum