I made a code like this to find the arithmetical mean for numbers the user has typed in but for some reason the program couldn't convert string to float in the end. What should I change?
print("I'm going to find the arithmetical mean! \n")
jnr = 0; sum = 0
negative = "-"
while True:
x = input(f"Type in {jnr}. nr. (To end press Enter): ")
if negative not in x:
jnr += 1
elif negative in x:
pass
elif x == "": break
sum = sum + float(x)
print("Aritmethmetical mean for these numbers is: "+str(round(sum/(jnr-1), 2)))
I got his Error :
Traceback (most recent call last): File
"C:\Users\siims\Desktop\Koolitööd\individuaalne proge.py", line 11, in
sum = sum + float(x) ValueError: could not convert string to
float
As I said in my comment the error comes from the fact that calling float(x) when the user uses Enter result in the error. The easiest way to fix your code without changing everything is by checking first if the input is "". That way you will not be trying to convert an empty string to float.
print("I'm going to find the arithmetical mean! \n")
jnr = 0;
sum = 0
negative = "-"
while True:
x = input(f"Type in {jnr}. nr. (To end press Enter): ")
if x == "":
break
elif negative not in x:
jnr += 1
sum = sum + float(x)
print("Aritmethmetical mean for these numbers is: "+str(round(sum/(jnr-1), 2)))
You're trying to convert a string to a float but it is an invalid string if you are using the string for that purpose. I would just continue asking until the user gives the right input, like this:
def float_input(s):
while True:
try:
x = input(s)
except ValueError:
print('Invalid input. Try again.')
else:
break
return x
Then, instead of input, use float_input in your code.
An updated version of your code :
print("I'm going to find the arithmetical mean! \n")
jnr = 0; sum = 0
while True:
x = int(input())
if x>1:
jnr += 1
elif x<1:
pass
if x == 0:
break
sum += float(x)
print(sum)
print("Aritmethmetical mean for these numbers is: {}".format(sum/jnr))
output:
I'm going to find the arithmetical mean!
9
9
9
9
9
0
Aritmethmetical mean for these numbers is: 9.0
Pythonic way:
You can find mean by:
print("I'm going to find the arithmetical mean! \n")
inp=[int(i) for i in input().split()]
print(sum(inp)/len(inp))
output:
I'm going to find the arithmetical mean!
9 9 9 9 9
9.0
Related
This is all the further i've gotten.
import math
num_to_convert = int(input("Please enter any intger from 1 and 100:"))
while num_to_convert < 1 or num_to_convert > 100:
num_to_convert = int(input("Sorry that's not an integer from 1 to 100, try again:"))
else:
print("I'm lost!")
I found this but I don't understand whats going on. Maybe some explanation of what's going on would help.
def decimalToBinary(n):
if(n > 1):
# divide with integral result
# (discard remainder)
decimalToBinary(n//2)
print(n%2, end=' ')
It seems like you want to convert an integer which is not a decimal to binary from your code i would write
while True:
try:
value1=input("Integer you want to convert to binary: ")
binaryvalue=(bin(int(value1)))
print (binaryvalue[2:])
except:
print("I did not understand that")
pass
Valuetoconvert=int(input("Number to convert: "))
u = format(Valuetoconvert, "08b")
print(u)
Try this then
See Below:
def toBin(n):
if n < 2:
return str(n)
else:
if n % 2 == 0:
return toBin(n//2) + "0"
else:
return toBin(n//2) + "1"
Explanation:
This is my sollution which works similar to yours. I hope you know what recursion is otherwise this is going to be difficult to understand.
Anyway the algorithm is to devide the number repeatedly by 2 until the number is smaller than 2 cause then you have the sollution right away(base case).
When the current number is greater than 2 you check wether it is
divisible by 2. If it is even you append a 0 to your string else append a 1. You can try this out on paper to better understand it.
This question already has answers here:
ValueError: invalid literal for int() with base 10: ''
(15 answers)
Closed 2 years ago.
I'm new to python. In this code, I'm trying to ask for numbers repeatedly. When the user enters 0, the program print the average of the numbers exclude 0. I can get the average from this code. However, there's a ValueError,
y = int(input())
ValueError: invalid literal for int() with base 10: ''
I don't understand why this error happens. Is it because of convert variable type under while loop? Can anyone help? Thanks!!
nums=0
i=0
x = int(input())
while x>0:
y = int(input())
i = i + 1
nums = y + nums
if y == 0:
avg = (nums+x)/(i)
print("The average of those numbers is {:.2f}.".format(avg))
This error occurs when you try to input a string of characters, instead of numbers.
E.g:
if you input '', 'string' - These won't work
but if you input '9', '239412' - This will work
It is likely the line y = int(input()) is receiving a string from the user input .
See this example.
>>> while True:
... y = int(input())
... print "Y=",y
...
12
Y= 12
0
Y= 0
"this"
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'this'
Like #Blade said you should give numbers as input. You can do this:
nums=0
i=0
try:
x = int(input())
while x>0:
try:
y = int(input())
i = i + 1
nums = y + nums
if y == 0:
avg = (nums+x)/(i)
print("The average of those numbers is {:.2f}.".format(avg))
except:
print("Input is not a number")
except:
print("Input is not a number")
You got the Value Error because you entered a space( "") which considered as a string but the input should be an integer int
For calculating the average of two numbers you can use this simple code instead : -
def average(x, y):
" Returns the average of two numbers "
return (x+y)/2
x = int(input("Enter a number:\n"))
y = int(input("Enter another number :\n"))
print(average(x, y))
I'm trying to use a function (dec2bin()) to convert decimal numbers to binary. I see the input number being printed as binary but in the wrong order. What do I need to change? Or do I need to start over?
Here is the code with the function at first then the program:
def dec2bin(value):
if value > 1:
dec2bin(value//2)
print (value%2, end = '')
invalue_ok = False
invalue = 0
while invalue_ok is False:
invalue = int(input("Give a value: "))
if invalue > 65535:
print ("Wrong. Number too big. Try again.")
elif invalue < 0:
print ("Wrong. Can only handle positive numbers.")
if invalue < 256:
print ("Number", invalue, "fits in one byte and in binary is ", dec2bin(invalue))
else:
print ("Number", invalue, "fits in 16 bytes and in binary is", dec2bin(invalue))`
The output looks like this:
Give a value: 234
1101010Number 234 fits in one byte and in binary is None
What can I do to get it right?
it works with
if value>0:
it's in the good order
There are three easier ways to do it:
The format method:
binary = "{0:b}".format(*number*)
The bin method (this also works with negative numbers):
binary = bin(*number*)
Or a function from this thread:
def intToBin(n):
if(n < 0):
return -1
elif(n == 0):
return str(n)
else:
result = ""
while(n != 0):
result += str(n%2)
n //= 2
return result[::-1]
binary = intToBin(*number*)
my problem is i have to calculate the the sum of digits of given number and that no is between 100 to 999 where 100 and 999 can also be include
output is coming in this pattern
if i take a=123 then out put is coming total=3,total=5 and total=6 i only want output total=6
this is the problem
there is logical error in program .Help in resolving it`
this is the complete detail of my program
i have tried it in this way
**********python**********
while(1):
a=int(input("Enter any three digit no"))
if(a<100 or a>999):
print("enter no again")
else:
s = 0
while(a>0):
k = a%10
a = a // 10
s = s + k
print("total",s)
there is no error message in the program because it has logical error in the program like i need output on giving the value of a=123
total=6 but i m getting total=3 then total=5 and in last total=6 one line of output is coming in three lines
If you need to ensure the verification of a 3 digit value and perform that validation, it may be useful to employ Regular Expressions.
import re
while True:
num = input("Enter number: ")
match = re.match(r"^\d{3}$, num)
if match:
numList = list(num)
sum = 0
for each_number in numList:
sum += int(each_number)
print("Total:", sum)
else:
print("Invalid input!")
Additionally, you can verify via exception handling, and implementing that math you had instead.
while True:
try:
num = int(input("Enter number: "))
if num in range(100, 1000):
firstDigit = num // 10
secondDigit = (num // 10) % 10
thirdDigit = num % 10
sum = firstDigit + secondDigit + thirdDigit
print("Total:", sum)
else:
print("Invalid number!")
except ValueError:
print("Invalid input!")
Method two utilizes a range() function to check, rather than the RegEx.
Indentation problem dude, remove a tab from last line.
Also, a bit of python hint/tip. Try it. :)
a=123
print(sum([int(x) for x in str(a)]))
I've made a simple program where the users adds as many numbers as they would like then type 'exit' to stop it and print the total but sometimes it says the converting the string to int fails, and sometimes it does convert but then it has the wrong out put e.g I type 1 + 1 but it prints 1
def addition():
x = 0
y = 1
total = 0
while x < y:
total += int(input())
if input() == "exit":
x += 1
print(total)
addition()
I have tryed converting it to a float then to an int but still has inconsistency, I did start learning python today and am finding the syntax hard coming from c++ / c# / Java so please go easy on the errors
Maybe this is what you are looking for:
def addition():
total = 0
while True:
value = input()
if value == "exit":
break
else:
try:
total += int(value)
except:
print('Please enter in a valid integer')
print(total)
EDIT
There are two reasons why the code isn't working properly:
First, the reason why it is failing is because you are trying to cast the word "exit" as an integer.
Second, as user2357112 pointed out, there are two input calls. The second input call was unintentionally skipping every other number being entered in. All you needed to do was one input call and set the entered value into a variable.
You can break the while loop, without using x and y.
def addition():
total = 0
while True:
total += int(input())
if input() == "exit":
break
print(total)
addition()
These are a few ways you can improve your code:
Run the loop forever and break out of it only if the user enters "exit"
To know when the user entered "exit" check if the input has alphabets with isalpha()
Making the above changes:
def addition():
total = 0
while True:
user_input = input()
if user_input.strip().isalpha() and user_input.strip() == 'exit':
break
total += int(user_input)
print(total)
addition()
def safe_float(val):
''' always return a float '''
try:
return float(val)
except ValueError:
return 0.0
def getIntOrQuit():
resp = input("Enter a number or (q)uit:")
if resp == "Q":
return None
return safe_float(resp)
print( sum(iter(getIntOrQuit,None)) )
is another way to do what you want :P