Lists
Create an empty list |
newlist=[] |
Assign value at index |
alist[index]= value |
Access value at index |
alist[index] |
Add item to list |
alist.append(new item) |
Insert into list |
alist.insert(at position, new item) |
Count # of an item in list |
alist.count( item ) |
Delete 1 matching item |
alist.remove(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 indexes/values 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 immediately |
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 |
Subtraction |
X - Y |
2 |
Multiplication |
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(txt,encoding) |
str(data,"utf8") |
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(integer) |
hex(255) hex(10) |
'0xff' '0xa' |
integer -> binary string |
bin(integer) |
bin(5) bin(3) |
'0b101' '0b11' |
float -> integer |
int(float) drops decimal |
int(3.14159) 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(integer) |
chr(65) chr(49) |
'A' '1' |
bytes -> string |
<bytes>.decode() |
b'ABC'.decode() |
'ABC' |
string -> bytes |
<str>.encode() |
'abc'.encode() |
b'abc' |
Useful OS functions
import os |
Executing a shell command |
os.system() |
Rename the file or directory src to dst |
os.rename(src, dst) |
Change working directory |
os.chdir(path) |
Get the users environment |
os.environ() |
Returns the current working directory |
os.getcwd() |
|
|
Dictionaries
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.keys() |
Iterable View of all values |
dict.values() |
Iterable View of (key,value) tuples |
dict.items() |
Slicing and Indexing
x[start:stop: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('{}'.format(STRING)) |
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".lower()="ab" |
Make UPPERCASE |
"Ab".upper()="AB" |
Make Title Format |
"hi world".title()="Hi World" |
Replace a substring |
"123".replace('2','z')= "1z3" |
Count occurrences of substring |
"1123".count("1")=2 |
Get offset of substring in string |
"123".index("2")=1 |
Detect substring in string |
“is” in “fish” == True |
|
Created By
Metadata
Favourited By
Comments
No comments yet. Add yours below!
Add a Comment
Related Cheat Sheets