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)
Related
#Develop a program that reads a four-digit integer from the user and displays the sum of the digits in the number. For example, if the user enters 3141 then your program should display 3+1+4+1=9.
ri = input("please enter four digits")
if len(ri) == 4 and ri.isnumeric() == True:
print(ri[0]+ri[1]+ri[2]+ri[3])
else:
print("Error: should be four digits!")
How do I do this? Haven't seen something like this before I'm sure, and as you can see my code fails....
ri = input("please enter four digits: ")
res = 0
for n in ri:
res += int(n)
print (ri[0]+"+"+ri[1]+"+"+ri[2]+"+"+ri[3]+"="+str(res))
ri = input("please enter four digits: ")
if len(ri) == 4 and ri.isnumeric():
print(f'{ri}={"+".join(ri)}={sum(map(int, ri))}')
else:
print("Error: should be four digits!")
please enter four digits: 3141
3141=3+1+4+1=9
Here is a one-liner for that. The length of the input doesn't matter to this one. Its up to you what to specify for the length or to take the length check away completely.
ri = input('please enter four digits:')
if len(ri) == 4 and ri.isnumeric():
print('+'.join(i for i in ri), '=', str(sum([int(a) for a in ri])))
else:
print('Error: should be four digits')
Output:
please enter four digits: 3149
3+1+4+9 = 17
ri = input("please enter some digits: ")
try:
print("Digit sum: " + str(sum([int(x) for x in ri])))
except:
raise ValueError("That was no valid number!")
For this solution, the length of the input does not matter.
Edit for better answer
input_string = input("Enter numbers")
output_string = ""
sum = 0
count = 0
for n in input_string:
if count < len(input_string)-1:
output_string += str(n) + "+"
else:
output_string += str(n) + "="
sum += int(n)
count += 1
output_string += str(sum)
print (output_string)
Output:
1+1+1+1=4
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).
Fellow python developers. I have a task which I can't seem to crack and my tutor is MIA. I need to write a program which only makes use of while loops, if, elif and else statements to:
Constantly ask the user to enter any random positive integer using int(raw_input())
Once the user enters -1 the program needs to end
the program must then calculate the average of the numbers the user has entered (excluding the -1) and print it out.
this what I have so far:
num = -1
counter = 1
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
anyNumber = int(raw_input("Enter another number: "))
counter += anyNumber
answer = counter + anyNumber
print answer
print "Good bye!"
Try the following and ask any question you might have
counter = 0
total = 0
number = int(raw_input("Enter any number: "))
while number != -1:
counter += 1
total += number
number = int(raw_input("Enter another number: "))
if counter == 0:
counter = 1 # Prevent division by zero
print total / counter
You need to add calculating average at the end of your code.
To do that, have a count for how many times the while loop runs, and divide the answer at the end by that value.
Also, your code is adding one to the answer each time because of the line - answer = counter + anyNumber, which will not result in the correct average. And you are missing storing the first input number, because the code continuously takes two inputs. Here is a fixed version:
num = -1
counter = 0
answer = 0
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
counter += 1
answer += anyNumber
anyNumber = int(raw_input("Enter another number: "))
if (counter==0): print answer #in case the first number entered was -1
else:
print answer/counter #print average
print "Good bye!"
There's another issue I think:
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
anyNumber = int(raw_input("Enter another number: "))
The value of the variable anyNumber is updated before the loop and at the beginning of the loop, which means that the first value you're going to enter is never going to be taken in consideration in the average.
A different solution, using a bit more functions, but more secure.
import numpy as np
numbers = []
while True:
# try and except to avoid errors when the input is not an integer.
# Replace int by float if you want to take into account float numbers
try:
user_input = int(input("Enter any number: "))
# Condition to get out of the while loop
if user_input == -1:
break
numbers.append(user_input)
print (np.mean(numbers))
except:
print ("Enter a number.")
You don't need to save total because if the number really big you can have an overflow. Working only with avg should be enough:
STOP_NUMBER = -1
new_number = int(raw_input("Enter any number: "))
count = 1
avg = 0
while new_number != STOP_NUMBER:
avg *= (count-1)/count
avg += new_number/count
new_number = int(raw_input("Enter any number: "))
count += 1
I would suggest following.
counter = input_sum = input_value = 0
while input_value != -1:
counter += 1
input_sum += input_value
input_value = int(raw_input("Enter any number: "))
try:
print(input_sum/counter)
except ZeroDivisionError:
print(0)
You can avoid using two raw_input and use everything inside the while loop.
There is another way of doing..
nums = []
while True:
num = int(raw_input("Enter a positive number or to quit enter -1: "))
if num == -1:
if len(nums) > 0:
print "Avg of {} is {}".format(nums,sum(nums)/len(nums))
break
elif num < -1:
continue
else:
nums.append(num)
Here's my own take on what you're trying to do, although the solution provided by #nj2237 is also perfectly fine.
# Initialization
sum = 0
counter = 0
stop = False
# Process loop
while (not stop):
inputValue = int(raw_input("Enter a number: "))
if (inputValue == -1):
stop = True
else:
sum += inputValue
counter += 1 # counter++ doesn't work in python
# Output calculation and display
if (counter != 0):
mean = sum / counter
print("Mean value is " + str(mean))
print("kthxbye")
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)
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