Class 2: Python basics

This is a quick introduction progamming with Python (Python 3 in particular). An excellent print resources is Python Programming for Beginners by Jason Cannon. Part 1: Programming in Python of Thomas J. Sargent and John Stachurski’s Python lectures at http://lectures.quantecon.org/py/index.html also contains a nice introduction.

Functions and the help() function

A function is a block of reuable code that does something. Each function has a name and the name is used to call the function. Sometimes functions require one or more inputs called arguments. Individual arguments may be either required or optional depending on the function. Python includes several built-in functions. You may also create a user-defined function by defining your own function and we'll cover how to do that later.

Two of the most important built-in functions are the print() and help() functions. The print() function does what you think it might: it prints the value of whatever is inside the parentheses. For example:


In [1]:
# Print the first several digits of pi (3.14159...):

Notice that the line # Print the first several digits of pi: doesn't do anything. In Python, any line that begins with the # symbol is a comment line. Comments are ignored by the Python interpretter and are used to provide notes to the program author and to others about what the code does. Good comments make code much more readable and it's good practice to thoroughly comment your code.

Now, suppose that I didn't know how to use the print() function. How could I learn how to use it? One option would be to search the internet for documentation or examples and this is a completely reasonable thing to do. Another option is to use another built-in function help(). For example:


In [2]:
# Use the help function to learn about the print function

The output indicates that print() has the following arguments value, ..., sep=' ', end='\n', file=sys.stdout, flush=False. Of the arguments, value, ... refers to an arbitrary set of values separated by commas and these are required. The other arguments are keyword arguments and they have default values (you can tell because of the equals signs) so they're optional. So suppose that I want to print out the numbers 1, 2, 3, 4, 5:


In [3]:
# Print the numbers 1 through 5:


# Print the numbers 1 through 5 separated by a comma:


# Print the numbers 1 through 5 separated by a comma and a space:

You can find a list of the built-in functions for Python here: https://docs.python.org/3/library/functions.html. We'll encounter several of them later. In the meantime, try using the help() function to find out what some of the other built-in functions do.

Error Messages

If you spend more than about 30 seconds with Python, then you're going to encounter an error message. Fortunately, Python's error messages often give youthe location in your code of the err the error in your code is and a description of the error. For example, the following block of code returns an error:


In [4]:
# print the value of an as-yet undefined variable called x

In trying to print the value of the variable x, we're told that there is a NameError beacuase 'x' is not defined. This means that a value for x should be assiged before calling the print() function. The following block works because it assigns a value to x before calling print():


In [5]:
# Set the value of x equal to the constant c = 2.71828... and print x

You should carefully read error messages because most of the time they point directly to the problem.

Variables

A variable is a named location in the computer's memory that stores a value. When you create a variables, you specify the name of the variable and you assign a value to that variable using something like:

variable_name = value

Here

  • variable names are case-sensitive.
  • variable names can contain letter, numbers, and underscores "_"
  • variable names must start with a letter or an underscore

Some examples of valid variable names:

  • x, y, and z
  • variable1 and variable2
  • capital and labor
  • arg_max and arg_min
  • homeAddress and workAddress

You should try to give variables meaningful names to make your code easier to read. For example, if you have a variable that stores the value of GDP for a county, then naming the variable gdp or output instead of y will improve the readability of your code.


In [6]:
# Create a variable called x that is equal to 10


# Create a variable called y that is equal to 3


# Print the values of x and y


# Create a variable called z that is equal to x / y and print the value of z

Everything in Python is an object and all objects have types. Among other things, an objects type determines what operations may be performed on the object and so it's worth getting making sure that you know the type of every variable you create. You can check the object type of a variable using the built-in function type().


In [7]:
# Print the types of x and z

Strings

Strings are representations of text. They are useful for printing the output of a routine, for supplying text properties of graphs like titles and legend entries, and for storing some types of data; e.g., html code for a webpage or names of a group of people.

Create a variable with a string value by using either single quotations ' or double quotations ". So, for example:

`first_name = 'Brian'`
`last_name = "Jenkins"`

will create two variables to store my first and last names. Use of the double or single quotations is a matter of prefernce but you should be consistent. Pick which you prefer and stick with that. Note that if you want to create a string containing a single quote, then you should either use double quotes around the string characters or use \' for the single quote:

option1 = "Brian's"
option2 = 'Brian\'s'

In [8]:
# Create a variable called first_name and set it equal to your first name.


# Create a variable called last_name and set it equal to your last name.


# Print the type of the variable first_name

Concatenating strings

Strings can be added together or concatenated using the "+" sign. For example:

'ant'+'eater'

returns:

'anteater'

In [9]:
# Use string addition to definine a new variable called first_last that 
# is equal to your first and last names separated by a space and print



# Use string addition to definine a new variable called last_first that 
# is equal to your last and first names separated by a comma and space
# and print

Indexing strings

Each character in a string is assigned a value called an index. String indices (and most indices in Python) begin with 0. So the first character of a string has an index of 0, the second has an index of 1, and so on.

You can use indices to slice into a string. For example, I can find the first letter of my name:

first_name[0]

returns:

'B'

Note that we use square brackets when slicing into a string. You can also use indices to slice out a range of values. For example, to print the first two letters of my name, I'd use:

first_name[0:2]

In the last command, Python interprets [0:2] to mean characters starting with an index of 0 up to but not including the character with an index of 2. And to print all but the first letter:

first_name[1:]

Here, Python interprets [1:] to mean every character with an index of 1 or greater. Finally, note that you can access the last character of a string by couting backward:

first_name[-1]

this is nice if you don't know how many characters are in a string.


In [10]:
# Use string indexing to print the third letter of your first name


# Use string indexing to print the first 2 letters of your first name


# Use string indexing to print the last 3 letters of your last name

Other string operations and methods

Without skipping ahead too much, it's worth knowing that some objects in Python have methods: special functions definied to run against an object. It's easiest to see what this means my example.

The lower() method is a string method that returns the value of a string with all letters replaced by lowercase letters.

drink = 'CoFfEe'
drink.lower()

will return:

'coffee'

Notice that we accessed the method by entering the variable name followed by a dot followed by the name of the method and then a set of parentheses. lower is a function that is defined only on string objects. We'll use methods extensively later on.

Notice that lower() does not affect the value of the variable. If we wanted to change the value of the variable drink to all lowercase letters, then we'd have to run:

drink = drink.lower()

See https://docs.python.org/2/library/stdtypes.html#string-methods for a list of available string methods.


In [11]:
# Use the lower() method on first_name to print your first name in all lowercase letters


# Use the upper() method to print your first name in all capital letters

Math and numbers

Python understands some basic number types: integers, floating point numbers (decimals), and complex numbers. It makes sense to distinguish between these types of numbers because computers store round numbers like integers differently from floating point decimals.

The Python interpretor understands the following operations on numbers

  • + : add
  • - : subtract
  • * : multiply
  • / : divide
  • ** : exponentiate

Note the carat "^" is not used for exponentiation and instead has an entirely differnt use in Python.


In [12]:
# Print the squareroot of 3.

Modules for mathematics

The Python interpreter does not have built-in functions for common mathematical functions like the sine, cosine, log, or exponential functions. To access with these functions you need to import one of several modules that have these functions.

The math module is part of the standard Python library. See the documentation here: https://docs.python.org/2/library/math.html#module-math). Another widely-used resource is NumPy. NumPy is much more elaborate and powerful than math and is available with Anaconda installations. Here's the website for NumPy: http://www.numpy.org/. We'll look at NumPy later.

Suppose that you want to compute the natural log of 10 using the math module. There are two ways to go about this. First, you can import the math module and then use the use the math.log function:

import math

x = math.log(10)

With this approach, you import the entire module and then access the log() in the math namespace. An alternative would be to import only the function that you needed:

from math import log

x = log(10)

The first approach has the disadvantage that all of the functionality of the module is loaded into memory while only one function is actually needed. The advantage of the first approach though is that the log name is kept neatly in the math namespace.


In [13]:
# Import the math module


# Print the square root of 2


# Print the factorial of 5


# Print the mathematical constants pi and e

In [14]:
# Import the numpy module as np


# Print the square root of 2


# Print the factorial of 5


# Print the mathematical constants pi and e

Note that in the previous examples, math.log and np.log refer to functions with the same names but in different namespaces.

More about numbers

Python distinguishes between integers (whole numbers) and floating point numbers (decimals). Floating point numbers have decimals in them. For example, while a person might regard 2 and 2. as the same number, Python views these as two different types of numbers:


In [15]:
# Print the types of 2 and 2.

Most of the time floating point numbers will work for us. Integers arise when working with things that can be enumerated (like arrays) or with data for which decimals would make no sense (e.g., ZIP codes). If a math expression involving only integers returns a non-integer, then Python returns a number with the appropriate type to represent the answer:


In [16]:
# Compute 1/3 and find the type of the result

In [17]:
# Compute the square root of -1 using exponentiation and find the type

The int(), float(), str(), and round() functions

In the same way that Python interprets the numbers 2 and 2. differently, Python also distinguishes between numbers and strings in which the characters happen to be numbers. For example, 2 and '2' may appear identical, but the first is a mathematical object and the other is simply a character string. Trying to add them together demonstrates the point:


In [18]:
# Try to add the integer 2 and the string '2'

The error indicates that it's possible to add an integer to a string and this is partly because the + sign means something very different for numbers and strings. Recall that + concatenates or joins strings so the preceding code block doesn't make any sense.

Sometimes you may wish to convert a number to a string. For example, you may want to export some numerical results to a text file. The str() function converts integers and floats to a string.


In [19]:
# Convert the floating point number 2.71828 to a string and verify the type of the result

The int() function has two uses. First, it will convert a floating point number into an integer by dropping the digits after the decimal. In this way, it works like the mathematical floor function. For example:


In [20]:
# Convert the floating point number 2.71828 to an integer and verify the type of the result

Note the int() function effectively rounds floating point numbers down to the nearest integer and so the round() function is actually a little bit better at moving from floats to integers:


In [21]:
# Round the floating point number 2.71828 to the nearest integer and verify the type of the result

round() is also versatile and allows you to optionally set the precision of the rounding.


In [22]:
# Round the floating point number 2.71828 to the nearest hundreth decimal