Python fundamentals, part 2

Importing modules, indentation, if statements, for loops.

Importing modules

You can import modules into your script -- snippets of Python code that give you access to additional functionality or variables -- from:

  • the Python standard library, which is part of the Python installation package
  • from your own Python files
  • and from third-party developers using a tool called pip.

A collection of modules is usually referred to as a "package" or "library."

For this class, we've pre-installed five external libraries: jupyter, bs4, requests, matplotlib and geopy.


In [ ]:
# import the csv module from the Python standard library
# https://docs.python.org/3/library/csv.html


# import the BeautifulSoup class from the (external) bs4 package


# import variables from a local file, my_module.py
# alias to `mm` using the `as` keyword


# access bits of the module with a period .

Indentation

Whitespace matters in Python. Sometimes you'll need to indent bits of code to make things work. This can be confusing! (FWIW, Jupyter will try to be helpful and insert the correct amount of "significant whitespace" for you.) You can use tabs or spaces, just don't mix them. The Python style guide recommends indenting your code in groups of four spaces, so that's what we'll use today.

if statements

Just like in Excel, you can use the "if" keyword to handle conditional logic.

These statements begin with the key word if (lowercase), then the condition to evaluate, then a colon, then a new line with a block of indented code to execute if the condition resolves to True.


In [ ]:

You can also add an else statement (and a colon) with an indented block of code you want to run if the condition resolves to False.


In [ ]:

If you need to, you can add multiple conditions with elif.


In [ ]:

for loops

Use a for loop to iterate over a collection of things. The statement begins with the keyword for (lowercase) variable_name in collection_to_iterate, then a colon, then the indented block of code with instructions about what to do with each item in the collection.


In [ ]:
# let's import a list of ingredients for pico de gallo


# print the list to see what's there


# now use a `for` loop to iterate over the list and print each item
# ("ingredient" is an arbitrary variable name)

In [ ]:
# you can also iterate over a dictionary

# let's import our puppy


# the iterable element in a dictionary is the key
# so I like to use that as my variable
# --> remember! order is not guaranteed in a dict

In [ ]:
# lots of things are iterable -- you can even loop over the characters in a string!