Variable and Function#

1. Create and Use of Variables#

  • Variable is a container of data.

  • Unlike other programming languages, Python has no explicit command for declaring a variable and no need to specify the variable’s type.

  • A variable is created the moment you first assign a value to it.

  • After the creation of a variable, it can be referenced, modified and deleted.

Naming Rules

  • A variable name must start with a letter or the underscore character, but cannot start with a number;

  • A variable name can only contain alpha-numeric characters and underscores, i.e., A-z, 0-9, and _;

  • Variable names are case-sensitive (age, Age and AGE are 3 completely different variables);

  • Avoid using Python reserved words as a variable’s name, such as str, max.

1.1 Declare a variable#

# valid names
my_name = "Michael"
_my_name = "Michael"
__my__name = "Michael"
myName = "Michael"
MyName = "Michael"
# invalid varialbe name example: space is invalid
my name = "Michael"  
  File "C:\Users\chjch\AppData\Local\Temp\ipykernel_16276\3326325253.py", line 2
    my name = "Michael"
       ^
SyntaxError: invalid syntax
# invalid variable name example: dash/hyphen is invalid (all special characters)
my-name = "Michael"  
  File "C:\Users\chjch\AppData\Local\Temp\ipykernel_16276\3539178090.py", line 2
    my-name = "Michael"
    ^
SyntaxError: cannot assign to operator
# invalid variable name example: starting with a number is invalid
1st_name = "Michael"
  File "C:\Users\chjch\AppData\Local\Temp\ipykernel_16276\2344343295.py", line 2
    1st_name = "Michael"
     ^
SyntaxError: invalid syntax

Good naming strategy:

  • Choose meaningful name instead of short name. num_course is better than nc.

  • Maintain the length of a variable name. number_of_courses_in_spring2020 is too long.

  • Be consistent; num_course or numCourse or NumCourse.

Tip

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Name variables in a more descriptive fashion is always preferable.

1.2 Declare Multiple Variables Simultaneously#

a, b, c = "Orlando", 2, "Gainesville"
print(a)
print(b)
print(c)
Orlando
2
Gainesville
x = y = z = 100
print(x)
print(y); print(z)
100
100
100

2. What is a function in Python#

  • a block of code which only runs when it is called

  • use the def keyword

  • pass data, known as arguments, into a function

  • return a result after a series of operations

2.1 Define a function#

def my_func():
    pass
my_func
<function __main__.my_func()>
def hello_world():
    print('hello_world')

2.2 Run (call) a function#

hello_world
<function __main__.hello_world()>

You need to include a pair of parentheses () to execute a function.

hello_world()
hello_world

2.3 Function with arguments#

def pet_favor(pet_name):
    print("I like " + pet_name + ".")
pet_favor("dog")
I like dog.

Note

In general, we should follow the same naming strategy for functions as described above for variables.

2.4 Function returns an output#

def multiply(a, b):
    return a * b
multiply(3, 4)
12
# assign the output of a function to a variable
result = multiply(3, 4)
print(result)
12

3. An Example Function#

Here, we look at two examples of relatively more practical functions. The first one will convert lat/lon coordinates from Degrees Minutes and Seconds (DMS) to Decimal Degrees (DD). The second function will do the conversion in the opposite direction.

3.1 From DMS to DD#

Coordinates of the University of Florida:

  • latitude = 29°38’34.98” N

  • longitude = 82°21’16.47” W

def dms_dd(degree, minute, second):
    dd = degree + minute/60 + second/3600
    return dd
dms_dd(29, 38, 34.98)
29.64305
print(
    "latitude is {}, and latitude is {}".format(
        dms_dd(29, 38, 34.98),
        -dms_dd(82, 21, 16.74)
    )
)
latitude is 29.64305, and latitude is -82.35464999999999

3.2 From DD to DMS#

Three things to learn:

  1. Be aware of the precision issue when dealing with floating points

    • how does int() function work (truncating)

    • use the round() function to round decimals.

  2. Be comfortable with using .format() string.

  3. The escape character in strings \.

    • \' –> ‘

    • \" –> “

    • \\ –> \

Tip:

  • Hold down Alt key and type 248 on the numeric keyboard.

print(round(0.7))
print(round(0.5))
1
0
round(3.1415926, 2)
3.14
int(0.7)
0
def dd_dms(dd):
    degree = int(dd)
    minute = int((dd - degree) * 60)
    second = round((dd - degree - minute/60) * 3600, 2)
    return "{}°{}'{}\"".format(degree, minute, second)
print("latitude: {} N.".format(dd_dms(29.64305)))
print("longitude: {} W.".format(dd_dms(82.354575)))
latitude: 29°38'34.98" N.
longitude: 82°21'16.47" W.

4. Import a function from another module#

  • module: any python code saved in a file (.py)

  • we can store our own Python function in a .py file

  • the function can then be imported as a regular Python module we imported (e.g., random)

  1. Create a new .ipynb file

  2. Save the .ipynb file to a .py file

  3. Import the function from the module

We can import the module (.py file) first, and then use . to access the function defined in the module.

import latlonconv

latlonconv.dd_dms(29.64305)

Or, we can directly import the function itself, using the from <module> import <function> method.

from latlonconv import dd_dms

dd_dms(29.64305)

Fix for Importing error

When running Python Notebook inside ArcGIS Pro, there’s a chance that the current path of the notebook isn’t added to the system paths. To fix that, you can manually insert the path containing your .py file to the system paths.

import sys
sys.path.insert(0, r"your\own\path")