Average and Sums Task

Question:

Basic task of making code that can find the sum & average of 10 numbers from the user.

My current situation so far:

Sum = 0
print("Please Enter 10 Numbersn")
for i in range (1,11):
    num = int(input("Number %d =" %i))
sum = Sum + num
avg = Sum / 10

However, I want to make it so that if the user inputs an answer such as "Number 2 = 1sd" it doesn’t stop the code immediately. Instead I’m looking for it to respond as "Invalid input. Try again" and then it restarts from the failed input.

e.g.

"Number 2 = 1sd"
"Invalid input. Try again."
"Number 2 = ..." 

How would I achieve that?

Asked By: bamb1

||

Answers:

You can do:

while True:
    try:
        num = int(input('Enter an integer: '))
        break
    except Exception:
        print('Invalid input')
#now num is an integer and we can proceed
Answered By: ReasonMeThis

you can check the input, then continue or return an error, something like this:

sum = 0

print('Please Enter 100 Numbers:n')
for i in range(1, 11):
    num = input('Number %d' % i)
    while not num.isdigit():
        print('Invalid input. Try again.')
        num = input('Number %d' % i)
    sum += int(num)

avg = sum / 10
print('Average is %d' % avg)
Answered By: Ali Rn

You can output an error message and prompt for re-entry of the ith number by prompting in a loop which outputs an error message and reprompts on user input error. This can be done by handling the ValueError exception that is raised when the input to the int() function is an invalid integer object string initializer such as as "1sd". That can be done by catching that exception, outputting Invalid input. Try again. and continuing when that occurs.

One possible resulting code that may satisfy your requirements is:

Sum = 0
print("Please Enter 10 Numbersn")
for i in range (1,11):
    num = None
    while num is None:
        try:
            num = int(input("Number %d =" %i))
        except ValueError:
            print('Invalid input. Try again.')
sum = Sum + num
avg = Sum / 10
Answered By: Mark A. Fitzgerald

If your data is not too much, I think put them in a list is better. Because you can easier change program to calculate others if you want.

nums = [] # a list only store valid numbers
while len(nums) < 10:
  input_n = input("Number %d = " % (len(nums) + 1))
  if input_n.isdigit():
    n = int(input_n)
    nums.append(n)
  else:
    print("Invalid input. Try again.")

# average is more commonly known as a float type. so I use %f.
print("Average = %f" % (sum(nums) / len(nums)))
Answered By: LiHS

This one is working for me.

sum_result = 0
print("Please Enter 10 Numbersn")
for i in range (1,11):
    try:
        num = int(input("Number %d =" %i))
        sum_result = sum_result + num
    except Exception:
        print("Please try again")
        num = int(input("Number %d =" %i))
        sum_result = sum_result + num
avg_result = sum_result / 10
print(sum_result)
print(avg_result)

Suggestions:

  1. Check the conventions for name variables in python, you are using builtin functions, which can be an issue in your code.
  2. When you are dealing with user inputs, usually you need error handling, so try, except, else, finally, are the way to go.
  3. When you have a code similar to this use, you normally name a function to do these tasks.
from statistics import mean

i=0

number_list = []

while i <= 9:
    num = input("Please Enter 10 Numbersn")
    if num.isdigit() ==False:
        print('Invalid input. Try again.')
        num
    else:
        number_list.append(int(num))
        i +=1

print(sum(number_list))
print(mean(number_list))
Answered By: Crackalackin
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.