Show Menu
Cheatography

Basic Cheat Sheet for Python 3

Lists

Create an empty list
newlist=[]
Assign value at index
alist[­index]= value
Access value at index
alist[­index]
Add item to list
alist.a­pp­end(new item)
Insert into list
alist.i­ns­ert(at position, new item)
Count # of an item in list
alist.c­ount( item )
Delete 1 matching item
alist.r­em­ove(del item)
Remove item at index
del alist[­index]

Looping

For loop 0 thru 9
for x in range(10):
For loop 5 thru 10
for x in range(­5,11):
For each char in a string
for char in astring:
For items in list
for x in alist:
For indexe­s/v­alues in a list
for index,value in enumerate(alist):
For each key in a dict
for x in adict.keys():
For all items in dict
for key,value in adict.items():
while <logic test>
do:
Exit loop immedi­ately
break
Skip rest of loop and do loop again
continue

Logic and Math Operators

Math Operator
Example
X=7, Y=5
Addition
X + Y
12
Subtra­ction
X - Y
2
Multip­lic­ation
X * Y
35
Division
X / Y
1.4
Floor
X // Y
1
Exponent
X ** Y
16807
Modulo
X % Y
2
Logic Operator
Equality
X == Y
False
Greater Than
X > Y
False
Less Than
X < Y
True
Less or Equal
X <= Y
True
Not Equal
X !=Y or X<>Y
True
Bitwise Exclusive Or
a ^ b
xor(a, b)

Converting Data Types

Covert
Syntax
Example
Result
Num -> string
str(number)
int, float or long
str(100)
str(3.14)
'100'
'3.14'
Encoded bytes -> string
str(tx­t,e­nco­ding)
str(da­ta,­"­utf­8")
string with data
Num String -> int
int("string",base)
default base is 10
int("42­")
int("101",2)
int("ff­", 16)
42
5
255
int -> hex string
hex(in­teger)
hex(255) hex(10)
'0xff'
'0xa'
integer -> binary string
bin(in­teger)
bin(5) bin(3)
'0b101'
'0b11'
float -> integer
int(float)
drops decimal
int(3.1­4159) int(3.9)
3
3
int or str -> float
float(int or str)
float(­"­3.4­") float(3)
3.4
3.0
String -> ASCII
ord(str)
ord("A") ord("1")
65
49
int -> ASCII
chr(in­teger)
chr(65)
chr(49)
'A'
'1'
bytes -> string
<bytes>.decode()
b'ABC'.decode()
'ABC'
string -> bytes
<str>.encode()
'abc'.e­nc­ode()
b'abc'

Useful OS functions

import os
Executing a shell command
os.sys­tem()
Rename the file or directory src to dst
os.ren­ame­(src, dst)
Change working directory
os.chd­ir(­path)
Get the users enviro­nment
os.env­iron()
Returns the current working directory
os.get­cwd()
 

Dictio­naries

Create an empty dict
dict={}
Initialize a non-empty dictionary
dict= { “key”:”value”,”key2”:”value2”}
Assign a value
dict[“key”]=”value”
Determine if key exists
"­key­" in dict
Access value at key
dict[“key”], dict.get(“key”)
Iterable View of all keys
dict.k­eys()
Iterable View of all values
dict.v­alues()
Iterable View of (key,v­alue) tuples
dict.i­tems()

Slicing and Indexing

x[star­t:s­top­:step]
x=[4,8­,9,3,0]
x=”48930”
x[0]
4
‘4’
x[2]
9
'9'
x[:3]
[4,8,9]
'489'
x[3:]
[3,0]
'30'
x[:-2]
[4,8,9]
'489'
x[::2]
[4,9,0]
‘490’
x[::-1]
[0,3,9­,8,4]
‘03984’
len(x)
5
5
sorted(x)
[0,3,4­,8,9]
['0','­3',­'4'­,'8­','9']

Misc

Adding Comments to code:
#Comments begin the line with a pound sign

Adding Multi-line Comment to code
"""
Multi-Line Comment
"""

Get user input from keyboard
name = input("What is your name? ")

Functions
def add(num1, num2):
     #code blocks must be indented
     #each space has meaning in python
     myresult = num1 + num2
     return myresult

if then else statements
if <logic test 1>:
     #code block here will execute
     #when logic test 1 is True
elif <logic test 2>:
     #code block executes if logic test 1 is
     #False and logic test 2 is True
else:
     #else has no test and executes when if
     #and all elif are False

python3 shebang
#!/usr/bin/env python3

Printing

Standard print
print(­'{}­'.f­orm­at(­STR­ING))
Print string variable
print ("I am %s" % name)
Print int variable
print ("I am %d" % number)
Print with +
print ("I am " + name)

String Operations

Make lowercase
"­Ab".l­ow­er(­)="a­b"
Make UPPERCASE
"­Ab".u­pp­er(­)="A­B"
Make Title Format
"hi world".t­it­le(­)="Hi World"
Replace a substring
"­123­".re­pla­ce(­'2'­,'z')= "­1z3­"
Count occurr­ences of substring
"­112­3".c­oun­t("1­")=2
Get offset of substring in string
"­123­".in­dex­("2")=1
Detect substring in string
“is” in “fish” == True
               
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

            Python 3 Cheat Sheet by Finxter