# Store data in arrays

Hi Everyone,
Currently I’m working in a GPS project which is using latitude and longitude. I have getting both coordinates from GPS module and I need to store them into Array to further calculations. both coordinates with some decimal points. I hope to store them in arrays as LatitudeData and LongitudeData which can access globally anywhere in main code.

``````import serial

global Degrees, NMEA1, NMEA2, NMEA3, DDD, MMM, Value

LatitudeData = []
LongitudeData = []
global index
def Latitude(NMEA1, NMEA2, NMEA3,):
if NMEA1 == 'A':             # Check Validity
Degrees = NMEA2[:2]
if NMEA3 == 's':
Degrees = int(Degrees)*-1
else:
Degrees = int(Degrees)

Degrees = str(Degrees).strip('.0')
DDD = NMEA2[2:10]
MMM = float(DDD)/60
MMM = str(MMM).strip('0.')[:6]
Value = Degrees + "." + MMM
return Value
else:
return 0.0
print("Location Invalid")

def Longitude(NMEA1, NMEA2, NMEA3,):
if NMEA1 == 'A':
Degrees = NMEA2[1:3]

if NMEA3 == 'w':
Degrees = int(Degrees)* -1
else:
Degrees = int(Degrees)
Degrees = str(Degrees)
DDD = NMEA2[3:10]
MMM = float(DDD)/60
MMM = str(MMM).strip('0.')[:6]
Value = Degrees + "." + MMM
return Value

else:
return 0.0
print("Location Invalid")

try:
gps = serial.Serial('com5', 115200)
while True:
decode = packet.decode('unicode_escape')
data = decode.split(",")
# print(data)
if data[0] =='\$GNRMC':

# print(data)
Output1 = Latitude(data[2], data[3], data[4])
print(Output1)
Output2 = Longitude(data[2], data[5], data[6])
print(Output2)

index = 0
LocationData1[index] = Output1
LocationData2[index] = Output2
index = index + 1
if index == 9:
index = 1
except serial.SerialException:
print("Error in Communication")
``````

I hope to store 10 values to each array and get mean value. So how to do this. I’m new to python coding and I tried several ways but couldn’t find some solution. So I need your comments.

Thank You.

Global declarations only have a meaning inside functions, so you can remove these useless lines:

``````global Degrees, NMEA1, NMEA2, NMEA3, DDD, MMM, Value
global index
``````

Possibly you need to move them inside the functions, but where they are, they do nothing.

Execution of the function exits at a return statement, so this print will never run:

``````        return 0.0
print("Location Invalid")
``````

Get rid of this `try...except` block:

``````try:
# lots of code
except serial.SerialException:
print("Error in Communication")
``````

Trust me, when you try to debug your code, and you get a useless error message “Error in Communication”, you will curse the person who wrote that. What sort of error?

Believe me, there is nothing worse that trying to debug code that hides the error and doesn’t tell you what happened or why it happened.

“Error in Communication” is nearly as bad as “An error occurred”.

If you want to do something 10 times, instead of using a `while True` infinite loop, use a for-loop:

``````for i in range(10):
# This block will execute ten times.
``````

If you want to collect the longitudes and latitudes into lists, instead
of printing them, append them to the list:

``````# Instead of this:
Output1 = Latitude(data[2], data[3], data[4])
print(Output1)

# Do this:
Output1 = Latitude(data[2], data[3], data[4])
LatitudeData.append(Output1)
``````

Your code tries to write data to two variables that don’t exist:

``````# This code will fail, because the variables don't exist.
LocationData1[index] = Output1
LocationData2[index] = Output2
``````

Once you have your ten data points, please reply to this with a new post, showing the result of

``````print(LongitudeData, LatitudeData)
``````

so we can see what you have and then we can help you work out the average (mean).

1 Like

By Indula_Karunathilaka via Discussions on Python.org at 12Jul2022 04:53:

Currently I’m working in a GPS project which is using latitude and
longitude. I have getting both coordinates from GPS module and I need
to store them into Array to further calculations. both coordinates with
some decimal points. I hope to store them in arrays as LatitudeData and
LongitudeData which can access globally anywhere in main code.

Minor note that in larger programmes we tend to avoid globals. In a
small programme they work ok.

import serial

global Degrees, NMEA1, NMEA2, NMEA3, DDD, MMM, Value

LatitudeData =
LongitudeData =
global index

There’s no point to “global” statements at the module level (your
script’s outermost level). This is because “global” is the
outermost/module level. So anything you assign to outside a function

The purpose of `global` is to be used inside a function to say that a
variable name comes from the module level namespace. In Python the scope
of variables is implicit:

• if you assign to a variable, it is local to the function (if you
have not said it is `global`); note that this actually means: if the
function has an assignment to the variable anywhere in it
• if you access a variable, it is sought in the function local
namespace, but if not found it is sought in the global namespace (and
then further in the builtins, which is where things like `print` come
from)

So:

``````x = 1  # global variable

def f(n):
print(n)
x = n + 1
print(x)

print(x)    # prints 1
f(x)        # prints 1 and then 2
print(x)    # prints 1
``````

because `x` inside the function is a local variable, because there
is an assignment to `x` inside. Out of the function again, `x` refers to
the global, and prints 1, because the global was unchanged.

Compare:

``````x = 1  # global variable

def f(n):
global x  # x refers to the global variable
print(n)
x = n + 1
print(x)

print(x)    # prints 1
f(x)        # prints 1 and then 2
print(x)    # prints 2
``````

The only different here is that inside the function we have declared
that `x` will come from the global (module) namespace. So assigning to
it now changes the global variable.

All of that said, we tend to use `global` very rarely.

def Latitude(NMEA1, NMEA2, NMEA3,):
if NMEA1 == ‘A’: # Check Validity
Degrees = NMEA2[:2]
if NMEA3 == ‘s’:
Degrees = int(Degrees)*-1
else:
Degrees = int(Degrees)

``````   Degrees = str(Degrees).strip('.0')
``````

A note: the `.strip('.0')` is probably not doing what you intend. It
strips all `'0'` or `'.'` characters from the front and the back of
the value. That’s probabably more than you intend.

[…]

else:
return 0.0
print(“Location Invalid”)

Because the `return` happens first, the `print` will not run. You
probably want to switch these around.

try:
gps = serial.Serial(‘com5’, 115200)
while True:
decode = packet.decode(‘unicode_escape’)
data = decode.split(“,”)
# print(data)
if data[0] ==‘\$GNRMC’:

``````       # print(data)
Output1 = Latitude(data[2], data[3], data[4])
print(Output1)
Output2 = Longitude(data[2], data[5], data[6])
print(Output2)

index = 0
LocationData1[index] = Output1
LocationData2[index] = Output2
index = index + 1
if index == 9:
index = 1
``````

except serial.SerialException:
print(“Error in Communication”)

``````
I hope to store 10 values to each array and get mean value. So how to do this. I'm new to python coding and I tried several ways but couldn't find some solution. So I need your comments.
``````

I’d `print("index =", index)` at various points in your loop. You’ll
probably see what’s happening then. Also `print(LocationData1)`, it
should be quite illuminating.

You’re settings `index=0` every time. I would do that once before the
loop. As it is, you’re always filling in the first array element.

See what this shows you about what’s going on.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like

Thank You @steven.daprano and @cameron for your comments. I really appreciate that.