Python Programming Cheat Sheet
Python Programming Cheat Sheet
Python Variables
Create a variable Output both text and a variable Add a variable to another variable
x=5 x="awesome" x="Python is "
y="John" print("This is "+x) y="awesome"
print(x) z=x+y
print(y) print(z)
Python Numbers
Verify the type of an object Create integers Create floating point numbers
x=1 x=1 x=1.10
y=2.3 y=2655546464 y=1.0
z=1j z=-25448484 z=-25.44
print(type(x)) print(type(x)) print(type(x))
print(type(y)) print(type(y)) print(type(y))
print(type(z)) print(type(z)) print(type(z))
Create scientific numbers with an "e" to indicate the power of 10 Create complex numbers
x=35e3 x=3+5j
y=12E4 y=5j
z=-25.4e48484 z=-5j
print(type(x)) print(type(x))
print(type(y)) print(type(y))
print(type(z)) print(type(z))
Python Casting
Casting - Integers Casting - Floats Casting - Strings
x=int(1) x=float(1) x=str(1)
y=int(2.8) y=float(2.8) y=str(2.8)
z=int("3") z=float("3") z=str("s3")
print(x) print(x) print(x)
print(y) print(y) print(y)
print(z) print(z) print(z)
Python Strings
Get the character at position 1 of a string Substring. Get the characters from position 2 to position 5 (not
a="Hello" included)
print(a[1]) a="Hello darkness"
print(a[2:5])
Remove whitespace from the beginning or at the end of a string Return the length of a string
a = " Hello, World! " a = "Hello, World!"
print(a.strip()) print(len(a))
Python Lists
Create a list Access list items Change the value of a list item
thislist = ["apple", "banana", "cherry"] thislist = ["apple", "banana", "cherry"] thislist = ["apple", "banana", "cherry"]
print(thislist) print(thislist[1]) thislist[1] = "blackcurrant"
print(thislist)
Loop through a list Check if a list item exists Get the length of a list
thislist = ["apple", "banana", "cherry"] thislist = ["apple", "banana", "cherry"] thislist = ["apple", "banana", "cherry"]
for x in thislist: if "apple" in thislist: print(len(thislist))
print(x) print("Yes, 'apple' is in the fruits list")
Add an item to the end of a list Add an item at a specified index Remove an item
thislist = ["apple", "banana", "cherry"] thislist = ["apple", "banana", "cherry"] thislist = ["apple", "banana", "cherry"]
thislist.append("orange") thislist.insert(1, "orange") thislist.remove("banana")
print(thislist) print(thislist) print(thislist)
Python Tuples
Create a tuple Access tuple items Change tuple values
thistuple = ("apple", "banana", "cherry") thistuple = ("apple", "banana", "cherry") thistuple = ("apple", "banana", "cherry")
print(thistuple print(thistuple[1]) thistuple[1] = "blackcurrant"
# the value is still the same:
print(thistuple)
Loop through a tuple Check if a tuple item exists Get the length of a tuple
thistuple = ("apple", "banana", "cherry") thistuple = ("apple", "banana", "cherry") thistuple = ("apple", "banana", "cherry")
for x in thistuple: if "apple" in thistuple: print(len(thistuple))
print(x) print("Yes, 'apple' is in the fruits tuple")
Python Sets
Create a set # Note: the set list is unordered, meaning: the items will appear in a
thisset = {"apple", "banana", "cherry"} random order.
print(thisset) # Refresh this page to see the change in the result.
for x in thisset:
Loop through a set print(x)
thisset = {"apple", "banana", "cherry"}
Remove an item in a set Remove an item in a set by using the discard() method
thisset = {"apple", "banana", "cherry"} thisset = {"apple", "banana", "cherry"}
thisset.remove("banana") thisset.discard("banana")
print(thisset) print(thisset)
Remove the last item in a set by using the pop() method Empty a set
thisset = {"apple", "banana", "cherry"} thisset = {"apple", "banana", "cherry"}
x = thisset.pop() thisset.clear()
print(x) #removed item print(thisset)
print(thisset) #the set after removal
Python Dictionaries
Create a dictionary Access the items of a dictionary Change the value of a specific item in a
thisdict = { thisdict = { dictionary
"brand": "Ford", "brand": "Ford", thisdict = {
"model": "Mustang", "model": "Mustang", "brand": "Ford",
"year": 1964 "year": 1964 "model": "Mustang",
} } "year": 1964
print(thisdict) x = thisdict["model"] }
print(x) thisdict["year"] = 2018
print(thisdict)
Print all key names in a dictionary, one by Print all values in a dictionary, one by one Using the values() function to return values
one thisdict = { of a dictionary
thisdict = { "brand": "Ford", thisdict = {
"brand": "Ford", "model": "Mustang", "brand": "Ford",
"model": "Mustang", "year": 1964 "model": "Mustang",
"year": 1964 } "year": 1964
} for x in thisdict: }
for x in thisdict: print(thisdict[x]) for x in thisdict.values():
print(x) print(x)
Loop through both keys an values, by using Check if a key exists Get the length of a dictionary
the items() function thisdict = { thisdict = {
thisdict = { "brand": "Ford", "brand": "Ford",
"brand": "Ford", "model": "Mustang", "model": "Mustang",
"model": "Mustang", "year": 1964 "year": 1964
"year": 1964 } }
} if "model" in thisdict: print(len(thisdict))
for x, y in thisdict.items(): print("Yes, 'model' is one of the keys in the
print(x, y) thisdict dictionary")
Empty a dictionary
thisdict = { Using the dict() constructor to create a dictionary
"brand": "Ford", thisdict = dict(brand="Ford", model="Mustang", year=1964)
"model": "Mustang", # note that keywords are not string literals
"year": 1964 # note the use of equals rather than colon for the assignment
} print(thisdict)
thisdict.clear()
print(thisdict)
Using the break statement in a for loop Using the continue statement in a for loop
fruits = ["apple", "banana", "cherry"] fruits = ["apple", "banana", "cherry"]
for x in fruits: for x in fruits:
print(x) if x == "banana":
if x == "banana": continue
break print(x)
Python Functions
Create and call a function Function parameters Default parameter value
def my_function(): def my_function(fname): def my_function(country = "Norway"):
print("Hello from a function") print(fname + " Refsnes") print("I am from " + country)
my_function() my_function("Emil") my_function("Sweden")
my_function("Tobias") my_function("India")
my_function("Linus") my_function()
my_function("Brazil")
Python Lambda
A lambda function that adds 10 to the A lambda function that multiplies argument A lambda function that sums argument a, b,
number passed in as an argument a with argument b and c
x = lambda a: a + 10 x = lambda a, b: a * b x = lambda a, b, c: a + b + c
print(x(5)) print(x(5, 6)) print(x(5, 6, 2))
Python Arrays
Create an array Access the elements of an array Change the value of an array element
cars = ["Ford", "Volvo", "BMW"] cars = ["Ford", "Volvo", "BMW"] cars = ["Ford", "Volvo", "BMW"]
print(cars) x = cars[0] cars[0] = "Toyota"
print(x) print(cars)
Python Iterators
Return an iterator from a tuple Return an iterator from a string Loop through an iterator
mytuple = ("apple", "banana", "cherry") mystr = "banana" mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple) myit = iter(mystr) for x in mytuple:
print(next(myit)) print(next(myit)) print(x)
print(next(myit)) print(next(myit))
print(next(myit)) print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
Python Modules
Use a module Variables in module Re-naming a module
import mymodule import mymodule import mymodule as mx
mymodule.greeting("Jonathan") a = mymodule.person1["age"] a = mx.person1["age"]
print(a) print(a)
Python Dates
Import the datetime module and display the current date
import datetime Return the year and name of weekday
x = datetime.datetime.now() import datetime
print(x) x = datetime.datetime.now()
print(x.year) print(x.strftime("%A"))
Python JSON
Convert from JSON to Python Convert from Python to JSON Convert Python objects into JSON strings
import json import json import json
# some JSON: # a Python object (dict): print(json.dumps({"name": "John", "age":
x = '{ "name":"John", "age":30, x={ 30}))
"city":"New York"}' "name": "John", print(json.dumps(["apple", "bananas"]))
# parse x: "age": 30, print(json.dumps(("apple", "bananas")))
y = json.loads(x) "city": "New York" print(json.dumps("hello"))
# the result is a Python dictionary: } print(json.dumps(42))
print(y["age"]) # convert into JSON: print(json.dumps(31.76))
y = json.dumps(x) print(json.dumps(True))
# the result is a JSON string: print(json.dumps(False))
print(y) print(json.dumps(None))
Convert a Python object containing all the legal data types Use the indent parameter to define the numbers of indents
import json import json
x={ x={
"name": "John", "name": "John",
"age": 30, "age": 30,
"married": True, "married": True,
"divorced": False, "divorced": False,
"children": ("Ann","Billy"), "children": ("Ann","Billy"),
"pets": None, "pets": None,
"cars": [ "cars": [
{"model": "BMW 230", "mpg": 27.5}, {"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1} {"model": "Ford Edge", "mpg": 24.1}
] ]
} }
# convert into JSON: # use four indents to make it easier to read the result:
y = json.dumps(x) print(json.dumps(x, indent=4))
# the result is a JSON string:
print(y)
Use the separators parameter to change the default separator Use the sort_keys parameter to specify if the result should be sorted
import json or not
x={ import json
"name": "John", x={
"age": 30, "name": "John",
"married": True, "age": 30,
"divorced": False, "married": True,
"children": ("Ann","Billy"), "divorced": False,
"pets": None, "children": ("Ann","Billy"),
"cars": [ "pets": None,
{"model": "BMW 230", "mpg": 27.5}, "cars": [
{"model": "Ford Edge", "mpg": 24.1} {"model": "BMW 230", "mpg": 27.5},
] {"model": "Ford Edge", "mpg": 24.1}
} ]
# use . and a space to separate objects, and a space, a = and a space to }
separate keys from their values: # sort the result alphabetically by keys:
print(json.dumps(x, indent=4, separators=(". ", " = "))) print(json.dumps(x, indent=4, sort_keys=True))
Python RegEx
Search a string to see if it starts with "The" and ends with "Spain" Using the findall() function
import re import re
#Check if the string starts with "The" and ends with "Spain": #Return a list containing every occurrence of "ai":
txt = "The rain in Spain" txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt) x = re.findall("ai", txt)
if (x): print(x)
print("YES! We have a match!")
else:
print("No match")
Using the search() function Using the split() function Using the sub() function
import re import re import re
txt = "The rain in Spain" #Split the string at every white-space #Replace all white-space characters with the
x = re.search("\s", txt) character: digit "9":
print("The first white-space character is txt = "The rain in Spain" txt = "The rain in Spain"
located in position:", x.start()) x = re.split("\s", txt) x = re.sub("\s", "9", txt)
print(x) print(x)
Python PIP
Using a package
import camelcase
c = camelcase.CamelCase()
txt = "lorem ipsum dolor sit amet"
print(c.hump(txt))
#This method capitalizes the first letter of each word.
Use the else keyword to define a block of code to be executed if no Use the finally block to execute code regardless if the try block raises
errors were raised an error or not
#The try block does not raise any errors, so the else block is #The finally block gets executed no matter if the try block raises any
executed: errors or not:
try: try:
print("Hello") print(x)
except: except:
print("Something went wrong") print("Something went wrong")
else: finally:
print("Nothing went wrong") print("The 'try except' is finished")
Python Files
Read a file Read only parts of a file
f = open("demofile.txt", "r") f = open("demofile.txt", "r")
print(f.read()) print(f.read(5))
Read one line of a file Loop through the lines of a file to read the whole file, line by line
f = open("demofile.txt", "r") f = open("demofile.txt", "r")
print(f.readline()) for x in f:
print(x)
Python MySQL
Create a connection to a database Create a database in MySQL Check if a database exist
import mysql.connector import mysql.connector import mysql.connector
mydb = mysql.connector.connect( mydb = mysql.connector.connect( mydb = mysql.connector.connect(
host="localhost", host="localhost", host="localhost",
user="myusername", user="myusername", user="myusername",
passwd="mypassword" passwd="mypassword" passwd="mypassword"
) ) )
print(mydb) mycursor = mydb.cursor() mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mycursor.execute("SHOW DATABASES")
mydatabase") for x in mycursor:
#If this page is executed with no error, you print(x)
have successfully created a database.
Select all records from a table Select only some of the columns in a table Use the fetchone() method to fetch only one
import mysql.connector import mysql.connector row in a table
mydb = mysql.connector.connect( mydb = mysql.connector.connect( import mysql.connector
host="localhost", host="localhost", mydb = mysql.connector.connect(
user="myusername", user="myusername", host="localhost",
passwd="mypassword", passwd="mypassword", user="myusername",
database="mydatabase" database="mydatabase" passwd="mypassword",
) ) database="mydatabase"
mycursor = mydb.cursor() mycursor = mydb.cursor() )
mycursor.execute("SELECT * FROM mycursor.execute("SELECT name, address mycursor = mydb.cursor()
customers") FROM customers") mycursor.execute("SELECT * FROM
myresult = mycursor.fetchall() myresult = mycursor.fetchall() customers")
for x in myresult: for x in myresult: myresult = mycursor.fetchone()
print(x) print(x) print(myresult)
Sort the result of a table alphabetically Sort the result in a descending order Delete records from an existing table
import mysql.connector (reverse alphabetically) import mysql.connector
mydb = mysql.connector.connect( import mysql.connector mydb = mysql.connector.connect(
host="localhost", mydb = mysql.connector.connect( host="localhost",
user="myusername", host="localhost", user="myusername",
passwd="mypassword", user="myusername", passwd="mypassword",
database="mydatabase" passwd="mypassword", database="mydatabase"
) database="mydatabase" )
mycursor = mydb.cursor() ) mycursor = mydb.cursor()
sql = "SELECT * FROM customers mycursor = mydb.cursor() sql = "DELETE FROM customers WHERE
ORDER BY name" sql = "SELECT * FROM customers address = 'Mountain 21'"
mycursor.execute(sql) ORDER BY name DESC" mycursor.execute(sql)
myresult = mycursor.fetchall() mycursor.execute(sql) mydb.commit()
for x in myresult: myresult = mycursor.fetchall() print(mycursor.rowcount, "record(s)
print(x) for x in myresult: deleted")
print(x)
Update existing records in a table Prevent SQL injection Limit the number of records returned from a
import mysql.connector import mysql.connector query
mydb = mysql.connector.connect( mydb = mysql.connector.connect( import mysql.connector
host="localhost", host="localhost", mydb = mysql.connector.connect(
user="myusername", user="myusername", host="localhost",
passwd="mypassword", passwd="mypassword", user="myusername",
database="mydatabase" database="mydatabase" passwd="mypassword",
) ) database="mydatabase"
mycursor = mydb.cursor() mycursor = mydb.cursor() )
sql = "UPDATE customers SET address = sql = "UPDATE customers SET address = mycursor = mydb.cursor()
'Canyon 123' WHERE address = 'Valley %s WHERE address = %s" mycursor.execute("SELECT * FROM
345'" val = ("Valley 345", "Canyon 123") customers LIMIT 5")
mycursor.execute(sql) mycursor.execute(sql, val) myresult = mycursor.fetchall()
mydb.commit() mydb.commit() for x in myresult:
print(mycursor.rowcount, "record(s) print(mycursor.rowcount, "record(s) print(x)
affected") affected")
Combine rows from two or more tables, mycursor = mydb.cursor() for x in myresult:
based on a related column between them sql = "SELECT \ print(x)
import mysql.connector users.name AS user, \ LEFT JOIN
mydb = mysql.connector.connect( products.name AS favorite \ import mysql.connector
host="localhost", FROM users \ mydb = mysql.connector.connect(
user="myusername", INNER JOIN products ON users.fav = host="localhost",
passwd="mypassword", products.id" user="myusername",
database="mydatabase" mycursor.execute(sql) passwd="mypassword",
) myresult = mycursor.fetchall() database="mydatabase"
) print(x) sql = "SELECT \
mycursor = mydb.cursor() users.name AS user, \
sql = "SELECT \ RIGHT JOIN products.name AS favorite \
users.name AS user, \ import mysql.connector FROM users \
products.name AS favorite \ mydb = mysql.connector.connect( RIGHT JOIN products ON users.fav =
FROM users \ host="localhost", products.id"
LEFT JOIN products ON users.fav = user="myusername", mycursor.execute(sql)
products.id" passwd="mypassword", myresult = mycursor.fetchall()
mycursor.execute(sql) database="mydatabase" for x in myresult:
myresult = mycursor.fetchall() ) print(x)
for x in myresult: mycursor = mydb.cursor()
Python MongoDB
Create a database Check if a database exist Create a collection
import pymongo import pymongo import pymongo
myclient = myclient = myclient =
pymongo.MongoClient('mongodb://localho pymongo.MongoClient('mongodb://localho pymongo.MongoClient('mongodb://localho
st:27017/') st:27017/') st:27017/')
mydb = myclient['mydatabase'] print(myclient.list_database_names()) mydb = myclient['mydatabase']
# database created! mycol = mydb["customers"]
# collection created!
Find the first document in the selection Find all documents in the selection
import pymongo import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/") myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"] mydb = myclient["mydatabase"]
mycol = mydb["customers"] mycol = mydb["customers"]
x mycol.find_one() for x in mycol.find():
print(x) print(x)
Find only some fields Filter the result
import pymongo import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/") myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"] mydb = myclient["mydatabase"]
mycol = mydb["customers"] mycol = mydb["customers"]
for x in mycol.find({},{ "_id": 0, "name": 1, "address": 1 }): myquery = { "address": "Park Lane 38" }
print(x) mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
Sort the result alphabetically Sort the result descending (reverse alphabetically)
import pymongo import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/") myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"] mydb = myclient["mydatabase"]
mycol = mydb["customers"] mycol = mydb["customers"]
mydoc = mycol.find().sort("name") mydoc = mycol.find().sort("name", -1)
for x in mydoc: for x in mydoc:
print(x) print(x)