String, Int Differentiation and Looping in Python - python

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)

Related

How to only count valid inputs

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

can a condition be in range in python?

can a range have a condition in python? for example, I wanna start at position 0 but I want it to run until my while statement is fulfilled.
total = 0
num = int(input ( "Enter a number: " ))
range[0,while num != 0:]
total += num
I want to be able to save different variables being in a while loop.
The purpose of my program is to print the sum of the numbers you enter unil you put in 0
my code
num = int(input ( "Enter a number: " )) #user input
number_enterd = str() #holds numbers enterd
total = 0 #sum of number
while num != 0:
total += num
num = int(input ( "Enter a number: " ))
number_enterd = num
print( "Total is =", total )
print(number_enterd) #check to see the numbers ive collected
expected output:
enter an integer number (0 to end): 10
1+2+3+4+5+6+7+8+9+10 = 55
as of right now I'm trying to figure out how to store different variables so i can print them before the total is displayed. but since it is in a loop, the variable just keeps getting overwritten until the end.
If you want to store all the numbers you get as input, the simplest way to do that in Python is to just use a list. Here's that concept given your code, with slight modification:
num = int(input ( "Enter a number: " )) #user input
numbers_entered = [] #holds numbers entered
total = 0 #sum of number
while num != 0:
total += num
numbers_entered.append(num)
num = int(input ( "Enter a number: " ))
print("Total is = " + str(total))
print(numbers_entered) #check to see the numbers ive collected
To get any desired formatting of those numbers, just modify that last print statement with a string concatenation similar to the one on the line above it.
I used a boolean to exit out of the loop
def add_now():
a = 0
exit_now = False
while exit_now is False:
user_input = int(input('Enter a number: '))
print("{} + {} = {} ".format(user_input, a, user_input + a))
a += user_input
if user_input == 0:
exit_now = True
print(a)
add_now()
If you want to store all of the values entered and then print them, you may use a list. You code would end like this:
#number_enterd = str() # This is totally unnecessary. This does nothing
num = int(input ( "Enter a number: " ))
total = 0 #sum of number
numsEntered = [] # An empty list to hold the values we will enter
numsEntered.append(num) # Add the first number entered to the list
while num != 0:
total += num
num = int(input ( "Enter a number: " ))
#number_enterd = num # Unnecesary as well, this overwrites what you wrote in line 2
# It doesn't even make the num a string
numsEntered.append(num) #This adds the new num the user just entered into the list
print("Total is =", total )
print("Numbers entered:", numsEntered) #check to see the numbers you've collected
For example, user enters 5,2,1,4,5,7,8,0 as inputs from the num input request.
Your output will be:
>>>Total is = 32
>>>Numbers entered: [5, 2, 1, 4, 5, 7, 8, 0]
Just as a guide, this is how I would do it. Hope it helps:
num = int(raw_input("Enter a number: "))
numsEntered = [] # An empty list to hold the values we will enter
total = 0 #sum of numbers
while True:
numsEntered.append(num) #This adds the num the user just entered into the list
total += num
num = int(raw_input("Enter a number: "))
print("Total is =", total)
print("Numbers entered:", numsEntered) #check to see the numbers you've collected
In this case, the last 0 entered to get out of the loop doesn't show up. At least, I wouldn't want it to show up since it doesn't add anything to the sum.
Hope you like my answer! Have a good day :)

TypeError: 'int' object is not iterable (new beginner)

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.

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

Python code won't run?

Hello i was wondering why this code will not run,thanks.
count = 0
finished = False
total = 0
while not finished:
number = int(input("Enter a number(0 to finish)"))
if number == 0:
finished = True
else:
total = total + number
count = count + 1
print("the average is", total/ count)
count = 0
Your script is alright, you haven't indented properly the elseclause, here's a working example, also, you should cast to float your average:
count = 0
finished = False
total = 0
while not finished:
number = int(input("Enter a number(0 to finish)"))
if number == 0:
finished = True
else:
total = total + number
count = count + 1
print("the average is", float(total) / float(count))
count = 0
Another possible way to do the same with few lines would be this:
values = []
while True:
number = int(input("Enter a number(0 to finish)"))
if number == 0:
break
values.append(number)
print("the average is", float(sum(values)) / float(len(values)))
It does run, the only issue I can see is that your else is indented inside your if block. In Python, indentation is important in a way that curled brackets or keywords are important in other programming languages.
count = 0
finished = False
total = 0
while not finished:
number = int(input("Enter a number(0 to finish)"))
if number == 0:
finished = True
else:
total = total + number
count = count + 1
print("the average is", total/ count)
count = 0

Categories