Python Tutorial
Python Tutorial
Python Tutorial
&
Cheat Sheet
Getting Started
What you need:
Linux based machine with Python 2.7 or higher (comes default on most linux systems)
(Python on windows also works though not ideal)
Editor on Linux such as VI or EMACS to edit your files
Python interpreter: operates similar to a unix shell: reads and executes commands
interactively
Setting your path variable to include the location of the Python interpreter: (usually
/usr/local/bin/python
Replace: Count:
>>>r='rule‘ >>>numbers=['1','2','1','2','2']
>>>r.replace('r','m') >>>numbers.count('2')
'mule‘ 3
Booleans
Boolean values are simply True or False .
Value is equal to another value with two equal signs: To check for inequality use:
>>> 10 == 10 >>> 10 != 10
True False
>>> 10 == 11 >>> 10 != 11
False True
To access the elements in the list you can use the placement in the list as an
indicator. This means numbering the items aligned with their placement in the list.
The list starts with 0
‘o>>> fruits[2]
range’
Len, Append and Pop
Use len to find number of elements in the list. Use append to add a new object to the end of the list and pop to
remove objects
from the end.
>>> fruits.append('blueberry')
>>> fruits
['apple', 'lemon', 'orange', 'grape', 'blueberry']
>>> fruits.append('tomato')
>>> fruits
['apple', 'lemon', 'orange', 'grape', 'blueberry', 'tomato']
>>> fruits.pop()
'tomato'
>>> fruits
['apple', 'lemon', 'orange', 'grape', 'blueberry']
Dictionaries
A dictionary optimizes element lookups. It uses keys and values, instead of numbers as placeholders. Each key
must have a value. You can used a word to look up a value.
>>> words={'apple':'red','lemon':'yellow'}
>>> words
{'lemon': 'yellow', 'apple': 'red'}
>>> words['apple']
'red'
>>> words['lemon']
'yellow‘
Output all the keys as a list with keys() and all the values with values()
>>> words.keys()
['lemon', 'apple']
>>> words.values()
['yellow', 'red']
3. Control Statements
IF Statements
The IF statement is used to check if a condition is true. Essentially, if the condition is true, the Python
interpreter runs a block of statements called the if-block. If the statement is false, the interpreter skips the
if block and processes another block of statements called the else-block. The else clause is optional.
>>> num = 20
>>> if num == 20:
... print 'the number is 20'
... else:
... print 'the number is not 20'
...
the number is 20
>>> num = 21
>>> if num == 20:
... print 'the number is 20'
... else:
... print 'the number is not 20'
the number is not 20
Loops
There are 2 kinds of loops used in Python. The For loop and the While loop. For loops are traditionally used when you have a piece of
code which you want to repeat n number of times. They are also commonly used to loop or iterate over lists. While loops, like the For Loop, are used for
repeating sections of code - but unlike a for loop, the while loop will not run n times, but until a defined condition is met.
For Loop:
>>> colors =('red','blue','green') While loop:
>>> colors
('red', 'blue', 'green') >>> num = 1
>>> for favorite in colors: >>> num
File Output
Open a file using 'w' to write to a file:
fout = open("bar.txt", "w")
fout.write("hello world")
fout.close()
Python Cheat Sheet
Common Built in Functions
Function Returns
abs(x) Absolute value of x
dict() Empty dictionary, eg: d = dict()
float(x) int or string x as float
id(obj) memory addr of obj
int (x) float or string x as int
len(s) Number of items in sequence s
list() Empty list, eg: m = list()
max(s) Maximum value of items in s
min(s) Minimum value of items in s
open(f) Open filename f for input
ord(c) ASCII code of c
pow(x,y) x ** y
range(x) A list of x ints 0 to x -‐ 1
round(x,n) float x rounded to n places
str(obj) str representation of obj
sum(s) Sum of numeric sequence s
tuple(items) tuple of items
type(obj) Data type of obj
Common Syntax Structures
Assignment Statement Function Definition
var = exp def function_name( parmameters ):
Console Input/Output stmt ...]
var = input( [prompt] ) Function Call
var = raw_input( [prompt] ) function_name( arguments )
print exp[,] … Class Definition
Selection class Class_name [ (super_class) ]:
if (boolean_exp): [ class variables ]
stmt ...] def method_name( self, parameters ):
[elif (boolean_exp): stmt
stmt ...]… Object Instantiation
[else: obj_ref = Class_name( arguments )
stmt ...] Method Invocation
Repetition obj_ref.method_name( arguments )
while (boolean_exp): Exception Handling
stmt ...] try:
Traversal stmt ...]
for var in traversable_object: except [exception_type] [, var]:
stmt ...] stmt ...]
Common File Methods
F.method() Result/Returns
read([n]) Return str of next n chars from F, or up to EOF if n not given
Module Import
import module_name
from module_name import name , ….
from module_name import *