Python Cheat Sheet (Module 3 Version)

Contents:

Input

Use input to get numerical data from the user,

name = input( "Prompt" )

This displays Prompt and then reads a line of input. By default the line is read from the keyboard, and reading is triggered when the Enter key is pressed. input evaluates the line it reads as a Python expression and stores the result as name.

Example:

distance = input( "Enter the distance in miles: " )

Notes:

Processing using =

Processing is specified in Python using assignment statements with the form,

name = expression

The value of expression is evaluated and stored in memory as name.

Notes:

Arithmetic Expressions

Arithmetic processing is expressed using standard mathematical notation within the limitations imposed by a keyboard, e.g.

3*(x + y)**4

Arithmetic Operators:

+ addition
- subtraction
/ division
% modulo (remainder), e.g. 19 % 4 → 3
* multiplication
** exponentiation, e.g. 2 ** 4 → 16

In addition the abs() function for absolute value is built-in, and less common mathematical functions can be accessed by importing the math library, e.g.

import math
print "The value of pi is", math.pi
print "The square root of pi is", math.sqrt(math.pi)

Output using print

Use print to display stored values:

print list

displays the value of each item in the list. Puts a space between each pair of values. Example:

print "The answer is", 5 + 2, "."

displays:

The answer is 7 .

Appending a comma to the end of a print statement holds the current output line open, e.g. the code,

print "The answer is",
print 5 + 2, "."

displays

The answer is 7 .

on a single line.

For more control over output appearance embed formatting codes into output strings. See section 2.2.6.2 String Formatting Operations of the Python Library Reference for the gory details.

Selection using if

Use if to execute one block of code or another, but not both.

if test:
    statement 
elif test:
    statement 
else:
    statement

N.B. the elif and else statements are optional as shown in the first two examples below.

Examples:

if x < 0:
    print x, "is negative"
if flip == 1:
    print "You got heads"
else:
    print "You got tails"
if num < 0:
    print "The number", num, "is negative."
elif num == 0:
    print "The number", num, "is neither positive nor negative."
else:
    print "The number", num, "is positive."

Relational Expressions

Look like standard arithmetic comparisons (but again within the limitations imposed by using a standard keyboard), e.g.

x <= 4

Relational Operators:

< less than, e.g 5 < 3 → False
<= less than or equal to, e.g. 3 <= 5 → True
== equal, e.g. 5 == 5 → True
!= not equal, e.g. 5 != 5 → False
>= greater than or equal to, e.g. 5 >= 3 → True
> greater than, e.g. 4 > 5 → False

Logical or Boolean Expressions

and a and b is only True when a is True and b is True
or a or b is True when a is True, or when b is True, or when both a and b are True
not not a is True when a is False