Python Statements


Assignment

As in C/C++, the = is the assignment operator.

Three forms of the assignment statement:

OperationInterpretation
init_velocity = 14.5Basic form. Object 14.5 is created. init_velocity refers to it.
last, first = 'Schwartz', 'Andrew'Tuple assignment.
[part_name, part_no] = "widget", 23654List assignment.
x = y = 0Multiple target. Note, that only one object is created!

Variable Names

Python Reserved Words

andassertbreakclass
continuedefdelelif
elseexceptexecfinally
forfromglobalif
importinislambda
notorpassprint
raisereturntrywhile

Statements

General Rules for Statements:


print

StatementExplanation
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

if

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!

while

Syntax:

while <test>:    #loop test
   <statements>    #block for loop body
else:    #Optional else
   <statements>    #else block is executed only if loop terminates normally.

Auxiliary Loop Statements

break

Terminates a loop, skipping any else block.

continue

Transfers control to the next iteration of the (innermost) loop body. The loop test is not skipped.


for

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,


pass

The null statement.


Next: Basic Python Programs

Go back to First Python Page.