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))
Related
I have a function that is supposed to take input, calculate the average and total as well as record count.
The bug in the code is that:
Even though I have added a try and except to catch errors, these errors are also being added to the count. How do I only count the integer inputs without making the "Invalid Input" part of the count?
Code snippet
count = 0
total = 0
avg = 0
#wrap entire function in while loop
while True:
#prompt user for input
line = input('Enter a number: ')
try:
if line == 'done':
break
print(line)
#function formulars for total, count, avg
count = int(count) + 1
total = total + int(line)
avg = total / count
except:
print('Invalid input')
continue
#print function results
print(total, count, avg)
With the above code the output for print(total, count, avg) for input i.e 5,4,7, bla bla car, done :
will be 16, 4, 5.33333333
expected output 16, 3, 5.33333333
When this line: total = total + int(line) throws an error,
The previous line count = int(count) + 1 has already ben executed, which incremented the count.
Swapping these two line should solve the problem.
Add line = int(line) before count = int(count) + 1 so the exception will be catched before count evaluated, or swap it with total:
count = 0
total = 0
avg = 0
while (line := input('Enter a number: ')) != 'done':
try:
# line = int(line)
total += int(line)
count += 1
avg = total / count
except ValueError:
print('Invalid input')
print(total, count, avg)
# Enter a number: 5
# Enter a number: 4
# Enter a number: r
# Invalid input
# Enter a number: 7
# Enter a number: done
# 16 3 5.333333333333333
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))
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)
This is my Task:
Require the user to enter their name, with only a certain name being able to trigger the loop.
Print out the number of tries it took the user before inputting the correct number.
Add a conditional statement that will cause the user to exit the program without giving the average of the numbers entered if they enter a certain input
numbers = []
number = 0
count = 0
total = 0
name = 0
while number >= 0:
number = int(raw_input("Please enter any number: \n"))
if number == -1:
break
numbers.append(number)
avg = float(sum(numbers)) / len(numbers)
print "The average of the numbers you entered is " + str(avg) + "!"
while name >= 0:
name = int(raw_input("Please enter the number of characters your name contains: \n"))
count += 1
total += count
if name == 6:
break
tries = sum(total)
print tries
tries = sum(total)... sum takes an iterable whereas total is an int hence the error.
If total = [ ]
and you can append count values in total that would be fine.
so total.append(count)
would create list then you can use sum(total) on it
but here you can simply use print total or count both are same.
numbers = []
number = 0
count = 0
total = 0
name = 0
while number >= 0:
number = int(raw_input("Please enter any number: \n"))
if number == -1:
break
numbers.append(number)
avg = float(sum(numbers)) / len(numbers)
print "The average of the numbers you entered is " + str(avg) + "!"
while name >= 0:
name = int(raw_input("Please enter the number of characters your name contains: \n"))
count += 1
total += count
if name == 6:
break
tries = total
print tries
and you try to reduce your code.
How to complete my 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.
count = 0
total = 0
while True:
x = raw_input('Enter number')
x=int(x)
total = total + x
count = count + 1
average = total / count
print total, count, average
The following code should be what you want.
count = 0
total = 0
while True:
x = raw_input('Enter number: ')
if(x.lower() == "done"):
break
else:
try:
x=int(x)
total = total + x
count = count + 1
average = total / count
except:
print("That is not an integer. Please try again.")
print total, count, average
or in Python 3
count = 0
total = 0
while True:
x = input('Enter number: ')
if(x.lower() == "done"):
break
else:
try:
x=int(x)
total = total + x
count = count + 1
average = total / count
except:
print("That is not an integer. Please try again.")
print(total, count, average)