Skip to content
Kenny Yu edited this page Nov 4, 2013 · 2 revisions

Introduction

Python is a programming language! It is particularly useful because:

  • Code looks almost like English, and as a result, is very easy to write
  • Has many useful built-in features in the language (e.g. lists, sets, dictionaries)
  • Object-oriented, functional, procedural, you can code in many different programming paradigms
  • Has many useful libraries (for numerical computation, data analysis, plotting, web scraping, launching a web server, etc.)

Setup

Make sure you have python and a version between at least 2.6 or higher, but less than 3.0. To check this:

python --version

Mac OS X users, CS50 Appliance users, and Ubuntu users should already have a compatible version installed. If you do not, please let us know!

Properties of Python

Whitespace matters

Unlike C/Java/C++ which uses { and } to identify blocks of code, Python uses whitespace to identify blocks of code. For example, consider the following C code to sum an array of n integers:

int sum(int *array, int n) {
  int ans = 0;
  for (int i = 0; i < n; i++) {
    ans += array[i];
  }
  return ans;
}

and the equivalent python code:

def sum(arr):
    ans = 0
    for num in arr:
        ans += num
    return ans

You can use either 4 or 2 spaces, but be consistent!

Dynamically Typed

In Python, you don't need to declare types (e.g. int, char, float) like you would in C/Java/C++!

Top Level

Python has an interactive top level! To get to the top level, type python at the command line. Lines beginning with >>> are commands that the user (you) can enter into the command line

top level

You can also use the -i option to drop you into the interactive top level after loading all the definitions from a file. As an example, suppose this was the contents of foo.py:

mylist = ["food", "cheese", "goat"]

And now you ran the command python -i foo.py:

top level interactive

To quit out of the top level, type quit(), or press CTRL + D.

Interpreted, not compiled

Python is interpreted, not compiled. You can just run your program without compiling it. To run a python file:

python file.py

By convention, python files use the .py file extension.

Help

At the top level, you can call help(VARIABLE) on any variable/function/class/method to see the documentation for that variable/function/class/method:

>>> s = ["food", "bar"]
>>> help(s) # this will open up the documentation for the list class
>>> help(s.append) # this will open up the documentation for the append() method on a list

Finish Bootcamp

Main Page