Average and Sums Task - python

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 Numbers\n")
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?

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 Numbers\n")
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

This one is working for me.
sum_result = 0
print("Please Enter 10 Numbers\n")
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:
Check the conventions for name variables in python, you are using builtin functions, which can be an issue in your code.
When you are dealing with user inputs, usually you need error handling, so try, except, else, finally, are the way to go.
When you have a code similar to this use, you normally name a function to do these tasks.

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

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)

from statistics import mean
i=0
number_list = []
while i <= 9:
num = input("Please Enter 10 Numbers\n")
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))

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)))

Related

Loop and check if integer

I have an exercise:
Write code that asks the user for integers, stops loop when 0 is given.
Lastly, adds all the numbers given and prints them.
So far I manage this:
a = None
b = 0
while a != 0:
a = int(input("Enter a number: "))
b = b + a
print("The total sum of the numbers are {}".format(b))
However, the code needs to check the input and give a message incase it is not an integer.
Found that out while searching online but for the life of me I cannot combine the two tasks.
while True:
inp = input("Input integer: ")
try:
num = int(inp)
except ValueError:
print('was not an integer')
continue
else:
total_sum = total_sum + num
print(total_sum)
break
I suspect you need an if somewhere but cannot work it out.
Based on your attempt, you can merge these two tasks like:
a = None
b = 0
while a != 0:
a = input("Enter a number: ")
try:
a = int(a)
except ValueError:
print('was not an integer')
continue
else:
b = b + a
print("The total sum of the numbers are {}".format(b))
If you want to use an If-Statement, you don't need the else: If the number is not 0 it will just start again until it's 0 sometime.
total_sum = 0
while True:
inp = input("Input integer: ")
try:
num = int(inp)
except ValueError:
print('was not an integer')
continue
total_sum = total_sum + num
if num == 0:
print(total_sum)
break
Since input's return is a string one can use isnumeric no see if the given value is a number or not.
If so, one can convert the string to float and check if the given float is integer using, is_integer.
a = None
b = 0
while a != 0:
a = input("Enter a number: ")
if a.isnumeric():
a = float(a)
if a.is_integer():
b += a
else:
print("Number is not an integer")
else:
print("Given value is not a number")
print("The total sum of the numbers are {}".format(b))

AttributeError: 'str' object has no attribute 'list'

We have to find out the average of a list of numbers entered through keyboard
n=0
a=''
while n>=0:
a=input("Enter number: ")
n+=1
if int(a)==0:
break
print(sum(int(a.list()))/int(n))
You are not saving the numbers entered. Try :
n = []
while True:
a=input("Enter number: ")
try: #Checks if entered data is an int
a = int(a)
except:
print('Entered data not an int')
continue
if a == 0:
break
n.append(a)
print(sum(n)/len(n))
Where the list n saves the entered digits as a number
You need to have an actual list where you append the entered values:
lst = []
while True:
a = int(input("Enter number: "))
if a == 0:
break
else:
lst.append(a)
print(sum(lst) / len(lst))
This approach still has not (yet) any error management (a user enters float numbers or any nonsense or zero at the first run, etc.). You'd need to implement this as well.
a needs to be list of objects to use sum, in your case its not. That is why a.list doens't work. In your case you need to take inputs as int (Can be done like: a = int(input("Enter a number")); ) and then take the integer user inputs and append to a list (lets say its name is "ListName")(listName.append(a)), Then you can do this to calculate the average:
average = sum(listName) / len(listName);
def calc_avg():
count = 0
sum = 0
while True:
try:
new = int(input("Enter a number: "))
if new < 0:
print(f'average: {sum/count}')
return
sum += new
count += 1
print(f'sum: {sum}, numbers given: {count}')
except ValueError:
print("That was not a number")
calc_avg()
You can loop, listen to input and update both s (sum) and c (count) variables:
s, c = 0, 0
while c >= 0:
a = int(input("Enter number: "))
if a == 0:
break
else:
s += a
c += 1
avg = s/c
print(avg)

How do I use a Try and Exception to raise an error with a print message in Python?

I'm trying to run a collatz in Python and I'm having trouble taking into account input that isn't an integer. I would like to have a Try and Except to work within my code that considers the user's non-integer input. Please see my code below.
number = int(input("Please enter a number: "))
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
print(number * 3 + 1)
return number * 3 + 1
while number != 1:
try:
number = collatz(int(number))
except ValueError:
print("Something went wrong, please try again...")
You are not using the try except when you are calling int on the input, which is why it is still erroring. You should use 2 while loops like this:
number = input("Please enter a number: ")
while not number.isdigit():
number = input("Please enter a number again: ")
number = int(number)
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
print(number * 3 + 1)
return number * 3 + 1
With try-except (in this case don't include the initial stuff in the other solution):
while True:
try:
number = int(input("Please enter a number: "))
break
except:
pass

Simple python iteration exercise..stuck with try and except

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.
This is what I have.
total = 0
count = 0
average = 0
while True:
number = input("Enter a number:")
if number == "done":
break
try:
total += numbers
count += 1
average = total / len(number)
except:
print ("Invalid input")
continue
print (total, count, average)
When I run this, I always get invalid input for some reason. My except part must be wrong.
EDIT:
This is what I have now and it works. I do need, however, try and except, for non numbers.
total = 0
count = 0
average = 0
while True:
number = input("Enter a number:")
if number == "done":
break
total += float(number)
count += 1
average = total / count
print (total, count, average)
I think I got it?!?!
total = 0
count = 0
average = 0
while True:
number = input("Enter a number:")
try:
if number == "done":
break
total += float(number)
count += 1
average = total / count
except:
print ("Invalid input")
print ("total:", total, "count:", count, "average:", average)
Should I panic if this took me like an hour?
This isn't my first programming language but it's been a while.
I know this is old, but thought I'd throw my 2-cents in there (since I myself many years later am using the same examples to learn). You could try:
values=[]
while True:
A=input('Please type in a number.\n')
if A == 'done':
break
try:
B=int(A)
values.append(B)
except:
print ('Invalid input')
total=sum(values)
average=total/(len(values))
print (total, len(values), average)
I find this a tad cleaner (and personally easier to follow).
The problem is when you try to use your input:
try:
total += numbers
First, there is no value numbers; your variable is singular, not plural. Second, you have to convert the text input to a number. Try this:
try:
total += int(number)
It's because there is no len(number) when number is an int. len is for finding the length of lists/arrays. you can test this for yourself by commenting out the try/except/continue. I think the code below is more what you are after?
total = 0
count = 0
average = 0
while True:
number = input("Enter a number:")
if number == "done":
break
try:
total += number
count += 1
average = total / count
except:
print ("Invalid input")
continue
print (total, count, average)
note there are still some issues. for example you literally have to type "done" in the input box in order to not get an error, but this fixes your initial problem because you had len(number) instead of count in your average. also note that you had total += numbers. when your variable is number not numbers. be careful with your variable names/usage.
A solution...
total = 0
count = 0
average = 0
while True:
number = input("Enter a number:")
if number == "done":
break
else:
try:
total += int(number)
count += 1
average = total / count
except ValueError as ex:
print ("Invalid input")
print('"%s" cannot be converted to an int: %s' % (number, ex))
print (total, count, average)
Problems with your code:
total+=numbers # numbers don't exist; is number
len(number) # number is a string. for the average you need count
if is not done, else process it
Use try ... except ValueError to catch problem when convert the number to int.
Also, you can use try ... except ValueError as ex to get an error message more comprehensible.
So, after several attempts, I got the solution
num = 0
count = 0
total = 0
average = 0
while True:
num = input('Enter a number: ')
if num == "done":
break
try:
float(num)
except:
continue
total = total + float(num)
count = count + 1
average = total / count
print(total, count, average)
Old problem with Update solutions
num = 0
total = 0.0
while True:
number = input("Enter a number")
if number == 'done':
break
try :
num1 = float(number)
except:
print('Invailed Input')
continue
num = num+1
total = total + num1
print ('all done')
print (total,num,total/num)
Write and Run picture
Covers all error and a few more things. Even rounds the results to two decimal places.
count = 0
total = 0
average = 0
print()
print('Enter integers and type "done" when finished.')
print('Results are rounded to two decimals.')
while True:
inp = input("Enter a number: ")
try:
if count >= 2 and inp == 'done': #only breaks if more than two integers are entered
break
count = count + 1
total += float(inp)
average = total / count
except:
if count <=1 and inp == 'done':
print('Enter at least 2 integers.')
else:
print('Bad input')
count = count - 1
print()
print('Done!')
print('Count: ' , count, 'Total: ' , round(total, 2), 'Average: ' , round(average, 2))

If statement for number in a range

I cannot tweak this for it to only respond to a value between 1 and 100. I know its somthing simple, but cannot find anything through searching that works.
while True:
Mynumber = raw_input('Enter number of random points')
if Mynumber == '0 < 100':
print 'number choosen'
Mynumber = int(Mynumber)
break
if 1 <= my_number <= 100:
Or, since you are grabbing from raw_input and have to convert to int from unknown string first:
try:
my_number = int(raw_number)
except ValueError:
print "%s not an integer value." % raw_number
else:
if 1 <= raw_number <= 100:
Though on further analysis, it looks like you are trying to do:
base_prompt = 'Enter number of random points'
user_input = raw_input(base_prompt)
while True:
try:
input_number = int(user_input)
except ValueError:
user_input = raw_input('%s not an interger\n%s' % (user_input, base_prompt))
else:
if 1 <= input_number <= 100:
break
else:
user_input = raw_input('%d out of range (1 to 100)\n%s' % (input_number, base_prompt))
If you're on Python 3.x, the following also works:
if int(my_number) in range(1, 101):
# ...
The caveat is that the end point of a range is exclusive, so it probably reads less intuitively than chained operators.

Categories