download notebook
view notebook w/o solutions
Python basics: Part 1
files needed = none
Before we can start working with data, we need to work out some of the basics of Python. The goal is to learn enough so that we can do some interesting data work—we do not need to be Python Jedi.
In this book we will cover 1. Assignment 2. Calculation 3. Help 4. Strings
Remember: Ask questions as we go.
Assignment
Run the following code block (ctrl+enter
). What does the code do?
# Assign the value 10 to the variable x
x = 10
# Print the value of x to the screen
print(x)
10
Key concept: In the code cell above, you assigned the value of 10 to the variable named x
. When we asked the Python interpreter to print x
, it printed the value assigned to x
.
The print()
function is a built-in python function. More on it later.
When writing in a code block, we use the pound sign (#) to create a comment. The python interpreter ignores what follows the #. You can put a comment on the same line as some code. (So we use # to make comments in code blocks and we use # to make headers in markdown blocks.)
Typically, comments are used to help explain to someone reading your code (often yourself at a later date) what is being done, or what a line is used for. Good coding practice means including comments when it is not obvious what you are doing from one line to the next, or to explain what a function is used for. Take note of how we use comments in these notebooks to help guide you through concepts!
# Variable names should typically be self-documenting
my_age = 40 # I am old!
print(my_age)
40
I used the underscore symbol in my variable name to make it more readable. Variable names must start with a letter or an underscore. Names can include letters, numbers, and underscores. Variable names are case sensitive. Before running the code below, what do you think the output will look like?
myAge = 25 # My auto insurance is much cheaper
myage = 35 # I can run for president
MYAGE = 50 # I can join AARP
my_age_2 = 16
print(myAge)
print(myage, MYAGE)
print(my_age, my_age_2, myAge)
25
35 50
40 16 25
We can print multiple variables from the same print statement. Notice that the my_age
variable from the earlier code block is available to me in later code blocks. What happens when you run the following code?
2_my_age = 5
File "<ipython-input-5-8140e86d2413>", line 1
2_my_age = 5
^
SyntaxError: invalid decimal literal
two_my_age = 5
Key concept: When we try to run code with mistakes, the interpreter stops and displays an error message. The error message will typically give us a clue as to what went wrong.
The "syntax error" message tells us that we broke one of python's rules. The caret (the ^ symbol) is pointing at where the problem occurred. In this case, we started a variable name with a number.
# Assign the value in my_age_2 to another variable
my_age_3 = my_age_2
print(my_age_2, my_age_3)
my_age_2 = 17
print(my_age_2, my_age_3)
16 16
17 16
Calculation
Computers are very good at calculating...
# Multiplication
z = 2*3
zz = 2 * 3
zzz = 2 * 3
print('This is z, zz, and zzz.')
print(z, zz, zzz)
# Did the whitespace matter?
This is z, zz, and zzz.
6 6 6
z_mult = z * zz
print('What is z times zz?')
print(z_mult)
What is z times zz?
36
Notice that we can use the print()
function to directly print messages to the screen. We put the text to be printed inside of single quotation marks. When we do that, we are creating a string data type. More on that soon.
Remember to consider the order of operations. Python will generally obey "PEMDAS" (or whatever you're used to calling it) but it is a good idea to use parentheses to separate operation from each other. Square brackets [ ]
and curly brackets { }
can't be used for mathematical operations in Python; they will be used for something entirely different (that we will see later).
# This obeys PEMDAS
x_1 = 3 + 4 * 2
print(x_1)
# To make this more legible, we use parentheses
x_2 = 3 + (4 * 2)
print(x_2)
11
11
# Note that brackets in Python can't be used as a separator
# Don't worry about what this error means just yet.
x_3 = 3 + [4 * 2]
print(x_3)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-42a1c12d9b18> in <module>
1 # Note that brackets in Python can't be used as a separator
2 # Don't worry about what this error means just yet.
----> 3 x_3 = 3 + [4 * 2]
4 print(x_3)
TypeError: unsupported operand type(s) for +: 'int' and 'list'
# Division
b = 10/2
bb = 20/5
bbb = 6/4
print(b, bb, bbb)
5.0 4.0 1.5
When we used division, the answers were displayed with decimal points, but when we multiplied they were not. Python is creating different types of variables.
Key concept: Every object in Python has a type. There are several types (integer, float, string, list...) which we will learn about as we proceed. You can learn about a variable's type using the type()
function. We have been dealing mostly with integers so far. Dividing two integers (10 and 2, for example) creates a float (5.0).
You can learn about a variable's type using the type()
function.
print(b)
print(type(b))
print(z)
print(type(z))
5.0
<class 'float'>
6
<class 'int'>
Types are important. Different types of objects can do different things. We will see this often in class.
Lastly, here are a few more mathematical operations. You are not likely to use integer and modular division very often, but it is worth knowing they exist.
# Exponents (note that it is not ^)
a = 2**3
print(a)
8
# Integer division (the quotient of dividing 13 by 5 is 2)
13//5
2
# Modular division (the remainder of dividing 13 by 5 is 3)
13%5
3
Practice: Calculation
Take a few minutes and try the following. Feel free to chat with those around if you get stuck. I am here, too.
- Suppose you lend \$300 for one year at 5 percent interest. What is the repayment amount? Create the variable
principal
and set it to 300 and the variablei
and set it equal to 0.05. Create a variable namedpayoff
to hold the payoff amount. Print the value of the payoff.
principal = 300
i = 0.05
payoff = principal*(1+i)
print(payoff)
315.0
- In a code cell, enter
r = 5
r = r+1
and run the cell. What is the value of r?
r = 5
r = r + 1
print(r)
6
- In the code cell below, enter
r=r+1
print(r)
and run the code. What happened?
r = r + 1
print(r)
11
Rerun the previous cell (ctrl+enter
). What is the value of r
? Rerun the cell again. And again. What is happening?
- In a code cell, set
m=2
andn=3
. Write some code that swaps the values ofm
andn
, so thatm=3
andn=2
.
# Initialize the variables
m = 2
n = 3
print('n=', n, 'm=', m)
# Now swap
temp = m
m = n
n = temp
print('n=', n, 'm=', m)
# There are easier ways to swap variables. We will see this later...
n= 3 m= 2
n= 2 m= 3
Help, or object introspection
The Jupyter Notebook has an easy way to get help about an object. In a code cell below, enter print?
to learn about the print function.
print?
Now try r?
r?
In general, we can use the ?
to learn about any object in our programs.
Strings
Strings are collections of characters. Python is very good at manipulating strings, whereas languages like MATLAB and STATA are less so. (More on this in the future.)
In Python, we put strings into quotation marks to assign them to variables. Either single or double quotes will do. These are all legitimate strings:
name = 'Kim Ruhl'
address = "7444 Soc Sci"
zip_code = '53705'
Notice that zip_code
looks like an integer. It is not! Let's try it out.
name = 'Kim Ruhl'
address = "7444 Soc Sci"
zip_code = '53705'
print(zip_code)
53705
# Why would I want to divide a zip code by 3? I have no idea!
z = zip_code/3
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-30-f540f1f0f3dc> in <module>
1 # Why would I want to divide a zip code by 3? I have no idea!
2
----> 3 z = zip_code/3
TypeError: unsupported operand type(s) for /: 'str' and 'int'
# What type of object is zip_code?
print(type(zip_code))
print(zip_code)
<class 'str'>
53705
We asked Python to divide a string by an integer. It does not know how to do that.
Python does know how to do some "math" with strings.
first = 'Bucky'
last = 'Badger'
name = first + last
print(name)
BuckyBadger
What does first*2
do? What about 2*first
?
print(first*5)
print(10*first)
BuckyBuckyBuckyBuckyBucky
BuckyBuckyBuckyBuckyBuckyBuckyBuckyBuckyBuckyBucky
Quotation marks
Single and double quotes do the same thing. The statements first_name = 'Kim'
and first_name = "Kim"
do the same thing.
We need double quotation marks when the string contains a single quote. The statement opinion = "I don't like hot weather"
works because the Python interpreter knows the string is contained in the double quotes, so it treats the single quote as a character.
opinion = "I don't like hot weather"
print(opinion)
I don't like hot weather
opinion_2 = 'I don't like hot weather'
print(opinion_2)
File "<ipython-input-35-0a4dfffcf0f9>", line 1
opinion_2 = 'I don't like hot weather'
^
SyntaxError: invalid syntax
To avoid issues with single quotes and apostrophes, we can "escape" the character (tell Python not to interpret it as a quote) using \
before it, as such:
'I don\'t like hot weather'
opinion_3 = 'I don\'t like hot weather'
print(opinion_3)
I don't like hot weather
Lastly, we can use triple quotes (made up of either single or double quote characters) to create strings that break over several lines.
second_coming = """
Turning and turning in the widening gyre
The falcon cannot hear the falconer;
Things fall apart; the centre cannot hold;
"""
print(second_coming)
Turning and turning in the widening gyre
The falcon cannot hear the falconer;
Things fall apart; the centre cannot hold;
print(second_coming + "another part of the poem")
Turning and turning in the widening gyre
The falcon cannot hear the falconer;
Things fall apart; the centre cannot hold;
another part of the poem
A second use of triple quotes is to create long comments. We have been using #
to create comments in our code, but we can also triple quotes. You will often see a triple quote at the beginning of a program.
"""
This program adds two numbers together.
Kim J. Ruhl
August 14, 2018
"""
This bit of code will not do anything because it is not assigned to a variable. It is only there for humans to read.
"""
This program adds two numbers together.
Kim J. Ruhl
August 14, 2018
"""
a = 88
b = 22
print(a+b)
110
Practice: Strings
Take a few minutes and try the following. Feel free to chat with those around if you get stuck. The TA and I are here, too.
-
In which of the following is x a string? Edit this markdown cell and type 'string' or 'not string' next to each example.
-
x = '10' (string)
- x= 10 (not string)
- x= "Hello World" (string)
- x = 'Lake Mendota' (string)
- x = 3.5 (not string)
-
x = 'ruhl2@wisc.edu' (string)
-
Fix this expression:
whose_car = 'Jane's'
- In our first and last name example, our output was
BuckyBadger
. Go back and fix your code so thatname
has a space between the first and last names. When you printname
, it should look like:Bucky Badger
.
whose_car = 'Jane\'s'
print(whose_car)
Jane's
name = first + ' ' + last
print(name)
Bucky Badger
sp = ' '
name = first + sp + last
print(name)
Bucky Badger