Advertisement
oldmagi

Chapter 5

Sep 7th, 2012
750
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. #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.
  2. lt=[]
  3. total=0
  4. count=0
  5. avg=float()
  6. while True:
  7.     i=input('Enter a number:')
  8.     try:
  9.         if i=='done':break
  10.         if int(i)==str():continue
  11.         lt.append(i)
  12.     except:
  13.         print("bad data\ninvalid input")
  14.            
  15. for i in lt:
  16.     total+=int(i)
  17.     count+=1
  18. avg=total/count    
  19. print(total,count,format(avg,'.7g'))
  20.  
  21. ------------------------------------------------------------------------------------------------
  22. #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.
  23. ls=[]
  24. while True:
  25.     i=input("Enter a number:")
  26.     try:
  27.         if i=='done':break
  28.         if int(i)==str():continue
  29.         ls.append(i)
  30.     except:
  31.         print("Bad data\nInvalid Data")
  32. print(ls)
  33. k=0
  34. for i in ls:
  35.     if int(i)>=k:
  36.         k=int(i)
  37. l=k
  38. for i in ls:
  39.     if int(i)<=l:
  40.         l=int(i)
  41. print("Minimum:",l,"Maximum:",k)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement