Why am I getting invalid character - python-3.x

I am running a simple code with a GPS sensor and Raspberry Pi 3b+ and want to perform some calculations with the readings and the only errors I'm getting is "SyntaxError: invalid character in identifier" but the line looks straightforward.
def Tasks():
def CalculateSpeed():
if x[-1] and y[-1] == even:
ChangeInLatitude=x1-x
DistanceConversion=ChangeInLatitude*111111
Speed=DistanceConversion/TimeElapsed
Speed=str(speed) + meters/interval
print (“The object this module is attached to is moving at “ + Speed)
The error code is placing the error marker at the end of "the" in the 8th line

You have unicode quotes.
foo = “bar“
is not valid nor is
foo = “bar”
but single or double "basic" quotes are:
foo = "bar"

Related

Type Conversion to Integer in Python using int() [duplicate]

I got this error from my code:
ValueError: invalid literal for int() with base 10: ''.
What does it mean? Why does it occur, and how can I fix it?
The error message means that the string provided to int could not be parsed as an integer. The part at the end, after the :, shows the string that was provided.
In the case described in the question, the input was an empty string, written as ''.
Here is another example - a string that represents a floating-point value cannot be converted directly with int:
>>> int('55063.000000')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '55063.000000'
Instead, convert to float first:
>>> int(float('55063.000000'))
55063
See:https://www.geeksforgeeks.org/python-int-function/
The following work fine in Python:
>>> int('5') # passing the string representation of an integer to `int`
5
>>> float('5.0') # passing the string representation of a float to `float`
5.0
>>> float('5') # passing the string representation of an integer to `float`
5.0
>>> int(5.0) # passing a float to `int`
5
>>> float(5) # passing an integer to `float`
5.0
However, passing the string representation of a float, or any other string that does not represent an integer (including, for example, an empty string like '') will cause a ValueError:
>>> int('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
>>> int('5.0')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'
To convert the string representation of a floating-point number to integer, it will work to convert to a float first, then to an integer (as explained in #katyhuff's comment on the question):
>>> int(float('5.0'))
5
int cannot convert an empty string to an integer. If the input string could be empty, consider either checking for this case:
if data:
as_int = int(data)
else:
# do something else
or using exception handling:
try:
as_int = int(data)
except ValueError:
# do something else
Python will convert the number to a float. Simply calling float first then converting that to an int will work:
output = int(float(input))
This error occurs when trying to convert an empty string to an integer:
>>> int(5)
5
>>> int('5')
5
>>> int('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
The reason is that you are getting an empty string or a string as an argument into int. Check if it is empty or it contains alpha characters. If it contains characters, then simply ignore that part.
Given floatInString = '5.0', that value can be converted to int like so:
floatInInt = int(float(floatInString))
You've got a problem with this line:
while file_to_read != " ":
This does not find an empty string. It finds a string consisting of one space. Presumably this is not what you are looking for.
Listen to everyone else's advice. This is not very idiomatic python code, and would be much clearer if you iterate over the file directly, but I think this problem is worth noting as well.
My simple workaround to this problem was wrap my code in an if statement, taking advantage of the fact that an empty string is not "truthy":
Given either of these two inputs:
input_string = "" # works with an empty string
input_string = "25" # or a number inside a string
You can safely handle a blank string using this check:
if input_string:
number = int(input_string)
else:
number = None # (or number = 0 if you prefer)
print(number)
I recently came across a case where none of these answers worked. I encountered CSV data where there were null bytes mixed in with the data, and those null bytes did not get stripped. So, my numeric string, after stripping, consisted of bytes like this:
\x00\x31\x00\x0d\x00
To counter this, I did:
countStr = fields[3].replace('\x00', '').strip()
count = int(countStr)
...where fields is a list of csv values resulting from splitting the line.
This could also happen when you have to map space separated integers to a list but you enter the integers line by line using the .input().
Like for example I was solving this problem on HackerRank Bon-Appetit, and the got the following error while compiling
So instead of giving input to the program line by line try to map the space separated integers into a list using the map() method.
your answer is throwing errors because of this line
readings = int(readings)
Here you are trying to convert a string into int type which is not base-10. you can convert a string into int only if it is base-10 otherwise it will throw ValueError, stating invalid literal for int() with base 10.
This seems like readings is sometimes an empty string and obviously an error crops up.
You can add an extra check to your while loop before the int(readings) command like:
while readings != 0 or readings != '':
readings = int(readings)
I am creating a program that reads a
file and if the first line of the file
is not blank, it reads the next four
lines. Calculations are performed on
those lines and then the next line is
read.
Something like this should work:
for line in infile:
next_lines = []
if line.strip():
for i in xrange(4):
try:
next_lines.append(infile.next())
except StopIteration:
break
# Do your calculation with "4 lines" here
Another answer in case all of the above solutions are not working for you.
My original error was similar to OP: ValueError: invalid literal for int() with base 10: '52,002'
I then tried the accepted answer and got this error: ValueError: could not convert string to float: '52,002' --this was when I tried the int(float(variable_name))
My solution is to convert the string to a float and leave it there. I just needed to check to see if the string was a numeric value so I can handle it correctly.
try:
float(variable_name)
except ValueError:
print("The value you entered was not a number, please enter a different number")

def lastLetters(words) eof error coming from outside of my code

I'm supposed to make a function that takes the last two letters from an input and print an output that shows just the last two letters but reversed with a space in the middle I did this successfully in one environment but its giving me an eof error on the hackerrank platform from outside of my manipulable space
def my_func():
words = input()
a = words
print(a[-1],a[-2])
my_func()
im supposed to take the input example "hello" and the output would be "o l"
this works on my phone where I first wrote it but is giving an eof error from a line in the pre wrote code on the hackerrank platform

How to compare string to value without quotation marks

I am pretty new to Haskell and today I was trying to make a calculator using Haskell (like most people make when learning a new language to get the hold of if statements) and I had trouble using if values with strings. I want to check if the string the user wrote is "plus" (without "") but if I don't the quotation marks (so it'd look like if op == plus) it doesn't recognize it as a string and outputs an error but if on the other hand I use the quotation marks (so it'd look like this if op == "plus") then it looks for the string "plus" with the quotation marks, how can I compare a string to a value without quotation marks?
Case 1:
calculate x op y = do
if op == "plus"
then x+y
else x
Result: the program looks for "plus" when calling the function and thus if the input when calling the function is for example "1 plus 3" it will give out an error of ':67:13: error: Variable not in scope: plus :: [Char]
Case 2:
calculate x op y = do
if op == plus
then x+y
else x
Result: When trying to load the program I get the error "test.hs:2:33: error: Variable not in scope: plus
Failed, modules loaded: none.", so I can't try and call the function obviously.
The quotation marks are just part of the syntax of string literals, not their contents. That is, if you write op == "plus", this will be true if (and only if) plus contains the characters 'p', 'l', 'u' and 's' (in that order, obviously) - it does not require (or allow) op to contain any quotes.
So if op == "plus" does not produce True for you even when you think it should, op does not contain what you think it does.

Why is my string nil?

I made this simple program that reads characters until the enter key is pressed
var data: string
while true:
var c = readChar(stdin) # read char
case c
of '\r': # if enter, stop
break
else: discard
data.add(c) # add the read character to the string
echo data
But when it tries to echo data, it crashes
> ./program
hello
Traceback (most recent call last)
program.nim(11) program
SIGSEGV: Illegal storage access. (Attempt to read from nil?)
This means data is nil. But every time I press enter a character, it adds the character to data. Something goes wrong, but where?
data is initially nil when you define it as var data: string. Instead you can use var data = "" to make it an initialized string.
The stream stdin buffers all the characters until the newline key is pressed, then it will submit the character(s). I expected the behavior to be reading direct characters.
That means that \r will never be the case, it will try to add a character to data but data is nil, so that fails. I thought it failed at the echo statement.
To demonstrate, this code works:
var data = ""
while true:
var c = readChar(stdin) # read char
case c
of '\e': # if escape, stop
break
else:
data.add(c) # add the read character to the string
echo data

unexpected symbol near '\' when loadstring byte

When trying to create a tool that converts a Lua code into byte and then string.dump it I got an error.
Code used :
s = [[
print("hello lua user")
]]
local byte = ""
for i = 1, s:len() do
byte = byte.."\\"..tostring(s:byte(i))
end
-- Creating the function to use in string.dump
f, err = loadstring(byte)
print(err)
local output = string.dump(f)
The error in title comes from printing err
The weird is that if I print(byte) and then manually paste it inside loadstring quoted, it works.
Manually pasting it won't work since I need it to be automated.
You are confusing with escaped sequences in Lua. Let's check a simpler example:
In a system using ASCII, '\97' is equivalent to 'a', so
print('\97')
print('a')
Both lines print the character a, but what you are converting is like this:
print('\\97')
This prints \97 itself, not a.
To make your code work, add these lines after you get byte.
local f1, err1 = loadstring("return '" .. byte .. "'")
byte = f1()
This call to loadstring converts a string like '\\97' back to '\97'.

Resources