CS 4440 Wiki:
Python 3 Cheat Sheet


Below is an abridged cheat sheet of Python 3 fundamentals that you'll use in this course.

This page is by no means comprehensive—we encourage you to bookmark and familiarize yourself with one of the many in-depth Python tutorials on the web. Some great examples are:


Running Python Code

Interactive mode:

In some course exercises, we'll walk you through examples demonstrated in Python's interactive mode. Think of interactive mode as a Python "session", where you write programs line-by-line (rather than all at once) and get feedback as each line is processed and executed.

To launch interactive mode, run python3 in your terminal. An example session is below:

$ python3
>>> print("Hello from the interpreter!")
Hello f​rom the interpreter!
>>> exit()

Writing and running scripts:

The most common way that you'll be using Python is writing and running your own programs (or more technically, "scripts"). After editing your Python program (any IDE or text editor will work), save it as a .py file. Then, run it by calling $ python3 /path/to/your/script.py. An example is below:

$ echo 'print("Hello from a script!")' > example.py
$ python3 example.py
Hello f​rom a script!

Debugging your code:

Occasionally your code might not function as expected. Thankfully, Python provides descriptive error messages to help you narrow down where your code is incorrect. For example:

>>> print(os.path)
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'os' is not defined

Here, we see error NameError: name 'os' is not defined. We can pinpoint that our mistake is a failure to define module os. A quick Google search turns up that this is indeed a core Python library, and that the fix is probably to just prepend the line import os at the beginning of our code.

To be successful in this course, you'll need to get comfortable with debugging. Often, the right fix will take you just a few minutes to find via research on Google, some trial-and-error fixing, adding a few print() statements, etc. Before you reach out to the course staff or ask on Piazza, we expect that you've spent some time trying to debug your own code first. To help others best help you, be sure to describe in detail what you've tried, what you think might be wrong, what solutions didn't work, etc.

Debugging is a skill you'll use all throughout your software development career—get comfortable with it!


Modules and Libraries

In many course exercises, you'll borrow functionality from third-party modules (files ending in .py) or libraries (collections of modules). These modules may contain useful variables (e.g., os.name) or functions (e.g., os.uname()). We'll cover the three main ways to import and use such objects below.


Note that in all of CS 4440, you may only use default Python libraries (the ones that come pre-installed in your Linux VM) and/or modules that we provide you. We won't install any others when grading your work, which means your code will fail—and you'll lose points—if you rely on any external dependencies.

Importing a module:

>>> import os               # Import the `os` module.
>>> print(os.name)          # To access objects, we use prefix "os.OBJNAME".
posix

>>> print(os.uname())       # This applies to all objects. E.g., `uname()`. 
posix.uname_result(sysname='Linux', ...)

Importing one module object:

>>> from os import name     # Import variable `name` from the `os` module.
>>> print(name)             # We no longer need a prefix to access `name`!
posix

>>> print(uname())          # This fails. Why? We've only imported `name`! 
NameError: name 'uname' is not defined. Did you mean: 'name'?

>>> print(os.uname())       # Also fails. Why? We didn't import the module!
NameError: name 'os' is not defined

Importing all module objects:

>>> from os import *        # The '*' imports every object from the module.
>>> print(name)             # As before, we no longer need to prefix objects!
posix

>>> print(uname())          # We can now access all objects from the module!
posix.uname_result(sysname='Linux', ...)

Variables

Initializing:

>>> x = 5           # We've declared variable `x` with value 5.
>>> print(type(x))  # Python correctly infers it is an integer!
<​c​lass 'int'>

>>> x = "cs4440"    # Let's now overwrite `x` with a string. 
>>> print(type(x))  # Notice how its type changes accordingly!
<​c​lass 'str'>

Casting:

>>> x = int(5)      # Let's cast `x` as an `int` (integer).
>>> print(x)        # Now print it — it's indeed an integer!
5
    
>>> x = float(5)    # Now cast it as a `float` type!
>>> print(x)        # Here we go — it is indeed a float!
5.0

String Manipulation

Length of a string:

>>> x = "cs4440"            # Use `len()` to get a string's length.
>>> print(len(x))
6

Appending to a string:

>>> x = "cs4440"            # Append ' is cool' to string 'cs4440'.
>>> x += " is cool"
>>> print(x)
cs4440 i​s cool

Substrings:

>>> x = "cs4440 is cool"    # Check if substring 'cool' is present.
>>> print("cool" in x)
T​rue

>>> print("4440" not in x)  # Check if substring '4440' not present.
F​alse

Splitting by a delimiter:

>>> x = "cs4440:cool"       # Use delimiter ':' to split into a list.
>>> print(x.split(':'))
['cs4440', 'cool']

Stripping characters:

>>> x = "  cs4440   "       # Strip any leading / trailing whitespace.
>>> print(x.strip())
cs4440

>>> x = "cs4440"            # Strip the substring '4440' from our string.
>>> print(x.strip('4440'))
cs

Repeating characters:

>>> x = "A"*10            # You can use multiplication to quickly  
>>> print(x)              # generate strings of repeated characters.
AAAAAAAAAA

Byte strings:

>>> x = b'cs4440'               # Python byte strings are wrapped by `b''`.
>>> print(x.decode('utf-8'))    # Use `decode()` to convert them to strings.
cs4440

>>> x = "cs4440"                # To convert a string to a byte string, you
>>> print(x.encode('utf-8'))    # can similarly use the `encode()` function.
b'cs4440'

List Manipulation

Indexing:

>>> x = ['cs4440', 'is', 'cool']    # Print the 0th item of our list.
>>> print(x[0])
cs4440

>>> x = ['cs4440', 'is', 'cool']    # Print the last item of our list.
>>> print(x[-1])
cool

Inserting:

>>> x = ['cs4440', 'is', 'cool']    # Overwrite the last item with 'fun'.
>>> x[-1] = 'fun'
>>> print(x)
['cs4440', 'is', 'fun']

>>> x.insert(2, 'super')            # Insert string 'super' in index two.
>>> print(x)
['cs4440', 'is', 'super', 'fun']

Joining:

>>> x = ['cs4440', 'is', 'cool']    # Join items into a space-delimited string. 
>>> print(' '.join(x))
cs4440 i​s cool

>>> y = ['all', 'day']              # Joins list y to our previous list x.
>>> print(x + y)
['cs4440', 'is', 'super', 'cool', 'all', 'day']

Conditional Statements

If statements:

>>> x = 5
>>> if (5 % 2 == 1):    # Evaluates to True if x modulo 2 equals 1.
...     print("Yes!")   # Prints string "Yes!" if condition is True.
Yes!

Else statements:

>>> x = 5
>>> if (x % 3 == 1):    # Evaluates to True if x modulo 3 equals 1.
...     print("Yes!")
... else:               # Prints "Nope!" if the condition is False. 
...     print("Nope!")  
Nope!

Loops

For loops:

>>> x = ['a', 'b', 'c']    # For every item `y` in list `x`...
>>> for y in x:
...     print(y)
a
b
c

While loops:

>>> x = 3
>>> while x != 0:          # While x is not equal to 0...
...   print(x)             # Print x and then decrement it.
...   x -= 1
3
2
1

Functions

Defining functions:

>>> def foo():             # Definition of function `foo()`.
...      print("Hello!")
...      return

>>> def bar(x, y):         # Definition of function `bar()`,
...      print(x+y)        # which expects two arguments.
...      return

Calling functions:

>>> foo()                  # Call foo(), which has no arguments.
Hello!

>>> bar(4000,440)          # Call bar(), which has two arguments.
4440