Variables, Data Types, and if Statements#

legos

Context#

Today we are getting started with code! We’ll be:

  • Thinking about why we code

  • Learning to use a Jupyter notebook

  • Establishing some of the base ingredients in code such as variables, data types, and operators and getting familiar with the associated vocabulary

The different ideas might feel a little disconnected right now, but eventually these building blocks will work together to help us to make more complicated things.

Summary

Jupyter Notebooks#

The primary way of writing code during lessons this summer will be in Jupyter Notebooks. Notebooks are a bit of a unique way of writing code, but they have become popular in data science fields due to the flexbility they give the user to iterate on the same dataset many times and their great visualization support. Read more in depth about Jupyter notebooks here.

Jupyter notebooks are made up of cells, or individual chunks of input. Cells can be either markdown cells, which are made up of text, or code cells. You run the code in a cell by hitting the Run button in the top bar or using shift + enter.

A few links for interested individuals to explore:

πŸ“ Check your understanding

Create a new cell in your notebook. Change it from a code cell to a markdown cell, type something into the cell and then run it.

πŸ‘©πŸ½β€πŸ’» Communicating with the computer#

Programming is about getting a computer to do something for you. You do this all the time when you use a computer. You tell it to access the internet or download a file for you. You tell it take a screenshot and save it to your Desktop. In those scenarios you are telling a computer to do something using your mouse or trackpad. In coding you are telling a computer what to do by learning how to write text that the computer understands.

One of the first tasks programmers ask a computer to do is repeat a line of text back to you. In Python, the instruction for that is print(). Learning what words the computer understands is called learning syntax.

# repeat a line of text back to you: "printing"
# modify it to change the output
print('Hello, world')
print("Boa tarde, mundo")  # single ' and double " are the same in Python
Hello, world
Boa tarde, mundo
# you can also print numbers
print(3.1415927)
3.1415927
# you can print a couple of things together if you seperate them by commas
print('hi ', 8943)
hi  8943
# you can print the output of math calculations
print(4/8+5)
5.5

print statements seem a little useless on their own, but when you have a more complex block of code they are helpful for confirming that what you think is happening is, in fact, happening. They are useful for finding errors in your code as well.

πŸ’‘ Key Ideas

In programming we learn which words the computer understands (aka the syntax of the Python language) and we use those to get the computer to do something for us.

Right now the computer is just parroting back text, but eventually it could be doing huge mathematical calculations, creating a stunning map, or connecting us to an exciting dataset!

πŸ“ Check your understanding

Write a cell of code to display the phrase: I am programming!

πŸ‘£ Assigning Variables#

As programming tasks get more complex we want to be able to keep track of many values at once. We do this is by assigning a name to values we want to keep track of. When we give a value a name it becomes a variable. There are different ways to think about variables that are related to the location of an object on your computer, but for practical use I like this framing.

# Assigning the number 7 to a variable I named x
x = 7
# Assigning the number 2 to a variable I named y
y = 2
# assigning the text 'pineapple' to a variable I named my_lunch
my_lunch = 'pineapple'

How do we see our variables? We print them.

print(x)
print('y is', y)
7
y is 2

πŸ“ Check your understanding

print the sum of your two variables x and y

An example with words instead of numbers

today = 'Sunday' # Change this to be the actual day
tomorrow = 'Friday'
print(today)
Sunday

🌟 Key Clarification - Order of Execution#

One fundamental principle of code is that it executes things in a certain order - from top to bottom.

print('this will print first')
print('this will print second')
this will print first
this will print second

We can make this difference really obvious by using the syntax time.sleep(3) to force Python to wait 3 seconds after it executes the first line.

import time
print('this will print first')
time.sleep(3)  # Wait 3 seconds
print('this will print second')
this will print first
this will print second

If you define a variable and change it further down in the cell the output value will be the most recent value.

today = 'Sunday'
print('print #1', today)
today = 'Thursday'
print('print #2', today)
today = 'Arbor Day'
print('print #3', today)
print #1 Sunday
print #2 Thursday
print #3 Arbor Day

The importance of sequence is also applied to the order in which you run the cells in your jupyter notebook.

today = 'Sunday'
today = 'Monday'
print(today)
Monday

πŸ’‘ Key Ideas

  1. Assiging a variable means giving a name to a value (a number, a piece of text, etc.) that you care about.

  2. You can change the value of your variable. Code executes from top to bottom so you need to follow along to keep track of changes to your variable.

πŸ“ Check your understanding

What is the output of the following lines of code:

x = 7
x = 9
y = x + 2
print('y is ', y, ' and x is ', x)

a) y is 9 and x is 7

b) y is 11 and x is 9

c) y is 9 and x is 9

d) y is 11 and x is 7

e) y is 7 and x is 9

🧩 Data Types#

So far in our code we have used text and numbers as our values. When we talk about our values we often refer to their data type. A data type is a way of classifying a value in Python that allows the computer to understand what it can do with the value.

β€œtext” and β€œnumber” aren’t actually data types in Python, but they do have corresponding data types:

Python Data Type

Plain English

Example

string (str)

text

β€˜Tuesday’ or β€œTuesday”

integer (bool)

whole number

67

float (float)

decimal number

2.9

Notice that with strings we tell Python that we want that as a data type by using quotations, '' or "", around our value.

One more data type I’ll introduce today is the boolean data type. Booleans have two possible values: True or False.

Python Data Type

English

Example

boolean (bool)

yes/no

True or False

# Example boolean
x = True
print(x)
True
# Capitalization matters
x = true
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[17], line 2
      1 # Capitalization matters
----> 2 x = true

NameError: name 'true' is not defined

A list of Python data types can be found here.

πŸ“ Check your understanding

What are the data types of the following values?

x = 9
y = 'stratocumulus'
z = False
i = 3.0
j = '2'
k = "true"

Why do we care about data types? The data type helps the computer understand what types of operations it can do on a value. Consider the + operation. Let’s say we have the following variables:

x = 2
y = 3
a = 'cat'
b = 'fish'

What is the difference between x + y and a + b? Does a + b even make sense? Try them out on your own.

Try it again and this time use a \ sign. What error do you get when you do a/b?

πŸ’‘ Key Ideas

We categorize our variables using data types. This helps us understand what the expected values are.

πŸ”³ Booleans and Comparisons#

Booleans might seem a bit useless on their own, but they become really useful when we get into comparisons, such as greater than, less than, and equal to.

Comparison Operators

This table was taken from the W3 schools Operators page.

Examples

# Example of "equal to" syntax
4+5 == 10
False
# Example of "greater than or equal to" syntax
2**10 >= 1000
True
# Example: Checking if a state code is New York
state_code = 'WI'
state_code == 'NY'
False
# Python math (arithmetic operators)
(8+4+6)/3
6.0

πŸ“ Check your understanding

Evaluate the output of the following:

  1. 2*3 <= 6

  2. 8 == 8

  3. 6 != 3+3

a) True, True, False

b) True, False, True

c) False, True, False

d) False, True, True

e) True, True, True

πŸ’‘ Key Ideas

  • Boolean data types have a value of either True or False.

  • Booleans are especially handy when doing comparisons (Ex. greater than, less than)

Comparing Multiple Items#

If you want to compare more than one thing there are two possible ways to do that, depending on what you want to happen. If you want to compare multiple items and see if they are both true, you use and. If you want to compare multiple items and see if either of them are true, you use or.

Operator

Use

and

checks if both logical statements are True

or

checks if either logical statements is True

True and True
True
True and False
False
True or False
True
True or True
True

Examples

4 == 4 and 5 == 6
# True and False -> False
False
5 < 6 and 6 < 7
# True and True -> True
True
4 == 4 or 5 == 6
# True or False -> True
True

πŸ“ Check your understanding

Evaluate the output of the following:

  1. 5 <= 6 and 5 != 5

  2. 4 > 5 or 5 < 6

πŸ’‘ Key Ideas

  • and and or are ways to compare multiple conditions at the same time.

  • When using and you are asking if all of the items are true. When using or you are asking if any one of the items is true.

❓ if statements#

Often after a comparison we want to make a decision based on if the comparison was True or False. For example,

if the cloud cover was less than 30 percent, start the processing. Otherwise, skip to the next image.

We do that in Python with if statements, which have the following syntax:

if <<True/False statement>>:
    <<do something>>
else:
    <<do something else>>

Statements contained in << >> are placeholders and should be filed with python code. The if, :, else: and indenting are all part of the required syntax for an if statement.

# If statement example
cloud_cover = 50
if cloud_cover < 30:
    print('Good image for processing')
else:
    print('Too many clouds for processing')
Too many clouds for processing

If you have multiple statements you can add in as many as you need after the first if using the syntax elif.

# Including elif
cloud_cover = 35
if cloud_cover < 30:
    print('Good image for processing')
elif cloud_cover < 40:
    print('Potentially usable')
elif cloud_cover < 50:
    print('Only if we are really desperate')
else:
    print('Too many clouds for processing')
Potentially usable

Notice that the if statement is exited as soon as it finds the first statement that returns true, starting from the top. So we can write an if statement like in the following example, but no matter what the code will never hit the elif:

if 3 < 4:
    print('three is less than four')
elif 2 < 4:
    print('two is less than four')
three is less than four

πŸ“ Check your understanding

What will be the output of the following code block?

pH = 3.4
if pH < 7:
    print('acidic')
elif pH == 7:
    print('neutral')
else:
    print('basic')

a) acidic

b) neutral

c) basic

d) acidicneutralbasic

e) acidicbasic

πŸ’‘ Key Ideas

  • If statements allow us to change how our code is executing based on a condition.

  • If statements use indenting as syntax and can also include elif and else. Code exits the if statement as soon as it finds the first True statement.

Wrapping up#

A lot of things happened in this notebook, but they are all ideas that come together to form the building blocks of code!

πŸ“ Check your understanding

Below is a block of code. It includes a lot of functionality that hasn’t been covered, but there are also lots of instances of the concepts from this lesson.

Example code

Find an example of:

  • any kind of operator

  • if statement

  • a variable getting assigned a value

  • a variable changing its value

  • any integer

  • any string

  • any line that will have a Boolean output