Intro to Python

2023 NGA LTER REU Students

Contains brief coverage of:

  • Printing cell outputs (and comments)
  • Variables and type
  • Structured Data Types
  • Control structures (loops)
  • Functions

Designed to take ~1 hour when combined with the Colab Welcome Notebook

Printing cell outputs (and comments)

  • output of last line will print to output cell
  • print() function also
  • comments don’t print
1
2
3
3
print(1)
print(2)
print(3)
1
2
3
# print(1)  command + / toggles line comment
# print(2)
# print(3)

Can do simple math

Use it like a calculator

1 + 2
3
4.6705 ** 3.8
349.60757209480767

Define variables

Define variables with =. The variable is on the left and the value is on the right.

Each of these has a type that defines what you can do with it. In other words, they are objects that have attributes and behavior. The list of built in types is at https://docs.python.org/3/library/stdtypes.html. Includes

  • int = integer number
  • float = floating point number
  • boolean = True or False
  • string = a list of characters

Start with the example from the Colab Welcome.

seconds_in_a_day = 24 * 60 * 60
seconds_in_a_day
86400
# this is the type of our variable

type(seconds_in_a_day)
int
# here is a more interesting type that has lots of functions and methods

text = "YOU DO NOT NEED TO SHOUT"

print(len(text))     # this is function - argument could be many objects

print(text.lower())  # this is method - specific to a single object

print(text + '!!!!') # can do math
      
type(text)
24
you do not need to shout
YOU DO NOT NEED TO SHOUT!!!!
str
# do they mix?  Nope. This causes an error.

#text + seconds_in_a_day

Values of variables can change

Well, of course they can. That is what programming is for.

But not everything that looks like an assignment is.

And using a Notebook, the order of operations matters. You can go back and run previous cells over again and get some very strange looking output. Try running these 3 cells in various orders.

seconds = 12
seconds
12
seconds = seconds + 60
seconds
72
print(seconds + 6)
seconds
78
72

Structured data

In addition to variables with a single value, there are other types that have multiple elements. The main ones are

  • List
  • Dictionaries
  • (Set)
  • (Tuple)
  • (Range)
# List = multiple values in order
# This is a new type

casts = [12, 13, 14]
print(type(casts))
<class 'list'>
# They can contain values of multiple types

cruise = ['SKQ202010S', 12, 7.5, 32.666, 'Summer']
print(cruise)
['SKQ202010S', 12, 7.5, 32.666, 'Summer']
# Can retrieve values by using the indices, just like strings
# can get a subset of the list back

print(cruise[0])
print(cruise[:3])
print(cruise[-3:])
SKQ202010S
['SKQ202010S', 12, 7.5]
[7.5, 32.666, 'Summer']
# Dictionaries are collections of key:value pairs


cruise = {'id': 'SKQ202010S',
          'temperature': 7.5,
          'cast': 12}
          
print(cruise)
{'id': 'SKQ202010S', 'temperature': 7.5, 'cast': 12}
# To retrieve values, use the key

cruise['id']
'SKQ202010S'
# unlike lists, they are unordered. This causes an error

#cruise[0]

Data Workflows and Automation

There are other commands that control the order of operations in a program. These can repeat commands or choose some commands instead of others.

  • Many of these rely on Booleans: tests of True/False.
  • Note the use of : to signify the start of a loop
  • Note the use of 4 spaces to indicate the commands that will be repeated
    • MATLAB uses the keyword end instead of indentations
# "while" repeats an operation while a condition is True

n = 0
while n < 5:
    print(n)
    n = n + 1
0
1
2
3
4
# "for" will do the same repetition, with a different syntax

for n in [0, 1, 2, 3, 4]:
    print(n)
0
1
2
3
4
# "if" will determine whether to execute or not

for n in [0, 1, 2, 3, 4]:
    if n % 2 == 0:  # if n is even
        print(n)
    else:           # if n is odd
        print('hi!')
0
hi!
2
hi!
4

Functions

For more complicated sets of instructions that will be repeated, or logic you want to keep separated for whatever reason, you can define a function. print() and len() are examples of functions we have already used.

  • Start the function definition with keyword def. Again there is an :
  • Again, indented with spaces
  • When call it, need parentheses even if there are no arguments
def is_even(n):
    if n % 2 == 0:
        return True
    else:
        return False

for n in [0, 1, 2, 3, 4]:
    if is_even(n):     # call our function
        print(n)
        print()        # parentheses without arguments
0

2

4

Packages

By default, you have access to only a few object classes and functions. But you can import (and create) packages and modules that enable many many more. To do this, use import. This is typically at the beginning of your Notebook or script, but it can go anywhere.

The Standard Python Library (https://docs.python.org/3/library/) contains those that are supported by and installed with Python. math is in the Standard Library. See https://docs.python.org/3/library/math.html for more information on it.

Others are available via pip or conda. numpy and pandas are examples of these.

import math

math.log10(10)
1.0
from math import pi, cos

cos(pi)
-1.0