addition: <Number> + <Number> = <Number>
multiplication: <Number> * <Number> = <Number>
subtraction: <Number> - <Number> = <Number>
division: <Number> / <Number> = <Number>
A <name> in Python can be any sequence of letters, numbers, and underscores (_) that does not start with a number. We usually use all lowercase letters for variable names, but capitalization must match exactly. Here are some valid examples of names in Python (but most of these would not be good choices to actually use in your programs):
An assignment statement assigns a value to a variable:
After the assignment statement, the variable <name> refers to the value of the <expression> on the right side of the assignment. An <expression> is any Python construct that has a value.
We can put more than one name on the left side of an assignment statement, and a corresponding number of expressions on the right side:
All of the expressions on the right side are evaluated first. Then, each name on the left side is assigned to reference the value of the corresponding expression on the right side. This is handy for swapping variable values. For example,
would swap the values of s and t so after the assignment statement s now refers to the previous value of t, and t refers to the previous value of s.
Note: what is really going on here is a bit different. The multiple values are packed in a tuple (which is similar to the list data type introduced in Unit 3, but an immutable version of a list), and then unpacked into its components when there are multiple names on the left side. This distinction is not important for what we do in CS101, but does become important in some contexts.
A procedure takes inputs and produces outputs. It is an abstraction that provides a way to use the same code to operate on different data by passing in that data as its inputs.
Defining a procedure:
def <Name>(<Parameters>): <Block>
The <Parameters> are the inputs to the procedure. There is one <Name> for each input in order, separated by commas. There can be any number of parameters (including none).
To produce outputs:
return <Expression>, <Expression>, ...
There can be any number of expressions following the return (including none, in which case the output of the procedure is the special value None).
Using a procedure:
<''Procedure''>(<Input>, <Input>, ...)
The number of inputs must match the number of parameters. The value of each input is assigned to the value of each parameter name in order, and then the block is evaluated.
The if statement provides a way to control what code executes based on the result of a test expression.
if <TestExpression>: <Block>
The code in <Block> only executes if the <TestExpression> has a True value.
Alternate clauses. We can use an else clause in an if statement to provide code that will run when the <TestExpression> has a False value.
if <TestExpression>: <BlockTrue> else: <BlockFalse>
The and and or operators behave similarly to logical conjunction (and) and disjunction (or). The important property they have which is different from other operators is that the second operand expression is evaluated only when necessary.
Loops provide a way to evaluate the same block of code an arbitrary number of times.
A while loop provides a way to keep executing a block of code as long as a test expression is True.
while <TestExpression>: <Block>
If the <TestExpression> evaluates to False, the while loop is done and execution continues with the following statement. If the <TestExpression> evaluates to True, the <Block> is executed. Then, the loop repeats, returning to the <TestExpression> and continuing to evaluate the <Block> as long as the <TestExpression> is True.
A for loop provides a way to execute a block once for each element of a collection:
for <Name> in <Collection>: <Block>
The loop goes through each element of the collection, assigning that element to the <Name> and evaluating the <Block>. The collection could be a String, in which case the elements are the characters of a string; a List, in which case the elements are the elements of the list; a Dictionary, in which case the elements are the keys in the dictionary; or many other types in Python that represent collections of objects.
A string is sequence of characters surrounded by quotes. The quotes can be either single or double quotes, but the quotes at both ends of the string must be the same type. Here are some examples of strings in Python:
length: len(<String>) = <Number>
string concatenation: <String> + <String> = <String>
string multiplication: <String> * <Number> = <String>
string indexing: <String>[<Number>] = <String>
string extraction: <String>[<Start Number>:<Stop Number>] = <String>
find: <Search String>.find(<Target String>) = <Number>
To find later occurrences, we can also pass in a number to find:
find after: <Search String>.find(<Target String>, <Start Number>) = <Number>
str: str(<Number>) = <string>
ord: ord(<One-Character String>) = <Number>
chr: chr(<Number>) = <One-Character String>
split: <String>.split() = [<String>, <String>, ... ]
A for loop provides a way to execute a block once for each character in a string (just like looping through the elements of a list):
for <''Name''> in <''String''>: <''Block''>
The loop goes through each character of the string in turn, assigning that element to the <Name> and evaluating the <Block>.
A list is a mutable collection of objects. The elements in a list can be of any type, including other lists.
Constructing a list**. A list is a sequence of zero or more elements, surrounded by square brackets:
Selecting elements: <List>[<Number>] = <Element> **
Selecting sub-sequences: <List>[<Start> : <Stop>] = <List> **
Update: <List>[<Number>] = <Value> **
Length: len(<List>) = <Number> **
Append: <List>.append(<Element>) **
Concatenation: <List~1~> + <List~2~> = <Element> **
Popping: <List>.pop() = <Element> **
Finding: <List>.index(<Value>) = <Number> **
Membership: <Value> in <List> = <Boolean> **
Non-membership: <Value> not in <List> = <Boolean> **
A for loop provides a way to execute a block once for each element of a List:
for <Name> in <List>: <Block>
(We introduced exceptions in Unit 4 because we needed them in our get_page procedure, but you are not expected to understand this in detail or be able to use exception handlers in your own code in cs101.)
try: <''Try Block''> except: <''Handler Block''>
Execute the code in the <Try Block>. If it completes normally, skip the <handler block=""> and continue with the following statement. If code in the <Try Block> raises an error, jump to the code in the <Handler Block>.
The except **can be followed by an exception type and a variable name:
except <Exception Type>, <Name>:
*If the exception raised in the <Try Block> matches the type <Exception Type>, evaluate the <Handler Block> with the variable <Name*> referring to the exception object.