Show Menu
Cheatography

Python 3 - the basics Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

NUMBERS

max()
returns largest argument of list
min()
returns smallest argument of list
abs()
returns absolute value of argument
type()
return data type of argument

STRINGS

Create Strings
'string'
creates string
"­str­ing­"
creates string
String Methods
print( )
("he­llo­"), (variable)
g = "Golf"
h = "Hotel"
print("%s, %s" % (g, h))
print("My name is {0}".fo­rma­t('­Fred'))
str(3)
returns "­3", not #3
len("st­rin­g")
returns 5
"­str­ing­".up­per()
returns 'STRING'
"­STR­ING­".lo­wer()
returns 'string'
word[0]
returns "­w"
word[1­:le­n(w­ord)]
returns "­ord­"

LOOPING

For loops  ­ ­ ­ ­ ­ 
for variable in sequence :
for x in range(1, 10):
    print(x)

The variable will iterate through each item in the sequence.
If ­ ­ ­ ­ ­ 
if condition :
if x == 7:
    print(x)

The following lines are only executed if the condition is true. The condition can be either a single compar­ison, eg. 5 > 3, or multiple compar­isons using Boolean operators to evaluate ultimate True or False eg. 1<2 and 2<3 (returns True, so the following lines are evaluated)
elif ­ ­ ­ ­ ­ 
elif condition :
provides second if test, when first if test is false:
elif x == 5:
    print(x)
else (runs if the if/elif test is false)
else:
    print(y)
while ­ ­ ­ ­ ­ 
while condition :
Remains in the loop while the condition is true. Use the "­bre­ak" command to leave the loop. This is useful if waiting on an input from microc­ont­roller. Once the microc­ont­roller input is received, the break command kicks out of the loop and continues with the program.
 

FUNCTION STRUCTURE

def shut_down(s):
    if s == "yes":
        return "shutting down"
    elif s == "no":
        return "Shutdown aborted"
    else:
        return "Sorry"
--------------------------------
def is_numeric(num):
    return type(num) == int or
           type(num) == float:
--------------------------------
def finish_game(score):
    tickets = 10 * score
    if score >= 10:
        tickets += 50
    elif score >= 7:
        tickets += 20
    return tickets

IMPORTING MODULES & FUNCTIONS

import math
makes math module available
usage:  ­mat­h.s­qrt()
from math import *
imports all math functions into program
usage:  ­sqrt()
from math import sqrt
imports only the math function specified
usage:  ­sqrt()

READING & WRITING FILES

input = open(file)
variable to hold file
indata = input.r­ead()
reads the file
output = open(t­o_file, 'w')
open file to write to, 'w' makes file writable
output.wr­ite­(in­data)
writes data to
to_file
output.cl­ose()
finish by closing
to_file
input.c­lose()
finish by closing
file
example: exercise 17 in the book Python The Hard Way (page 43).
 

LISTS

list_name = [item_1, item_2]
Items can be 'strings', variables, integers, etc.
List Index
use the index to access specific locations
usage: ­ 
list_n­ame[0] #first entry
Add to Lists: ­ .append
use .append to add a new entry to the end of the List; note the use of ( )
list_n­ame.ap­pen­d('­str­ing')

adds 'string' to end of the list contents
Add to Lists: ­ assignment
replace an item in a List:
list_n­ame[4] = 'string'

replaces 5th item in list with 'string'
Adding Lists together
list_A = [1,2,3]
list_B = [4,5]
list_C = list_A + list_B
print(list_C)    #returns [1,2,3­,4,5]
len(list_name)
returns the number of items in the list
print (list_name)
returns
[item_1, item_2, etc.]
List Slicing
letters = ['a', 'b', 'c', 'd']
slice = letters[1:3]
print slice #returns ['b', 'c']

[1:3]
means this will return entries starting at index 1 and continue up to, but not including the third index position
List Slicing with Strings
strings are considered to be natural lists, with each letter being an item of the list
animal = 'blueWhale'
print = (anima­l[4­:])­ ­ ­ ­ ­#re­turns Whale
print = (anima­l[:­4])­ ­ ­#re­turns blue
List Manipu­lation ­ ­ .index
letters = ['a', 'b', 'c']
print(letters.index('b'))    #prints 1
List Manipu­lation ­ ­ .sort
numbers = [5, 3, 7]
print(numbers.sort())    #prints [3,5,7]
List Manipu­lation ­ ­ .pop
numbers = [5, 3, 7]
print(numbers.pop())  #no index pops last item
  #prints 7, and removes it from the list

print(­num­ber­s.p­op(­1))­ ­ ­#pops second item
  #prints 3, and removes it from the list
List Manipu­lation ­ ­ .insert
numbers = [5, 3, 7]
print(numbers.insert(1,9))   #prints [5,9,3,7]

inserts the number 9 "­bef­ore­" position 1 in the list

Dictio­naries

ph_numbers = {'Jack­':x123, 'Mark'­:x655}

ph_num­ber­s['­Mark']
 ­ ­ 
#retur­ns x655

ph_num­ber­s['­Mark'] = x899  #a­ssigns new number

ph_numbers
 ­ ­ 
#retur­ns {­'Ja­ck'­:x123, 'Mark'­=x899}
A dictionary is comprised of both a "­key­" and a "­val­ue". You access or reassign a particular value by using the key, NOT the position. The dictionary does not maintain a specific order to any of its entries.