Exercise 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 anumber, 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.333333333333333
sum = 0
count = 0
while True:
inp_number = input("Enter a number: ")
if inp_number == "done":
break
try:
fl_number = float(inp_number)
count = count + 1
sum = sum + fl_number
average = sum / count
except:
print("Invalid input")
continue
if count == 0:
quit()
print("\n\nSum: ", sum, "\nCount: ", count, "\nAverage: ", average)
#OR
num_list = list()
while True:
inp_num = input("Enter your number: ")
if inp_num == "done":
break
try:
fl_num = float(inp_num)
except:
print("Inavlid Input!")
continue
num_list.append(fl_num)
if num_list == []:
quit()
print("Sum:", sum(num_list), "Count:", len(num_list), "Average:", sum(num_list)/len(num_list))
Exercise 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.
sum = 0
count = 0
maximum = None
minimum = None
while True:
inp_number = input("Enter a number: ")
if inp_number == "done":
break
try:
fl_number = float(inp_number)
count = count + 1
sum = sum + fl_number
if maximum is None or maximum < fl_number:
maximum = fl_number
if minimum is None or minimum > fl_number:
minimum = fl_number
except:
print("Invalid input")
continue
if count == 0:
quit()
print("\n\nSum: ", sum, "\nCount: ", count)
print("Maximum: ", maximum, "\nMinimum: ", minimum)
#OR
num_list = list()
while True:
inp_num = input("Enter your number: ")
if inp_num == "done": break
try: fl_num = float(inp_num)
except:
print("Invalid Input!")
continue
num_list.append(fl_num)
if num_list == []: quit()
if len(num_list) >= 2: print("Sum:", sum(num_list), "Count:", len(num_list), "Largest Number:", max(num_list), "Smallest Number:", min(num_list))
elif len(num_list) == 1: print("Sum:", sum(num_list), "Count:", len(num_list), "Largest Number:", max(num_list), "Smallest Number: None")