Python Cheat Sheet (Module 2 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. 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 and 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 you can embed formatting codes into output strings. See section 2.2.6.2 String Formatting Operations of the Python Library Reference for the gory details.