Programming is an important skill. Python will serve you well for years to come. The tables here give you the core words, built-ins, standard library functions, and operators that you'll use most when you're coding with Python.
Python Core Words
Keyword | Summary | Example |
---|---|---|
and | Logical operator to test whether two things are both True. | x>2 and x |
as | Assign a file object to a variable. Used with with. Let your code refer to a module under a different name (also called an alias). Used with import. |
with open(name of file>,file mode>) as object name>: import cPickle as pickle |
break | Stop execution of a loop. | for i in range(10): if i%2 ==0: break |
class | Define a custom object. | class name of class>(object): ""Your docstring"" class MyClass(object): ""A cool function."" |
continue | Skip balance of loop and begin a new iteration. | for i in range(10): if i%2 ==0: continue |
def | Define a function. | def name of function>( ""Your docstring"" def my_function(): ""This does... "" |
elif | Add conditional test to an if clause. | See if. |
else | Add an alternative code block. | See if. |
for | Create a loop which iterates through elements of a list (or other iterable). | for dummy variable name> in sequence>: for i in range(10): |
from | Import specific functions from a module without importing the whole module. | from module name> import name of function or object> from random import randint |
global | Make a variable global in scope. (If a variable is defined in the main section, you can change its value within a function.) | global x |
if | Create a condition. If the condition is True, the associated code block is executed. Otherwise, any elif commands are processed. If there are none, or none are satisfied, execute the else block if there is one. | if
[elif , ...] [else: ] if x == 1: print("x is 1") elif x == 2: print("x is 2") elif x > 3: print("x is greater than 3") else print("x is not greater than 3, nor is it 1 one or 2") |
import | Use code defined in another file without retyping it. | import name of module> import random |
in | Used to test whether a given value is one of the elements of an object. | 1 in range(10) |
is | Used to test whether names reference the same object. | x = None x is None # faster than x == None |
lambda | Shorthand function definition. Usually used where a function needs to be passed as an argument to another function. | lamda times = lambda x, y: x*y command=lambda x: self.draw_line(self.control_points) |
not | Logical negation, used to negate a logical condition. Don't use for testing greater than, less than, or equal. | 10 not in range(10) |
or | Logical operator to test whether at least one of two things is True. | x10 |
pass | Placeholder keyword. Does nothing but stop Python complaining that a code block is empty. | for i in range (10): pass |
Output text to a terminal. | print("Hello World!") | |
return | Return from the execution of a function. If a value is specified, return that value, otherwise return None. | return return x+2 |
while | Execute a code block while the associated condition is True. | while while True: pass |
with | Get Python to manage a resource (like a file) for you. | with open( |
Extend Python's core functionality with these built-ins.
Built-in | Notes | Example |
---|---|---|
False | Value, returned by a logical operation or directly assigned. | ok_to_continue = False age = 16 old_enough = age >=21 (evaluates comparison age>=21 and assigns the result to old_enough) |
None | Value used when representing the absence of a value or to initialise a variable which will be changed later. Returned by functions which do not explicitly return a value. | x = None |
True | Value, returned by a logical operation. | ok_to_continue = True age = 16 old_enough = age >=21 (evaluates comparison age>=21 and assigns the result to old_enough) |
__name__ | Constant, shows module name. If it's not "__main__", the code is being used in an import. | if __name__=="__main__": |
dir | List attributes of an item. | dir(object name>) |
enumerate | Iterate through a sequence and number each item. | enumerate('Hello') |
exit | Exit Python (Command Line) interpreter. | exit() |
float | Convert a number into a decimal, usually so that division works properly. | 1/float(2) |
getattr | Get an attribute of an object by a name. Useful for introspection. | getattr(name of object>, name of attribute>) |
help | Get Python docstring on object. | help(name of object>) help(getattr) |
id | Show the location in the computer's RAM where an object is stored. | id(name of object>) id(help) |
int | Convert a string into an integer number. | int('0') |
len | Get the number of elements in a sequence. | len([0,1]) |
object | A base on which other classes can inherit from. | class CustomObject(object): |
open | Open a file on disk, return a file object. | open( open('mydatafile.txt', 'r') # read (opens a file to read data from) open('mydatafile.txt', 'w') # write (creates a new file to write to, destroys any existing file with the same name) open('mydatafile.txt', 'a') # append (adds to an existing file if any, or creates a new one if none existing already) |
Reimplementation of print keyword, but as a function. Need to import from the future to use it (srsly!) |
from future import print_function print ('Hello World!') |
|
range | Gives numbers between the lower and upper limits specified (including the lower, but excluding the upper limit). A step may be specified. | range(10) range(5,10) range(1,10,2) |
raw_input | Get some text as a string from the user, with an optional prompt. | prompt = 'What is your guess? ' players_guess = raw_input(prompt) |
str | Convert an object (usually a number) into a string (usually for printing). | str(0) |
type | Give the type of the specified object. | type(0) type('0') type([]) type({}) type(()) |
Use the work that others have already done. Try these modules from the Python standard library.
Module | What It Does | Sample Functions/Objects |
---|---|---|
os.path | Functions relating to files and file paths. | os.path.exists( |
pickle, cPickle | Save and load objects to/from a file. | pickle.load( |
random | Various functions relating to random numbers. | random.choice( |
String | Stuff relating to strings. | string.printable |
sys | Various functions related to your computer system. | sys.exit() |
Time | Time-related functions. | time.time() |
Tkinter | User interface widgets and associated constants. | Tkinter.ALL Tkinter.BOTH Tkinter.CENTER Tkinter.END Tkinter.HORIZONTAL Tkinter.LEFT Tkinter.NW Tkinter.RIGHT Tkinter.TOP Tkinter.Y Tkinter.Button( text= Tkinter.Canvas( width= Tkinter.Checkbutton( text= Tkinter.Entry( width= Tkinter.Frame( Tkinter.IntVar() Tkinter.Label( text = Tkinter.mainloop() Tkinter.Menu( Tkinter.OptionMenu( None, None) Tkinter.Scale( from_= to= Tkinter.Scrollbar( Tkinter.StringVar() Tkinter.Tk() |
Add, subtract, divide, multiply, and more using these operators.
Operator | Name | Effect | Examples |
---|---|---|---|
+ | Plus | Add two numbers. Join two strings together. |
Add: >>> 1+1 2 Join: >>> 'a'+'b' 'ab' |
– | Minus | Subtract a number from another. Can't use for strings. |
>>> 1-1 0 |
* | Times | Multiply two numbers. Make copies of a string. |
Multiply: >>> 2*2 4 Copy: >>> 'a'*2 'aa' |
/ | Divide | Divide one number by another. Can't use for strings. |
1/2 # integer division: Answer will be rounded down. 1/2.0 # decimal division 1/float(2) # decimal division |
% | Remainder (Modulo) | Give the remainder when dividing the left number by the right number. Formatting operator for strings. |
>>> 10%3 1 |
** | Power | x**y means raise x to the power of y. Can't use for strings. |
>>> 3**2 9 |
= | Assignment | Assign the value on the right to the variable on the left. | >>> a = 1 |
== | Equality | Is the left side equal to the right side? Is True if so; is False otherwise. | >>> 1 == 1 True >>> 'a' == 'a' True |
!= | Not equal | Is the left side not equal to the right side? Is True if so; is False otherwise. | >>> 1 != 1 False >>> 1 != 2 True >>> 'a' != 'a' True |
> | Greater than | Is the left side greater than the right side? >= means greater than or equal to |
>>> 2 > 1 True |
Less than | Is the left side less than the right side? means less than or equal to |
>>> 1 True |
|
& (or and) | And | Are both left and right True? Typically used for complex conditions where you want to do something if everything is True: while im_hungry and you_have_food: |
>>> True & True True >>> True and False False >>> True & (1 == 2) False |
| (or or) | Or | Is either left or right True? Typically used for complex conditions where you want at least one thing to be True: while im_bored or youre_bored: |
>>> True | False True >>> True or False True >>> False | False False >>> (1 == 1) | False True |