I am trying to run a while loop in python. I can get most of it to function correctly but parts of the code are not working correctly and I have been trying different methods to solve it but I can't get it to do exactly what I want.
I am trying to write a program that 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
Here is my code:
total=0
number=None
count=0
while True:
num=raw_input('Enter a number: ')
print 'Enter a number',num
for intervar in num:
count=count+1
if num=='done':
break
else:
try:
number=int(num)
if number is int:
continue
except:
print 'bad data'
total=total+number
print 'Enter a number:',number
print 'Total is',total
print 'Count is',count
When I enter 3,4,5 The output from this code is:
Enter a number 3
Enter a number 4
Enter a number 5
Enter a number nine
bad data
Enter a number done
Enter a number: 5
Total is 5
Count is 12
The code should read
Enter a number 3
Enter a number 4
Enter a number 5
Enter a number bad data
Enter a number done
Total is 12
Count is 3
Here is your code rearranged a bit:
total=0
count=0
while True:
num=raw_input('Enter a whole number: ')
try:
# just try to convert it
number=int(num)
# success -> accumulate
total += number
count += 1
except ValueError:
# if it isn't an integer, maybe they're done
if num.lower() == 'done':
break
else:
print 'bad data'
print 'Total is',total
print 'Count is',count
And here is an alternative
# keep all the numbers in a list for use later
numbers = list()
while True:
num=raw_input('Enter a whole number: ')
try:
# just try to convert it
numbers.append(int(num))
except ValueError:
# if it isn't an integer, maybe they're done
if num.lower() == 'done':
break
else:
print 'bad data'
print 'Total is', sum(numbers)
print 'Count is', len(numbers)
You've got at least three remaining problems, here
Problem 1
for intervar in num:
count=count+1
At this point num is a string and you are iterating over the characters in that string, incrementing count. The for loop is essentially equal to
count += len(num)
Do you want to count all inputs or only the correctly entered numbers?
Problem 2
The indentation of
total=total+number
is wrong. It must be inside the while loop. Also, use += when adding to a variable.
Problem 3
The is operator compares the object identities of two objects. In this case, the comparison is true, iff number is the class int
if number is int:
continue
What you want is:
if isinstance(number, int):
[...]
However, that is redundant, since after number = int(num) number is always an int.
Use a list to track the numbers, perform calculations at the end of the input session.
numbers = []
while True:
input = raw_input('Enter a whole number: ')
try:
numbers.append(int(input))
except ValueError:
if input is not None and input.lower() == 'done':
break
else:
print 'Invalid input.'
length = len(numbers)
total = sum(numbers)
average = total/count
print 'Total is', total
print 'Count is', length
print 'Average is', average
what you want to do is fix your increment for the total count
total=0
number=None
count=0
while True:
input = raw_input('Enter a whole number: ')
try:
number=int(input)
total += number
except:
if input.lower() == 'done':
break
else:
print 'bad data'
continue
count += 1
print 'Total is',total
print 'Count is',count
print 'Average is', total/count
notice I changed your variable name from num to input since its not always a number... also your check for the type of number was incorrect so I changed that too.. you only want to increment when its a number so I put that in the try... also your count i changed to not loop over all of the characters inputted but rather just count 1 for each time they enter something
an even better way would be to write a number check function
total=0
number=None
count=0
def check_int(str):
if str[0] in ('-', '+'):
return str[1:].isdigit()
return str.isdigit()
while True:
input = raw_input('Enter a whole number: ')
if check_int(input):
total += int(input)
count += 1
elif input.lower() == 'done':
break
else:
print 'bad data'
continue
print 'Total is',total
print 'Count is',count
print 'Average is', total/count
the benefit of this drops the need for a try/except which has considerable overhead
here is the code that prints your expected output.
you had an indentation error and too many prints.
total = 0
number = None
count = 0
while True:
num = raw_input('Enter a number: ')
if num == 'done':
break
else:
try:
number = int(num)
if number is int:
continue
except:
print 'bad data'
count += 1
total += number
print 'Total is',total
average = float(total)/float(count)
print 'average for %s is %s'%(count, average)
Related
the conditions are:
Repeatedly reads numbers until the user enters 'done'. Once 'done' is entered, break out of the loop.
If the user enters anything but a number, capture the error using a try-except construct and display the message "Bad Data"
Once 'done' is entered print out one of 2 messages:
If the total is greater or equal to 200 then:
"The total (the value in the total variable) for the numbers entered is Large"
If the total is less than 200 then:
"The total (the value in the total variable) for the numbers entered is Small"
count = 0
while count <= 200:
x = int(input('Please enter a number to add: '))
count = count + x
if x >= 200:
print('The total', count, 'for the number entered is Large')
break
elif x == 'done':
print ('The total',count,'for the number entered is Small')
break
elif x == ValueError:
print('Bad Data')
continue
Im a beginner so a little help would be cool.
When you accept the input value you need to check if it is a number before you try to convert it to an int. So you have two ways of doing this: either wrap the first line in a try except block to catch the value error or just check to see if the input they supply is actually a number. Also as Tim Roberts said above you can't check for "done" if you have already converted to an integer so that's why I have moved that check to the top of each example.
Version 1 (Try Except):
count = 0
while count <= 200:
user_input = input('Please enter a number to add: ')
if user_input.lower() == 'done':
print('The total', count, 'for the number entered is Small')
break
try:
x = int(user_input)
except ValueError:
print('Bad Data')
continue
count = count + x
if x >= 200:
print('The total', count, 'for the number entered is Large')
break
Version 2 (Check if number):
count = 0
while count <= 200:
user_input = input('Please enter a number to add: ')
if user_input.lower() == 'done':
print('The total', count, 'for the number entered is Small')
break
if user_input.isnumeric():
x = int(user_input)
else:
print('Bad Data')
continue
count = count + x
if x >= 200:
print('The total', count, 'for the number entered is Large')
break
PS. Adding the .lower() to the user_input allows them to type 'done' or 'DONE' or any combination of uppercase and lowercase and it will still exit.
I have edited your code a little bit. It might help you to understand the logic.
total = 0
while True:
userInput = input('Please enter a number to add: ')
if userInput == "done":
break
try:
x = int(userInput)
total += x
if total >= 200:
print('The total', total, 'for the number entered is Large')
elif total <= 200:
print ('The total',total,'for the number entered is Small')
except:
print("Bad Data")
A few notes. I have changed the count name to total since the logic of your problem seems to be closer to this name.
Output
Please enter a number to add: I am inputting bad data
Bad Data
Please enter a number to add: 100
The total 100 for the number entered is Small
Please enter a number to add: 0
The total 100 for the number entered is Small
Please enter a number to add: 50
The total 150 for the number entered is Small
Please enter a number to add: 30
The total 180 for the number entered is Small
Please enter a number to add: -50
The total 130 for the number entered is Small
Please enter a number to add: done
write a program that repeatedly read numbers until the user enters "done". Once "done" is entered, print out the total, count, and average numbers. if the user enters anything other than number, 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
""" """Approach1 """
Number = input(Enter a number: )
count = 0
total = 0
average = 0
try:
number = float(Number)
except ValueError:
print('Invalid input')
quit()
while True: # Stays in loop until break
number = input('Enter a number: ')
if number == 'done':
break # Exits the while loop
number = check_for_float(input_number)
for a number in Number:
count = count + 1
total = total + 1
average = number / count
print("Total:", total , "Count:", count, "Average: ", average)
After running this program, I was expecting an input box to pop and ask for input value which is not happening. Please advise.
I am completing questions from a python book when I came across this question.
Write a program which repeatedly reads numbers until the user enters "done". Once done is entered, print out total, count, and average of the numbers.
My issue here is that I do not know how to check if a user specifically entered the string 'done' while the computer is explicitly checking for numbers. Here is how I approached the problem instead.
#Avg, Sum, and count program
total = 0
count = 0
avg = 0
num = None
# Ask user to input number, if number is 0 print calculations
while (num != 0):
try:
num = float(input('(Enter \'0\' when complete.) Enter num: '))
except:
print('Error, invalid input.')
continue
count = count + 1
total = total + num
avg = total / count
print('Average: ' + str(avg) + '\nCount: ' + str(count) + '\nTotal: ' + str(total))
Instead of doing what it asked for, let the user enter 'done' to complete the program, I used an integer (0) to see if the user was done inputting numbers.
Keeping your Try-Except approach, you can simply check if the string that user inputs is done without converting to float, and break the while loop. Also, it's always better to specify the error you want to catch. ValueError in this case.
while True:
num = input('(Enter \'done\' when complete.) Enter num: ')
if num == 'done':
break
try:
num = float(num)
except ValueError:
print('Error, invalid input.')
continue
I think a better approach that would solve your problem would be as following :
input_str = input('(Enter \'0\' when complete.) Enter num: ')
if (input_str.isdigit()):
num = float(input_str)
else:
if (input_str == "done"):
done()
else:
error()
This way you control cases in which a digit was entered and the cases in which a string was entered (Not via a try/except scheme).
I'm trying to write a 'while' loop that takes a users input, if it is a number it remembers it, if it is a blank space it breaks. At the end it should print the average of all entered numbers. This is giving me the error 'could not convert string to float: '. What exactly is wrong here? Thanks!
EDIT: I re-wrote it like this and I get the same error about converting, but it seems to be on the final (count += 1) line?
number = 0.0
count = 0
while True:
user_number = input('Enter a number: ')
if user_number == ' ':
break
print (number / count)
number = number + float(user_number)
count += 1
My guess is that you directly hit enter when you don't want to pass numbers anymore. In that case, comparing with a space is incorrect.
number = 0.0
count = 0
while True:
user_number = input('Enter a number: ')
if user_number == '':
break
number += float(user_number)
count += 1
print (number / count)
Also a statement after a break is unreachable.
If you want a cleaner alternative, I would recommend appending to a list, and then computing the average. This removes the need for a separate counter. Try this:
numbers = []
while True:
user_number = input('Enter a number: ')
if user_number == '':
break
numbers.append(float(user_number))
print (sum(numbers) / len(numbers))
Additionally, you could remove the need for a break by testing in the head of while, but you'll need to take an additional input outside the loop.
You should change the order, right now you try to convert everything into floats, even blank spaces.
while True:
user_number = input('Enter a number: ')
if not user_number.isdigit():
print (number / count)
break
count += 1
number = number + float(user_number)
Additionally, you should do the print of the average value before the break.
I changed your if condition to break if any input except a number is entered, it should be a bit more general than before.
Change order and it should solve the problem, you should first check is enterned input is string or not then go to number part
#!/usr/bin/python
number = 0.0
count = 0
while True:
user_number = raw_input('Enter a number: ')
if user_number == (' '):
print (number / count)
break
number = number + float(user_number)
count += 1
This should work for you.
lst= []
while True:
user_number = input('Enter a number: ')
if user_number == ' ':
break
lst.append(int(user_number))
print(int(user_number))
print("Average : " + str(sum(lst)/len(lst)))
This code works correctly.
I think you are giving Other than space as input to break.
number = 0.0
count = 0
while True:
user_number = input('Enter a number: ')
if user_number == ' ':
break
print (number / count)
number = number + float(user_number)
count += 1
or else use below code:
--> Break will be triggered for non-digit input.
number = 0.0
count = 0
while True:
user_number = input('Enter a number: ')
if not user_number.isdigit():
break
number = number + float(user_number)
count += 1
print("user_number", number)
print("Count", count)
print (number / count)
I'm kind of new to coding in Python and I'm trying to write a loop that asks for numerical input and reads it until the user inputs "done", where it will then exit the loop and print the variables: number, count and average. (not trying to store anything in a list)
I also want it to print "invalid input" and continue the loop if the user enters anything that isn't an integer, unless its "done".
Unfortunately it returns "invalid input" and keeps looping even when I enter "done". What am I doing wrong? Could anyone point me in the right direction?
number = 0
count = 0
avg = 0
inp = 0
while True:
try:
inp = int(raw_input('Enter a number: '))
if inp is 'done':
number = number + inp
count = count + 1
avg = float(number/count)
break
except:
print 'Invalid input'
print number
print count
print float(avg)
sum = 0.0
count = 0
while True:
inp = raw_input('Enter a number: ')
if inp == 'done':
break
try:
sum += int(inp)
count += 1
except ValueError:
print 'Invalid input'
print sum
print count
if count != 0: # Avoid division by zero
print sum / count