ValueError: could not convert string to float - python

So... I have this primitive calculator that runs fine on my cellphone, but when I try to run it on Windows 10 I get...
ValueError: could not convert string to float
I don't know what the problem is, I've tried using raw_input but it doesn't work ether. Please keep in mind I'm green and am not aware of most methods for getting around a problem like this
num1 = float(input ()) #take a float and store it
chars = input () #take a string and store it
num2 = float(input ())

your code only convert string that are integers like in below statement
num1 = float(input ()) #take a float and store it ex 13
print num1 # output 13.0
if you provide 13 as a input it will give the output as 13.0
but if you provide SOMEONEE as input it will give ValueError
And it is same with the case of raw_input() but the difference is that by default raw_input() takes input as a string and input() takes input as what is provided to the function

I think this is happening because in some cases 'input' contains non-numerical characters. Python is smart and when a string only contains numbers, it can be converted from string to float. When the string contains non-numerical characters, it is not possible for Python to convert it to a float.
You could fix this a few ways:
Find out why and when there are non-numerical characters in your input and then fix it.
Check if input contains numbers only with: isdecimal()
Use a try/except
isdecimal() example:
my_input = raw_input()
if my_input.isdecimal():
print("Ok, go ahead its all numbers")
UPDATE:
Two-Bit-Alchemist had some great advice in the comments, so I put it in my answer.

Related

Using input() as parameter for range() in Python

How does input() work as a parameter to range() in Python?
For example:
Say the user inputs multiple numbers 10 and 2 or more literally type "10 2"
for i in range(int(input())):
try:
a,b=map(int,input().split())
print(a//b)
except Exception as e:
print("Error Code:",e)
What range does the for loop use then? Is it (0,10), (0,2) or something else? Or, said differently, which number does the range use for the upper limit if the user inputs multiple numbers? More generally, I am trying to understand the purpose of the for loop here and why the code can't just be:
try:
a,b=map(int,input().split())
print(a//b)
except Exception as e:
print("Error Code:",e)
input() values will be stored as str.
It all comes down to what the user inputs. The piece of code you provided is very bad, because the user has to guess what to input and when. But the logic works as follows:
If you type in a single value, then int(input()) will convert that value to integer. For example, if you input 2, then input() will hold the string "2" and int("2") will yield integer 2.
If you have multiple values, then you cannot convert to int right away, because what the hell does int("2 10") mean? That is why you have to use .split(), to separate these multiple values in many singular values. For example, if you run x = input() and type in 2 10, then x will hold the string "2 10". Now, "2 10".split() yields the list of strings ["2", "10"].
The piece of code map(int,input().split()) comes in to convert this list of strings to a list of integers. It maps each value to a new value using the function int to transform it.
Now that this is established, it becomes easier to understand how this works in a for loop using range.
The range type, as per docs, may have one parameter stop or three arguments (start, stop [, step]) in its constructor. These arguments are all integers.
Thus, the values from input() have to fit this structure. If you type in 2 10 in input, and try to do range("2 10"), you'll receive an error. Because you are passing one argument of type str. That is why you have to convert to integer first. But you cannot convert "2 10" to integer right away, as we just discussed. That is why you have to split first, and then convert each value to int, and just then pass these as arguments to range().
So, to summarize, given x = input() and you type in 2 10, here is what does not work:
>>> int(x)
>>> range(x)
what does work:
>>> a,b=map(int,input().split())
>>> range(a, b)
The first input() will determine the stop condition of the for loop
Which means the first input() determines the number of time your for loop will be executed
Other input() will assign the values to a and b as string
The above is equivalent to:
stop = input()
stop = int(stop)
for i in range(stop):
try:
a,b=map(int,input().split())
print(a//b)
except Exception as e:
print("Error Code:",e)
But if the first input() is given as "10 10" then the code will throw you an error something like the string can not be converted to int
The a,b=map(int,input().split()) means you are expecting an input of two numbers separated by spaces and these inputs will be given exactly stop number of times
This pattern is used when you want to read n lines from the input, for example the input is:
3
1 2
3 4
5 6
The first input will determine how many times the for loop needs to be run to read all the lines.
For a single line of input like "10 2" you don't need to use a loop.

Keep zero digit save while converting string to integer in python

I am converting a string into integer using int function and it is working fine but i want to keep save zero digit that are at the start of the string.
string_value = '0123'
print(int(string_value))
result is 123
How can i format output 0123 as in integer type value not in string.
You can't, but if you want to put 0's (zero padding) at the beginning of your number, this is the way to do it.
"{:04}".format(123)
# '0123'
"{:05}".format(123)
# '00123'
Like every one said you can try above answers or the following :
string_value = '0123'
int_no = int(string_value)
print("%04d" % int_no)
print(string_value.zfill(4))
Both will give same answer
Impossible, you cannot get an integer value of 0123.
You should change your mind, you do not actually need 0123 in integer, but you need to keep zero when displaying it. So the question should change to how to format output.

Python 3 taking multiple data types in input, separated by space

So i need to find a way to take multiple data types as an input and store them in variables. Lets say i have 3 variables, each of them should store a fixed data type
a - float
b - str
c - int
and if the user enters a wrong, he will be asked to type again.
The user will enter all of them, separated by space but i can't think of a way to store them in the variables, while keeping the data type. I've tried with .split(), but it just transforms them into strings. It's probably something quite obvious, but can't figure it out right now. Thanks in advance!
Maybe:
def myfucn(vars):
vars = vars.split()
try:
float(vars[0])
if not "." in vars[0]:
raise Exception("First var should be INT not Float")
except ValueError:
print("Error not Float found")
try:
int(vars[2])
except ValueError:
print("Error Int no found")
#answer
a_float, b_str, c_int = vars
print(" Yes ")
greetings
You are on the right track if the split() function. The problem is that when you say that user will give three values separated by ' ', you are taking in a string.
The following is a string:
'34.44 35.45 5'
Maybe what you can do is after using split, you can cast each returned item to a variable. If you still need to check the type of variable, you can use the type() function.
Hope this helps!

Unicode Prefix on Numbers - Python

I am trying to create a list where I need to input numbers as strings in one list and I am trying to do it with a while loop.
while input_list[-1] != "":
input_list.append(raw_input())
However when numbers are entered they are returned as u'X', X being the number entered. I cannot perfrom mathematical calculations on these numbers.
I would usually use str() or int() but I cant generalise in this case.
Is there a cleaner way to remove the u' ' prefix than simpley using if statements?
The "u'' prefix" is trying to indicate the type of the value. You have strings here, not numbers. If you want to do math, you need to convert your strings to numbers. If they happen to enter a string that can't be converted to a number, you should tell the user what happened
user_typed = raw_input()
try:
user_number = float(user_typed)
except ValueError:
print "Couldn't convert this to a number, please try again: %r" % user_typed
See also: LBYL and EAFP

How do I get Python 2.7 to accept multiple variable inputs on a single line

Im trying to get the user to input the length and width of a rectangle at the same time.
length,width = float (raw_input("What is the length and width? ")).split(',')
When I run the program, however, and enter two variables such as 3,5 I get an error saying that I have an invalid literal for type float().
Well, that's because you're entering two numbers separated by a comma, but splitting that value on a period. Split it on a comma and it should work much better.
First, why does this fail:
float (raw_input("What is the length and width? ")).split(',')
The split(',') splits a string into a sequence of strings. You can't call float on a sequence of strings, only on a single string. That's why the error says it's "an invalid literal for type float".
If you want to call the same function on every value in a sequence, there are two ways to do it:
Use a list comprehension (or a generator expression):
[float(x) for x in raw_input("What is the length and width? ")).split(',')]
Or the map function:
map(float, raw_input("What is the length and width? ")).split(','))
I would use the list comprehension, because that's what the BDFL prefers, and because it's simpler for other things you may want to do like x[2], but it really doesn't matter that much in this case; it's simple enough either way, and you should learn what both of them mean.
You also will probably want to cast to integers:
prompt = "what is the length and width? "
inpt = raw_input(prompt)
length, width = [int(i) for i in inpt.split(',')]

Categories

Resources