As in C/C++, the = is the assignment operator.
Operation | Interpretation |
---|---|
init_velocity = 14.5 | Basic form. Object 14.5 is created. init_velocity refers to it. |
last, first = 'Schwartz', 'Andrew' | Tuple assignment. |
[part_name, part_no] = "widget", 23654 | List assignment. |
x = y = 0 | Multiple target. Note, that only one object is created! |
and | assert | break | class |
continue | def | del | elif |
else | except | exec | finally |
for | from | global | if |
import | in | is | lambda |
not | or | pass | |
raise | return | try | while |
Statement | Explanation |
---|---|
print "comfy", "chair" | Print items from tuple, space separated, and newline. |
print "penguin", | Final comma suppresses newline. |
print "%d penguins, and %d albatross." % (penguin_ct, albatross_ct) | Formatted output |
Note that the tests in an if statement do not require enclosing parentheses.
Syntax:
if <test1>: | #if test |
<statements> | #Block indentation is significant! |
elif <test2>: | #Optional elif's |
<statements> | #Block is delimited by indentation! |
else: | #Optional else |
<statements> | #Indent with spaces only! |
Syntax:
while <test>: | #loop test |
<statements> | #block for loop body |
else: | #Optional else |
<statements> | #else block is executed only if loop terminates normally. |
Terminates a loop, skipping any else block.
Transfers control to the next iteration of the (innermost) loop body. The loop test is not skipped.
The for loop iterates through a sequence. The sequence may be a string, tuple, list, or any new object you create that responds to the sequence indexing operation.
Syntax:
for <index> in <object>: | #object items are iteratively assigned to index. |
<statements> | #block for loop body |
else: | #Optional else |
<statements> | #else block is executed only if loop terminates normally. |
To make a counting loop, you can use the built-in range( ) function to create a list of the numbers you want to count. The following example prints the integers from zero to nine:
for i in range(10): |
print i, |
The null statement.