Python Tutorial

by Max Timkovich
Updated: 2017-9-19

for Paul, Nick, and Nathan: so you guys can have some marketable skills.

Introduction

Python is a pretty cool programming language. It's easy to read and write and runs on a bunch of different operating systems. Despite being relatively easy to learn, it's not a toy; it's used on websites like YouTube, reddit, and Dropbox.

This tutorial isn't exhaustive, but should be a good starting point, and for learning what Python is about.

Downloading Python

This tutorial will be for Python 3. Python 3 has a lot of nice performance improvements from Python 2 as well as better Unicode handling.

You can download Python 3 here.

Getting started

Open Python. On Windows, it'll be called IDLE. It'll give you this:

repl

This is a REPL (read-eval-print loop). Anything you type will be run and printed to the screen. This is really useful for playing around with Python and trying out new concepts. You should try out most of the things in the tutorial in the REPL.

Here's some stuff to try out to get a feel for Python. Hit enter after each command to have it run.

# Printing stuff to the screen
>>> print 'hello, world'

# Advanced mathematics
>>> 1 + 2

# Assigning integers to variables
>>> a = 6
>>> b = 7
>>> a * b

Alternatively, you can save your code in a .py file and run it through IDLE or the command line that way.

Basic data types

Data types are the way data from your program is stored on the computer. The most basic ones are integers, floats, booleans, and strings.

Python is dynamically typed, which means you don't have to tell it the type of the variable before you assign it values. For instance, the following is valid, though a bit confusing.

a = 6
a = 7.3
a = 'lol'
a = True

You can convert between different basic data types using the int(), float(), and bool() functions.

>>> float(3)
3.0
>>> int(3.14)
3
>>> bool(1)
True

Getting Serious

All you need to know to program in any language is the following:

Assigning variables

a = 3
foo = 'spooky boogie'
e = 2.718

if statements

if statement1:
    # run if statement1 is true
elif statement2:
    # run if statement2 is true (but not statement1)
else:
    # run if statement 1 and 2 are false

while/for statements

while statement:
    # Loop until statement is false

for variable in iterable:
    # loop over iterable variable and assign individual elements to variable

# e.g.
for i in range(6):
    print(i, end=' ')

# Output: 1, 2, 3, 4, 5

Printing

# Display variable's value
print(value)

# Advanced printing
print('Hello, {}!'.format('World'))

# Output: 'Hello, World!'

Everything else is just a bonus.

But we'll cover it anyway.

Conditionals

The majority of the heavy lifting in any program happens in the conditional statements: loops and if statements.
The format for them is looks like:

if statement:
    # Do stuff

while statement:
    # Do stuff until statement is false

A statement is anything that evaluates to either True or False. In Python, empty strings (''), 0, empty lists ([]), and None evaluate
to False. Everything else is True.

You can combine statements together with and and or, which works exactly like you'd expect.

>>> 1 == 2 or 8*3 == 24
True
>>> True and False
False

for loops are the last conditional statement, but those will be covered in the next section, as their utility makes the most amount of sense when paired with lists.

Control Statements

There are a couple of special statements for interacting with loops.

break exits out of a loop unconditionally.

continue will skip the rest of the code in the loop and proceed to the next iteration of the loop.

Advanced Data Types

Most of the time, you won't be working with one variable, you'll be working with a lot of them. Lists, dictionaries, and sets help organize, access, and manipulate multiple variables.

Lists

Lists are sequential arrays of data. They're declared using square brackets [ ]

>>> days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
>>> nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Individual elements in a list can be accessed using [n]. Lists start indexing from 0. Items can be accessed from the end of the list using negative numbers.

>>> days[0]
'Monday'
>>> days[-2]
'Saturday'
>>> days[1] = ''

You can get what's called a splice of the list by providing two numbers. If only a colon is provided, the splice will go all the way to the beginning or end of the list.

>>> days[2:4]
['Wednesday', 'Thursday', 'Friday']
>>> days[:-2]
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
>>> days[:]
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

Lastly, you can provide a third number to the splice to set the "step" or how much to increment over the list. A negative number can be given to step number.

>>> nums[::2]
[0, 2, 4, 6, 8]
>>> nums[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]

Strings in Python are (for the most part) lists of characters, so any of the operations you can do on a list (with the notable exception of assigning individual characters) can be done on a string.

Making a list of numbers like nums is something that's done very frequently in Python, so that list can also be generated using the range() function.

>>> range(9)
[0, 1, 2, 3, 4, 5, 6, 7, 8]

range has 2 optional arguments, its full declaration is range(start, end, step). start is what value to start the range at and defaults to 0. end is the maximum number (exclusive). step defaults to 1, and signifies how many values to skip while going through the range. i.e. a value of 2 would make the range skip every other value. step can be negative to walk from a start to end where start is larger than end.

There are some ways to modify your list, and I'll list (hahahahahahahahahahaha) some of the more commonly used ones below.

For everything else you can do on a list, check out the documentation.

Tuples

One thing that is related closely to lists that you may encounter when programming in Python are tuples. Tuples are deliminated with ( ).

>>> t = (255, 0, 88)
>>> t[0]
255

Tuples are similar to lists in that they hold multiple elements and can be indexed using []. They differ in the fact that tuples are immutable, that is that tuples cannot be modified after they are created. Attempting to change a tuple's value or use append on it will fail with an exception.

For loops

for loops and lists compliment each other very well.

for loops work like this:

>>> for i in lst
...     # do stuff

They iterate over every element of the list lst and assign its value to the variable i.

Sorting

To sort a list, use the sorted function.

>>> l = range(5)[::-1]
[4, 3, 2, 1, 0]
>>> sorted(l)
[0, 1, 2, 3, 4]

List Comprehensions

List comprehensions allow you to quickly operate on a list. Their style looks like this:

[i*2 for i in range(0, 3)] # [0, 2, 4]
[i for i in range(0, 10) if i % 2 == 0]
# Return a list of only the even numbers: [0, 2, 4, 6, 8]

Dictionaries

Dictionaries (aka hash table, hash map) map from a unique key to a value. They are notable because looking up a value in a dictionary by its key is very fast: O(1).

Dictionaries are declared using {}

>>> d = {}
>>> d = {
            'app': 'python',
            'version': 2.7
        }
>>> d['app']
'python'

Dictionaries are crazy useful. I'll try to show some of their power by showing a small program below to get a count of the frequency of letters of a string.

letters = {}
strng = "Dictionaries are crazy useful. I'll try to show some of their power by showing a small program below to get a count of the frequency of letters of a string."
for s in strng:
    if s not in letters:
        letters[s] = 0
    letters[s] += 1

Output:

{' ': 29, "'": 1, '.': 2, 'D': 1, 'I': 1, 'a': 8, 'c': 4, 'b': 2, 'e': 13, 'g': 4, 'f': 6, 'i': 7, 'h': 3, 'm': 3, 'l': 7, 'o': 13, 'n': 5, 'q': 1, 'p': 2, 's': 7, 'r': 12, 'u': 4, 't': 12, 'w': 4, 'y': 4, 'z': 1}

One thing to note is that the order of the keys in a dictionary are arbitrary, so don't depend on them being in any particular order.

Sets

Sets are just like their mathematical equivalents, they hold a collection of values with no duplicates. Internally, they are equivalent to dictionaries, but their key doesn't map to any value.

Sets are declared like this:

>>> set([1, 1, 2, 3, 5])
set([1, 2, 3, 5])

Check out the documentation on sets for more stuff you can do with set objects, like set difference or checking if one set is a subset of another.

Functions

If you ever find yourself repeating the same block of code, it's a code idea to stick that in a function. Functions take 0 or more parameters as an argument, and can return a value.

Functions are declared like so:

def square(x):
    return x * x

square(19) # 361

Files

Sometimes in life, you'll want to have your Python program open a file.

with open('file_name.file') as f:
    for line in f:
        # do stuff

    # To read the entire file into a variable
    # This will be very memory inefficient for large files, so avoid doing this when possible.
    text = f.read()

The above code will open the file as read-only. There are other flags you can pass to the open function to open files with different settings. open(f, 'w') will open f as writable and open(f, 'a') will open f appendable, and all changes will be added to the end of the file.

Objects

Objects are a special data type that can store multiple variables as well as functions.

class Player:
    def __init__(self, name):
        self.name = name
        self.score = 0

    def win(self):
        self.score += 1

one = Player('One')
one.win()
print(one.score) # 1

This creates a class called Player, that takes one argument when it's created: name. There's a built-in Python function that gets called when the object is created called __init__. Note that every function inside a class has the first argument of self which refers to the object using the function.

Libraries

In general, if you ever think about writing something big and complex, someone else has already written it for you. You can use other people's libraries by installing it using the Python package manager pip, and then adding:

import library

at the top of your program.

Now, you can use the functions and objects in library by prefixing them with library: e.g. library.function().

There's two other ways to import libraries into your program.

import library as lb

Same as normally importing a library, but you can give it a different name if, for instance, the default library name is long and you're using it a lot

from library import func1, func2

Imports only func1 and func2 from library. You no longer have to prefix those functions with the library name to use them.

from library import *

Imports all objects and functions from library into the current program. Use this sparingly, as it can clutter your project's namespace in confusing ways.

Common Libraries

Below are some of my most commonly used packages, as well as what I use them for.

OS Library

This section is to get you acquainted with libraries, mainly calling their functions and finding what you need from the documentation. We're going to be using the os library because it is one of the most common libraries.

The os library wraps various OS functions, such as opening files, changing the current directory, and renaming and deleting files. Before doing any programming, open the documentation and briefly scroll through all of the features that the os library has.

Using the os library is as easy as adding

import os

to the top of your program.

I'll list out some of the most common os system calls below.

>>> os.getcwd() # return what directory the program is being run in
>>> os.mkdir('Python') # make a directory named 'Python'
>>> os.remove('important.txt') # delete the given file
>>> os.listdir('/etc') # return a list of all the files in the given directory
>>> os.rename('old', 'new') # rename (or move) file from 'old' to 'new'

Obviously there's a lot more that the os library can do, and all of it is listed in its documentation.

NumPy/Scipy Library

The NumPy and SciPy libraries for Python that provides functions and data models to help Python function like Matlab.

NumPy for Matlab users is a great resource for learning how to use NumPy. If you know Matlab, you can look up the corresponding NumPy function, and, if you don't, it's great for looking up the common things you'd want to do with NumPy.