Python

From CS 61A Wiki
Jump to: navigation, search
Python is the main programming language for 61A.

Basics

Data types

Every value is an object. The following are the most commonly used Python data types:

Number

A number can be an integer or a float. An integer can be converted to a float using the float() constructor, and a float can be converted to an integer using the int() constructor.

Examples:

>>> 2 # integer
2
>>> 2.0 # float
2.0
>>> int(2.0)
2
>>> float(2)
2.0

Boolean

A boolean has only two possible values: True or False. The type of a boolean is bool. Comparison operators return booleans:

>>> 1 > 2
False
>>> 1 < 2
True
>>> 's' == 's'
True

In a boolean context, all values evaluate to True except the following, which evaluate to False:

None
0
""
[]
()
{}
set()

String

Main article: Sequence#String

Tuple

Main article: Sequence#Tuple

List

Main article: Sequence#List

Dictionary

Main article: Dictionary

Set

Main article: Set

Operators

Main article: Operator

Statements and expressions

Computer programs are generally made up of statements and expressions:

  • Statements carry out actions. A program executes a statement. Examples include the def, import, return, and assignment (=) statements.
  • Expressions compute some value. A program evaluates an expression. Expressions can include anything from primitives (True, 2, 3, 2.0) to lengthy call expressions.

Function call

A function call is executed in the following way:

  • create a new local frame
  • bind arguments to formal parameters in that frame
  • execute the body

Iteration

Main article: Iteration

Iteration is the process of repeatedly executing a block of code.

Command Line

To start a Python interpreter, one can just type python3 into the command line, or the name of the command that leads to the Python 3 program:

python3

To run a Python file, one should include the file path. Any additional arguments provided can be accessed via sys.argv.

python3 path/to/file.py
python3 path/to/file.py arg1 arg2 ...

To run a Python file and then continue execution with an interactive session, add the -i flag.

python3 -i path/to/file.py

Testing

Python has a lot of built-in support for testing. The two testing modules used for this course are doctest and unittest.

  • Doctest - Find docstrings that model interactive sessions and compare the output specified in the docstrings to the actual output from the program.
  • Unittest - Organize test code into units and then run the units together, logging the tests that succeeded and the ones that failed.