Curangle() throwing this error - TypeError: float() argument must be a string or a number - linux

Below is the original code:
#Update the solar file for reporting
logsolar = open('/tools/inputs/solarvalues.txt','w')
writeline=("[myvars]\n")
logsolar.write(writeline)
writeline=("solar_heading: " + str(round((float(getsolarheading())),1)) + "\n")
logsolar.write(writeline)
writeline=("solar_elevation: " + str(round((float(getsolarangle())),1))+ "\n")
logsolar.write(writeline)
writeline=("actual_elevation: " + str(round((float(getcurangle())),1))+ "\n")
logsolar.write(writeline)
writeline=("actual_heading: " + str(round((float(getcurheading())),1))+ "\n")
logsolar.write(writeline)
logsolar.close()
The following is the error message:
Traceback (most recent call last):
File "solarrobot7-core.py", line 373, in <module>
writeline=("actual_elevation: " + str(round((float(getcurangle())),1))+ "\n")
TypeError: float() argument must be a string or a number
i've been through like seven pages of Google for this, but still can't figure out how to code this line so that it doesn't throw this error. Sorry it took so long. The following is from where curangle() is first called.
#Read the IMU to get the angle of incline (forwards/backwards)
#This is what we use for the solar panels, so we have to switch
#from 0 degrees on the normal axis to 0 degrees on the horizon
def getcurangle():
# The escape character for # is \x23 in hex
serialport.write(b"\x23o0 \x23f")
response = serialport.readline()
words = response.split(b",")
if len(words) > 2:
try:
if ((float(words[1]) -90) * -1) < 89:
curangle = ((float(words[1]) -90) * -1)
else:
curangle = 0
except:
curangle = 999
return curangle + AngleOffset
The "b" in .split(b",") was added to the original code to supposedly make this code run under Python-3.x.

Ignoring the exception, if response does not have a "," character to be split, then words[1] will not be filled and can't be converted to a float.
First check to make sure response contains a comma from serialpoint elsewhere in your code.
You can also check this by adding print response and then print words[1] to make sure words[1] is returning a number and not a null value.
With the except, we can assume that the return value is always an int (either words[1] is an int and is returned, or words[1] is not an int and 999 gets returned from the except) so the error is coming from AngleOffset.
Double check the value of AngleOffset.

Related

struct.error: unpack requires a buffer of 2 bytes - file problem

script tells me that unpack requires a buffer of 2 bytes.
maybe someone finds that error.
Thats a script to read a file with hex adresses and compare it with clear text file.
But everytime i get this struct.error
Traceback (most recent call last):
File "/home/starshield/deye/test.py", line 290, in <module>
params.parse(raw_msg, start, end - start + 1)
File "/home/starshield/deye/test.py", line 30, in parse
self.parsers[j['rule']](rawdata, j, start, length)
File "/home/starshield/deye/test.py", line 96, in try_parse_unsigned
temp = struct.unpack('>H', rawData[offset:offset + 2])[0]
struct.error: unpack requires a buffer of 2 bytes
code line 27 to 34:
def parse(self, rawdata, start, length):
for i in self._lookups['parameters']:
for j in i['items']:
self.parsers[j['rule']](rawdata, j, start, length)
return
def get_result(self):
return self.result
code line 91 to 101
for r in definition['registers']:
index = r - start # get the decimal value of the register'
# print("Reg: %s, index: %s" % (r, index))
if (index >= 0) and (index < length):
offset = OFFSET_PARAMS + (index * 2)
temp = struct.unpack('>H', rawData[offset:offset + 2])[0]
value += (temp & 0xFFFF) << shift
shift += 16
else:
found = False
if found:
The last block is from 292 to 299
for i in range(start, end):
value = getRegister(raw_msg, i)
name = "Unknown"
for paramters in parameter_definition["parameters"]:
for item in paramters["items"]:
for reg in item["registers"]:
if reg == i:
name = item["name"]
not able to find the error

How to filter out letters from numbers

I am trying to create a program that calculates the area of a trapezoid, and rejects letters until the user inputs a number but it throws an error at the bottom when I input all the values.
print("Enter 'x' to exit.")
starter = input("Press any key except 'x' to continue: ")
if starter == 'x':
break
else:
print("\nCalculating area of a trapezoid")
base_1 = 5
base_2 = 6
height = input('Height of Trapezoid: ')
while not height.isdigit():
height = input("Error. Please input height as a positive number: ")
base_1 = input('Base one value: ')
while not base_1.isdigit():
base_1 = input("Error. Please input base one as a positive number: ")
base_2 = input('Base two value: ')
while not base_2.isdigit():
base_2 = input("Error. Please input base two as a positive number: ")
print("the area of the trapezoid is: " + str(area = ((base_1 +base_2)/2)*height))
Typical error I receive.
Traceback (most recent call last):
File "P:\$College Class Notes\Python\First Project.py", line 78, in <module>
print("the area of the trapezoid is: " + str(area = ((base_1 +base_2)/2)*height))
TypeError: unsupported operand type(s) for /: 'str' and 'int'
Even though the user is are inputing numbers, input() returns a string. You'll need to cast them to ints yourself.
base_1 = input('Base one value: ')
while not base_2.isdigit():
base_1 = input("Error. Please input base one as a positive number: ")
base_1 = int(base_1)
Also, no need to set area = ((....)) in your print statement. That is actually invalid syntax. You could just remove the area = and it will work, but to make the code cleaner, I'd move your area assignment outside of the print.
area = ((base_1 +base_2)/2)*height
print("the area of the trapezoid is: " + str(area))
In order to get floats, I'd just put it in a try/catch. You can set the while condition to whether base_1 is set or not since if an exception is raised, base_1 still won't be set.
base_1 = None
while not base_1:
try:
base_1 = float(input('Please input a number: '))
except ValueError:
print('Error. Not a number')

OverflowError: character argument not in range(0x110000) using getch in python 3.5

I get overflow error using getch in ubuntu.
This is the code:
import getch
print("Inserisci 8 caratteri esadecimali: ")
allowedChar = '0123456789abcdefABCDEF'
contatore = 0
uuid = ""
while contatore < 8:
char = getch.getch() # User input, but not displayed on the screen
if char in allowedChar:
print(char, end="", flush=True)
contatore = contatore + 1
uuid = uuid + char
uuid = uuid + "-"
print(uuid)
I have to input a UUID but I want to appear only characters allowed (hex digits) but when I type "è" or "ù" or "ò" or "à" I get this error:
Traceback (most recent call last):
File "Char.py", line 7, in
char = getch.getch() # User input, but not displayed on the screen
OverflowError: character argument not in range(0x110000).
Please I need to overcome this error. I need help. I'm not using Windows.

input error in Python3.6

t = int(input())
while t:
qu , pt = input().split(' ')
qu = int(qu)
pt = int(pt)
sd = []
for i in range(0,qu):
x = int(input()) # I think I am getting problem in this part of
sd.append(x)
hd , cw = 0 , 0
diff = pt / 10
cwk = pt / 2
for i in range(0,qu):
if sd[i] <= diff:
hd += 1
else:
if sd[i] >= cwk:
cw += 1
if hd == 2 and cw == 1:
print ('yes')
else:
print('no')
t -= 1
When I try to give input like '1 2 3' I get an an error like this
Traceback (most recent call last):
File "C:/Users/Matrix/Desktop/test.py", line 8, in <module>
x = int(input())
ValueError: invalid literal for int() with base 10: '1 2 3'
Why am I seeing this problem ? How do I rectify this ?
The issue is that you're passing it a string rather than an integer. When you typed "1 2 3," you left spaces, which are considered characters. Spaces cannot be cast as integers. If your set on having the input as number space number space number space, then I suggest you split the sentence at the whitespace into a list.
def setence_splitter(user_input):
# splits the input
words = text.split()
Now you have the list, words, which will have each individual number. You can call each individual number using its index in words. The first number will be words[0] and so on.

Cannot load variable because of not callable str obj

I am having this error no matter what I have tried. I attempted using edf(edf_size), and int(edf_size).
Traceback (most recent call last):
enter code hereFile "C:/Users/Joshua/PycharmProjects/Plane Maker/main.py", line 229, in <module>
file.write("The EDF Thrust Tube is "+ edf() + " inches.\n")
TypeError: 'str' object is not callable
It corresponds with these two sections of code:
edf_size = int(input("Enter the edf size, only the number portion in mm (like 64): "))
character = input("Do you want a plane with speed, power, or both? ")
while True:
if (character == "speed"): break
if (character == "power"): break
if (character == "both"): break
file.write("The EDF size is "+ str(edf_size) + " mm.\n")
file.write("The EDF Thrust Tube is "+ edf() + " inches.\n")
and
#Set edf tube length
def edf():
global edf_size
thrust_tube = (edf_size * 25.4) * 4
return str(thrust_tube)
.
.
.
Please help me I really just dont know why it won't work.
Do you need to use the Global?
Can you try this?
file.write("The EDF Thrust Tube is "+ edf(edf_size) + " inches.\n")
#Set edf tube length
def edf(elf_size):
thrust_tube = (edf_size * 25.4) * 4
return str(thrust_tube)
Also are you sure you are not redefining edf as a string somewhere in your code?

Resources