Cheat Sheet

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Python for Beginners – Cheat Sheet

Data types and Collections Numerical Operators Comparison Operators List Methods

integer 10 + addition < less l.append(x) append x to end of list


float 3.14 - subtraction <= less or equal l.insert(I, x) insert x at position i
boolean True/False * multiplication > greater l.remove(x) remove first occurrence of x
string ‘abcde’ / division >= greater or equal l.reverse() reverse list in place
list [1, 2, 3, 4, 5] ** exponent == equal
tuple (1, 2, ‘a’, ‘b’) % modulus != not equal Dictionary Methods
set {‘a’, ’b’, ’c’} // floor division
Logical Operators d.keys() returns a list of keys
dictionary {‘a’:1, ‘b’:2}
d.values() returns a list of values
Operations Index starts at 0 and logical AND
d.items() returns a list of (key, value)
or logical OR
Strings:
not logical NOT
s[i] i:th item of s String Methods
s[-1] last item of s
Membership Operators
s.strip() remove trailing whitespace
in value in object s.split(x) return list, delimiter x
Lists:
not in value not in object s.join(l) return string, delimiter s
l = [] define empty list
s.startswith(x) return True if s starts with x
l[i:j] slice in range i to j
Conditional Statements s.endswith(x) return True if s ends with x
l[i] = x replace i with x
s.upper() return copy, uppercase only
l[i:j:k] slice range i to j, step k if condition:
<code> s.lower() return copy, lowercase only

Dictionaries: elif condition:


<code>
d = {} create empty dictionary Import from Module
d[i] retrieve item with key i else:
<code> from module import func import func
d[i] = x store x to key I
from module import func as f import func as f
i in d is key i in dictionary
Python for Beginners – Cheat Sheet

Built-in Functions String Formatting Reading and Writing Files

float(x) convert x to float “Put {}into a {}”.format(“values”, “string”) fh = open(<path>,’r’)


int(x) convert x to integer ‘Put values into a string’ for line in fh:
str(x) convert x to string “Put whitespace after: {:<10}, or before:{:>10}”.format(“ a”,”b”) <code>
set(x) convert x to set ‘Put whitespace after: a , or before: b’ fh.close()
type(x) returns type of x “Put whitespace around:{:^10}.”.format(“c”)
len(x) returns length of x ‘Put whitespace around: c . out = open(<path>,’w’)
max(x) returns maximum of x out.write(<str>)
min(x) returns minimum of x out.close()
Regular Expressions
sum(x) returns sum of values in x
import re
sorted(x) returns sorted list Functions
p = re.compile(pattern) compile search query
round(x, d) returns x rounded to d
p.search(text) search for all matches def Name(param1, param2 = val):
print(x) print object x
p.sub(sub, text) substitute match with sub <code>
#param2 optional, default: val
Loops
. any one character return <data>
while condition: * repeat previous 0 or more times
<code> + repeat previous 1 or more times sys.argv

for var in list: ? repeat previous 0 or 1 times


import sys import module
<code> \d any digit
sys.argv[0] name of script
\s any whitespace
sys.argv[1] first cmd line arg
Control statements: [abc] any character in this set {a, b, c}
break terminate loop [^abc] any character *not* in this set
continue jump to next iteration [a-z] any letter between a and z
pass does nothing a|b a or b

You might also like