Search code examples
pythonpython-3.7

Missing variable when trying to write to file


Can anyone see where I'm going wrong? I'm just writing variables to a file to check that everything is as expected. Everything works except 'y'. Why doesn't 'y' get written to the file? It could be obvious but I just can't see the error. Works in python shell but not in my script. Python 3.7 on RPi3.

QS = request.args.get('q')
xVal,yVal = QS.split('.')
x = xVal
y = yVal*-1

path = 'debug.txt'
dataRec = open(path, 'a')
debugInfo = (str(QS) + ' xVal is ' + str(xVal) + ' yVal is ' + str(yVal) + ' Y is ' + str(y) + '\n')
dataRec.write(str(debugInfo))
dataRec.close()

Output to debug.txt

-7.-70 xVal is -7 yVal is -70 Y is
-7.-70 xVal is -7 yVal is -70 Y is
-7.-70 xVal is -7 yVal is -70 Y is
0.0 xVal is 0 yVal is 0 Y is

I'd appreciate any help before I go insane!!


Solution

  • The values are strings. You need to convert them to ints before you multiply them:

    y = int(yVal)*-1
    

    But why it's empty now? Because string *n gives that string repeated n times. Negative numbers are considered the same as 0, making y an empty string.