I'm just at the beginning to learn Python.
As an exercise I wrote this little script:
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.
It does what it should in general, but: When I played with it a little I noticed one strange behavior: As it takes several (int) numbers after the prompt it won't - and shouldn't - take characters. So far so good, but then I tried a float as input. The script won't take it as valid input but would count it and put the truncated number into the total.
Code:
total = float(0) # sum of items
count = int(0) # number of items
avrg = float(0) # average of items
input_in = True
while input_in:
try:
line = input('Enter a number: ')
if line == 'done':
print('total:', str(total),' count:', str(count),' average:', str(avrg))
break
print(line)
for itervar in line:
total = total + float(itervar)
count = count+1
avrg = total / count
except:
print('Invalid input')
Output:
Enter a number: 1.5
1.5
Invalid input
Enter a number: 5
5
Enter a number: 5
5
Enter a number: 5
5
Enter a number: done
total: 16.0 count: 4 average: 4.0
What I tried - and didn't work: Assign the variables line and/or itervar as float().
I tried the included Debugger but I'm not able to understand it.
I have no clue how this could work.
Your line:
for itervar in line:
Is walking over each character of the input, which for your first input (1.5) results in three iterations:
1
.
5
So for the first iteration, your total is increased by 1, and for the second iteration, you're trying to use . as a number, and failing. (Hence why your final value, after adding 5 + 5 + 5, is 16)
Instead of using a for loop to iterate over your input, you should look into converting the entire input string into a number.
And as an added bonus...
Consider whether you actually need to be recalculating your average each loop. Since you have the total, and the count, I'd recommend instead calculating your average value on-demand, as a result of those two numbers.
As you've already figured out, input() returns a string.
When you iterate through a string with a for loop, you iterate over each character individually. This means that, when you enter '1.5', you get three iterations:
itervar = '1'
itervar = '.'
itervar = '5'
Due to how you wrote your code, the first one goes correctly, but then when it tries to convert '.' to a float, it produces an error.
Why not just consider the entire input as a whole, instead of character-by-character?
line = input('Enter a number: ')
if line == 'done':
print('total:', str(total),' count:', str(count),' average:', str(avrg))
break
print(line)
total = total + float(line)
count = count+1
avrg = total / count
Related
What I want to do, is to write a program that given a sequence of real numbers entered by the user, calculates the mean. Entering the sequence should be finished by inputting ’end’. To input more than 1 number I try:
num=input("Enter the number: ")
while num!="end":
num = input("Enter the number: ")
But I don't want the program to "forget" the first 'num', because I'll need to use it later to calculate the mean. What should I write to input and then use more than one value, but not a specific number of values? User should can enter the values until they enter 'end'. All of values need to be use later to calculate the mean. Any tip for me?
First, define an empty list.
numbers = []
Then, ask for your input in an infinite loop. If the input is "end", break out of the loop. If not, append the result of that input() to numbers. Remember to convert it to a float first!
while True:
num = input("Enter a number: ")
if num == "end":
break
numbers.append(float(num))
Finally, calculate the mean:
mean = sum(numbers) / len(numbers)
print("Mean: ", mean)
However, note that calculating the mean only requires that you know the sum of the numbers and the count. If you don't care about remembering all the numbers, you can just keep track of the sum.
total = 0
count = 0
while True:
num = input("Enter a number: ")
if num == "end":
break
total += float(num)
count += 1
print("Mean: ", total / count)
Mean is sum of all nos/total nos. Let's take input from user and add it to list, because we can easily use sum() function to find sum and len() function to find total nos. Your code:
obs=[]
while True:
num=input("Enter number: ")
if num=="end":
break
else:
obs.append(int(num))
print("Mean: ",(sum(obs)/len(obs)))
I'm trying to work out the average of numbers that the user will input. If the user inputs nothing (as in, no value at all) I want to then calculate the average of all numbers that have been input by the user upto that point. Summing those inputs and finding the average is working well, but I'm getting value errors when trying to break the loop when the user inputs nothing. For the if statement I've tried
if number == ''
First attempt that didn't work, also tried if number == int("")
if len(number) == 0
This only works for strings
if Value Error throws up same error
Full code below
sum = 0
while True :
number = int(input('Please enter the number: '))
sum += number
if number == '' :
break
print(sum//number)
Error I'm getting is
number = int(input('Please enter the number: '))
ValueError: invalid literal for int() with base 10:>
Any help much appreciated!
EDIT: Now getting closer thanks to the suggestions in that I can get past the problems of no value input but my calculation of average isn't working out.
Trying this code calculates fine but I'm adding the first input twice before I move to the next input
total = 0
amount = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
total = number + number
amount += 1
except:
break
total += number
print(total/amount)
Now I just want to figure out how I can start the addition from the second input instead of the first.
sum = 0
while True :
number = input('Please enter the number: '))
if number == '' :
break
sum += int(number)
print(sum//number)
try like this
the issue is using int() python try to convert input value to int. So, when its not integer value, python cant convert it. so it raise error. Also you can use Try catch with error and do the break.
You will always get input as a string, and if the input is not a int then you cant convert it to an int. Try:
sum = 0
while True :
number = input('Please enter the number: ')
if number == '' :
break
sum += int(number)
print(sum//number)
All of the answers dont work since the print statement referse to a string.
sum = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
except:
break
sum += number
print(sum//number)
including a user_input will use the last int as devisor.
My answer also makes sure the script does not crash when a string is entered.
The user has to always input something (enter is a character too) for it to end or you will have to give him a time limit.
You can convert character into int after you see it isn't a character or
use try & except.
sum = 0
i = 0
while True :
try:
number = int(input('Please enter the number: '))
except ValueError:
break
i += 1
sum += number
try:
print(sum/number)
except NameError:
print("User didn't input any number")
If you try to convert a character into int it will show ValueError.
So if this Error occurs you can break from the loop.
Also, you are trying to get the average value.
So if a user inputs nothing you get NameError so you can print an Error message.
My task is:
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.
My idea was to append the numbers entered by the user to a list and after that loop through the list to sum the number and calculate the average using this total divided by the length of the list. Does that work? However, my list does not append integers, only strings. Besides, the word 'done' was also appended to the list.
my code is:
x=[ ]
while True:
line = input('enter a number: ')
x.append(line)
if line == 'done':
break
my desired output is:
Enter a number: 4
Enter a number: 5
Enter a number: bad data
Enter a number: 7
Enter a number: done
16 3 5.333333333333333
My idea was to append the numbers entered by the user to a list and after that loop through the list to sum the number and calculate the average using this total divided by the length of the list. Does that work?
Yes, that sounds like the perfect solution.
However, my list does not append integers, only strings.
Convert the input to an int before appending it:
x.append(int(line))
This will fail if line cannot be converted to an int, so you probably actually want:
try:
x.append(int(line))
except ValueError:
pass
Besides, the word 'done' was also appended to the list.
Check for the string 'done' before you append it.
if line == 'done':
break
try:
x.append(int(line))
except ValueError:
pass
Finally, you can use sum and len to do your calculations.
Here is what you can do, assuming the user can only input integers:
x=[]
while True:
try:
line = input('enter a number: ')
if line == 'done':
break
x.append(int(line))
except:
pass
print(sum(x),len(x),sum(x)/len(x))
If the user should be able to input floats:
x=[]
while True:
try:
line = input('enter a number: ')
if line == 'done':
break
x.append(float(line))
except:
pass
print(sum(x),len(x),sum(x)/len(x))
I'm very new to programming, just started working my way through a Python course. I've been looking through the course material and online to see if there's something I missed but can't really find anything.
My assignment is to make a chatbot that takes input and summarizes the input but also calculates the average. It should take all the input until the user writes "Done" and then terminate and print the results.
When I try to run this:
total = 0
amount = 0
average = 0
inp = input("Enter your number and press enter for each number. When you are finished write, Done:")
while inp:
inp = input("Enter your numbers and press enter for each number. When you are finished write, Done:")
amount += 1
numbers = inp
total + int(numbers)
average = total / amount
if inp == "Done":
print("the sum is {0} and the average is {1}.". format(total, average))
I get this error:
Traceback (most recent call last):
File "ex.py", line 46, in <module>
total + int(numbers)
ValueError: invalid literal for int() with base 10: 'Done'
From searching around the forums I've gathered that I need to convert str to int or something along those lines? If there are other stuff that need to be fixed, please let me know!
It seems that the problem is that when the user types "Done" then the line
int(numbers) is trying to convert "Done" into an integer which just won't work. A solution for this is to move your conditional
if inp == "Done":
print("the sum is {0} and the average is {1}.". format(total, average))
higher up, right below the "inp = " assignment. This will avoid that ValueError. Also add a break statement so it breaks out of that while loop as soon as someone types "Done"
And finally I think you are missing an = sign when adding to total variable.
I think this is what you want:
while inp:
inp = input("Enter your numbers and press enter for each number. When you are finished write, Done:")
if inp == "Done":
print("the sum is {0} and the average is {1}.". format(total, average))
break
amount += 1
numbers = inp
total += int(numbers)
average = total / amount
Ok, so I've got a couple issues with a program (for school again) that I'm using to add up all the digits of a number. I've got some of the program down, except 2 things. First, how to use a variable (thelength below) in replacement of a number to call a specific digit of the input (I'm not sure if this is even possible, but it would be helpful). And second, how to add up different numbers in a string. Any ideas?
Here's what I have so far:
number = str(int(input("Please type a number to add up: ")))
length = len(number)
thelength = 0
total = 0
thenumbers = []
while thelength < length:
#The issue is me trying to use thelength in the next two lines, and the fact that number is now a string
total += number[thelength]
thenumbers.append(number[thelength])
thelength += 1
for num in thenumbers:
print(num[0])
print("+")
print("___")
print(total)
Thanks for any help I can get!
I don't know what "call a specific digit of the input" means, but the error in your code is here:
total += number[thelength]
total is an int, and you're trying to add a string to it, convert the digit to an integer first.
total += int(number[thelength])
Result:
1
2
3
+
___
6
import re
import sys
INPUT_VALIDATOR = re.compile("^[0-9]+$")
input_str = input("Please type a natural number to add up: ")
if INPUT_VALIDATOR.match(input_str) is None:
print ("Your input was not a natural number (a positive whole number greater or equal to zero)!")
print ("This displeases me, goodbye puny human.")
sys.exit(1)
total = 0
for digit_str in input_str:
print(digit_str)
total += int(digit_str)
print("+")
print("___")
print(total)
If you don't need to print the digits as you go, it's even easier:
# (Add the same code as above to get and validate the input string)
print(sum(int(digit_str) for digit_str in input_str))
number = int(input("Please type a number to add up: "))
total = 0
while number > 0:
total += number % 10
total /= 10
print(total)
num % 10 pretty much gets the last digit of a number
then we divide it by 10 to truncate the number by its last digit
we can loop through the number as long as it's above 0 and take the digital sum by using the method outlined above
Every thing that you need is convert the digits to int and sum them :
>>> s='1247'
>>> sum(map(int,s))
14
But as you get the number from input it could cause a ValueErorr , for refuse that you can use a try-except :
try :
print sum(map(int,s))
except ValueErorr :
print 'please write a valin number :'
Also if you are using python 2 use raw_input for get the number or if you are using python 3 just use input because the result of both is string !