Python: String will not convert to float [duplicate] - python

This question already has answers here:
Turn a variable from string to integer in python [duplicate]
(3 answers)
Closed 4 years ago.
I wrote this program up a few hours ago:
while True:
print 'What would you like me to double?'
line = raw_input('> ')
if line == 'done':
break
else:
float(line) #doesn't seem to work. Why?
result = line*2
print type(line) #prints as string?
print type(result) #prints as string?
print " Entered value times two is ", result
print 'Done! Enter to close'
As far as I can tell, it should be working fine.The issue is that when I input a value, for example 6, I receive 66 instead of 12. It seems like this portion of code:
float(line)
is not working and is treating line as a string instead of a floating point number. I've only been doing python for a day, so its probably a rookie mistake. Thanks for your help!

float() returns a float, not converts it. Try:
line = float(line)

float(line) does not convert in-place. It returns the float value. You need to assign it back to a float variable.
float_line = float(line)
UPDATE: Actually a better way is to first check if the input is a digit or not. In case it is not a digit float(line) would crash. So this is better -
float_line = None
if line.isdigit():
float_line = float(line)
else:
print 'ERROR: Input needs to be a DIGIT or FLOAT.'
Note that you can also do this by catching ValueError exception by first forcefully converting line and in except handle it.
try:
float_line = float(line)
except ValueError:
float_line = None
Any of the above 2 methods would lead to a more robust program.

float(line) doesn't change line at all, so it is still a string. You'll want to use line = float(line) instead.

Related

'/' understood as a float?

I am looping through a pandas dataframe and trying to append the result on a conditional statement. However, my code seems to be posing a problem stopping me from append what I want although it prints fine but displays the error in the end. here is my code below:
counta=[]
for line in ipcm_perf['Alarms']:
if '/' in line:
print (line)
the error I get is the following :
2 for line in ipcm_perf['Alarms']:
----> 3 if ('/') in line:
4 print (line)
5
TypeError: argument of type 'float' is not iterable
I really do not know why Python is flagging that line. where's the float? Everything is being printed but with error at the bottom. It is stopping from appending.
your problem is that you are trying to check if there is a string (/) in a floating number (line), and Python does not like that.
That's because when you write "/" in some_string Python iterates through each char of some_string, but he can iterate through a floating number.
you can double check this by simply running:
if '/' in 3.14:
print("something")
output:
TypeError: argument of type 'float' is not iterable
I suppose that you're searching for a / because you've seen that somewhere in the column. If that's the case, it probably is in a string, and if that's the case, a quick&dirty way to clean your data can be:
if type(line) == str:
if "/" in line:
print(line)
else:
print("I am not a string")
and with line = 3.14, it returns:
I am not a string
and with line = "4/2", it returns:
I am a string

Syntax error: 002: on assigning values to variables python

Im writing a program for Uni to find all the palindromic primes, i have written out the program already but when i run it, my first input gets an error while trying to assign values to the variable.
please could someone tell me why this is the case!
start =input("Enter the start point N:")
starteval= eval(start)
endval = eval(input("Enter the end point M:"))
reverse=""
x=starteval+1
while x<endval:
reverse+=start[::-1]
evalreverse=eval(reverse)
if evalreverse==starteval:
if starteval==2 or starteval==3:
print(starteval)
elif starteval%2==0 or starteval%3==0:
pass
i=5
w=2
a=0
while i<=starteval:
if starteval%i==0:
break
else:
a=True
i+=2
if a==True:
print (starteval)
else:
pass
x+=x+1
the ouput i recieve is
"Enter the start point N:200
Enter the end point M:800
Traceback (most recent call last):
File "", line 1, in <module>
start =input("Enter the start point N:")
Syntax Error: 002: <string>, line 1, pos 3"
please and thank you!
Try instead of the first 3 lines to use:
starteval = int(raw_input("Enter the start point N:"))
endval = int(raw_input("Enter the end point M:"))
In Python 3 integer literals cannot begin with a zero:
>>> i = 002
File "<stdin>", line 1
i = 002
^
SyntaxError: invalid token
Because you are applying the eval function to your string input, Python attempts to parse your input as a valid Python expression, whcih is why you see the error you see.
It would make more sense to use int(input(...)) to get the integer (though you would still have to handle any exceptions raised when the user types a non-integer into your code). This has the advantage that it will accept the input that is causing you trouble in eval.
You could write a small intParsing function, that handles simple input parsing for you, then basically replace every "eval()" function of your code with intParsing().
Here is your edited code:
def intParsing(input_str):
str = ""
# Delete all chars, that are no digits (you could use a regex for that too)
for char in input_str.strip():
if char.isdigit():
str += char
# Now you only got digits in your string, cast your string to int now
r = int( str )
print "result of parsing input_str '", input_str, "': ", r
return r
start =raw_input("Enter the start point N:")
starteval= intParsing(start) # I edited this line
end = raw_input("Enter the end point M:") # I edited this line
endval =intParsing(end) # I edited this line
reverse=""
x=starteval+1
while x<endval:
reverse+=start[::-1]
evalreverse= intParsing(reverse) # I edited this line

Python retrieve string input from int(input()) exception

I'm trying to make the following code work:
try:
x = int(input())
except ValueError as var:
#print the input of the user
If I try to print(var) it would print the error line and not the original input of the user.
For example, if the user would insert bla instead of an integer I would like to print bla
P.S I must not change the line x = int(input()), else I would've solved it easily
I would change the x = int(input()) line, but since you ask, here is an ugly hack wich exploits the format of a ValueError message:
invalid literal for int() with base 10: 'foobar'
by splitting it at first : and removing surrounding ':
try:
x = int(input())
except ValueError as e:
original_input = str(e).split(":")[1].strip()[1:-1]
print(original_input)
by the way, if you are still using Python 2.x, you should use raw_input instead of input. In fact old input will automatically attempt a conversion to int if possible:
try:
x = int(raw_input())
except ValueError as e:
original_input = str(e).split(":")[1].strip()[1:-1]
print original_input
What appears when you print var?
Until you provide that information, here is a possible hackish solution:
try:
x = int(input())
except NameError as var:
e = str(var)
print e[6:-16]
This is assuming var is equal to
NameError: name 'user_input' is not defined
where user_input is the user's input.
EDIT: This post assumed the code was running in Python 2.x whereas it seems to be running with Python 3. Leaving this up in case people are wondering for Python 2
This is hack that reads the input from the passed error message. It handles quotes in the input string and backslashes correctly.
#We get input from the user
try:
x = int(input())
except ValueError as var:
#we need to find the text between the quotes in the error message
#but we don't know what kind of quote it will be. We will look for
#the first quote which will be the kind of quotes.
#get the location or existence of each kind of quote
first_dquote = str(var).find('"')
first_squote = str(var).find("'")
used_quote = 0
#if double quotes don't exist then it must be a single quote
if -1 == first_dquote:
used_quote = first_squote
#if single quotes don't exist then it must be a dubble quote
elif -1 == first_squote:
used_quote = first_dquote
#if they both exist then the first one is the outside quote
else: used_quote = min(first_squote,first_dquote)
#the output is what is between the quotes. We leave of the end
#because there is the end quote.
output = str(var)[used_quote+1:-1]
#but the error message is escaped so we need to unescape it
output = bytes(output,"utf_8").decode("unicode_escape")
#print the output
print(output)

Converting string to int in serial connection

I am trying to read a line from serial connection and convert it to int:
print arduino.readline()
length = int(arduino.readline())
but getting this error:
ValueError: invalid literal for int() with base 10: ''
I looked up this error and means that it is not possible to convert an empty string to int, but the thing is, my readline is not empty, because it prints it out.
The print statement prints it out and the next call reads the next line. You should probably do.
num = arduino.readline()
length = int(num)
Since you mentioned that the Arduino is returning C style strings, you should strip the NULL character.
num = arduino.readline()
length = int(num.strip('\0'))
Every call to readline() reads a new line, so your first statement has read a line already, next time you call readline() data is not available anymore.
Try this:
s = arduino.readline()
if len(s) != 0:
print s
length = int(s)
When you say
print arduino.readline()
you have already read the currently available line. So, the next readline might not be getting any data. You might want to store this in a variable like this
data = arduino.readline()
print data
length = int(data)
As the data seems to have null character (\0) in it, you might want to strip that like this
data = arduino.readline().rstrip('\0')
The problem is when the arduino starts to send serial data it starts by sending empty strings initially, so the pyserial picks up an empty string '' which cannot be converted to an integer. You can add a delay above serial.readline(), like this:
while True:
time.sleep(1.5)
pos = arduino.readline().rstrip().decode()
print(pos)

python input() not working as expected [duplicate]

This question already has answers here:
Receive a string, convert to calculate and display response, but.. Can't split
(2 answers)
Closed 9 years ago.
I am a python newbie.I am getting familiar with loops and tried this example from a book
while True:
s = input('Enter something : ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
However the output is as follows
Enter something : ljsdf
Traceback (most recent call last):
File "trial_2.py", line 2, in <module>
s = input('Enter something : ')
File "<string>", line 1, in <module>
NameError: name 'ljsdf' is not defined
You have to use raw_input() instead (Python 2.x), because input() is equivalent to eval(raw_input()), so it parses and evaluates your input as a valid Python expression.
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
Note:
input() doesn't catch user errors (e.g. if user inputs some invalid Python expression). raw_input() can do this, because it converts the input to a string. For futher information, read Python docs.
you want raw_input() in python2
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print 'Length of the string is', len(s)
print 'Done'
input() tries to evaluate (dangerously!) what you give it
Your code will work fine in python 3.x
But if you are using python 2 you will have to input string using raw_input()
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
It seems like you're using Python 2.x, while the code is expected to be run in Python 3.x.
input in Python 2.x evaluates the input string unlike input in Python 3.x.
In Python 2.x input() is designed to return numbers, int or float depending on the input from the user, you can also enter variable names.
you need to use:
raw_input('Enter something: ')
The error is caused because Python thinks that "ljsdf" is the name of a variable, and that's why it raises this exception:
NameError: name 'ljsdf' is not defined
becuase "ljsdf" is not defined as a variable. :D
raw_input() is safer to use, and then convert the input to whatever other type after :D

Categories

Resources