Python Syntax and Commands Cheat Sheet
Python Syntax and Commands 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([Link]()) 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"]
[Link]("orange") [Link](1, "orange") [Link]("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"}
[Link]("banana") [Link]("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 = [Link]() [Link]()
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 [Link]():
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 [Link](): 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)
[Link]()
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
[Link]("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 = [Link]() import datetime
print(x) x = [Link]()
print([Link]) print([Link]("%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([Link]({"name": "John", "age":
x = '{ "name":"John", "age":30, x={ 30}))
"city":"New York"}' "name": "John", print([Link](["apple", "bananas"]))
# parse x: "age": 30, print([Link](("apple", "bananas")))
y = [Link](x) "city": "New York" print([Link]("hello"))
# the result is a Python dictionary: } print([Link](42))
print(y["age"]) # convert into JSON: print([Link](31.76))
y = [Link](x) print([Link](True))
# the result is a JSON string: print([Link](False))
print(y) print([Link](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 = [Link](x) print([Link](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([Link](x, indent=4, separators=(". ", " = "))) print([Link](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 = [Link]("^The.*Spain$", txt) x = [Link]("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 = [Link]("\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:", [Link]()) x = [Link]("\s", txt) x = [Link]("\s", "9", txt)
print(x) print(x)
Python PIP
Using a package
import camelcase
c = [Link]()
txt = "lorem ipsum dolor sit amet"
print([Link](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("[Link]", "r") f = open("[Link]", "r")
print([Link]()) print([Link](5))
Read one line of a file Loop through the lines of a file to read the whole file, line by line
f = open("[Link]", "r") f = open("[Link]", "r")
print([Link]()) 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 [Link] import [Link] import [Link]
mydb = [Link]( mydb = [Link]( mydb = [Link](
host="localhost", host="localhost", host="localhost",
user="myusername", user="myusername", user="myusername",
passwd="mypassword" passwd="mypassword" passwd="mypassword"
) ) )
print(mydb) mycursor = [Link]() mycursor = [Link]()
[Link]("CREATE DATABASE [Link]("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 [Link] import [Link] row in a table
mydb = [Link]( mydb = [Link]( import [Link]
host="localhost", host="localhost", mydb = [Link](
user="myusername", user="myusername", host="localhost",
passwd="mypassword", passwd="mypassword", user="myusername",
database="mydatabase" database="mydatabase" passwd="mypassword",
) ) database="mydatabase"
mycursor = [Link]() mycursor = [Link]() )
[Link]("SELECT * FROM [Link]("SELECT name, address mycursor = [Link]()
customers") FROM customers") [Link]("SELECT * FROM
myresult = [Link]() myresult = [Link]() customers")
for x in myresult: for x in myresult: myresult = [Link]()
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 [Link] (reverse alphabetically) import [Link]
mydb = [Link]( import [Link] mydb = [Link](
host="localhost", mydb = [Link]( host="localhost",
user="myusername", host="localhost", user="myusername",
passwd="mypassword", user="myusername", passwd="mypassword",
database="mydatabase" passwd="mypassword", database="mydatabase"
) database="mydatabase" )
mycursor = [Link]() ) mycursor = [Link]()
sql = "SELECT * FROM customers mycursor = [Link]() sql = "DELETE FROM customers WHERE
ORDER BY name" sql = "SELECT * FROM customers address = 'Mountain 21'"
[Link](sql) ORDER BY name DESC" [Link](sql)
myresult = [Link]() [Link](sql) [Link]()
for x in myresult: myresult = [Link]() print([Link], "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 [Link] import [Link] query
mydb = [Link]( mydb = [Link]( import [Link]
host="localhost", host="localhost", mydb = [Link](
user="myusername", user="myusername", host="localhost",
passwd="mypassword", passwd="mypassword", user="myusername",
database="mydatabase" database="mydatabase" passwd="mypassword",
) ) database="mydatabase"
mycursor = [Link]() mycursor = [Link]() )
sql = "UPDATE customers SET address = sql = "UPDATE customers SET address = mycursor = [Link]()
'Canyon 123' WHERE address = 'Valley %s WHERE address = %s" [Link]("SELECT * FROM
345'" val = ("Valley 345", "Canyon 123") customers LIMIT 5")
[Link](sql) [Link](sql, val) myresult = [Link]()
[Link]() [Link]() for x in myresult:
print([Link], "record(s) print([Link], "record(s) print(x)
affected") affected")
Combine rows from two or more tables, mycursor = [Link]() for x in myresult:
based on a related column between them sql = "SELECT \ print(x)
import [Link] [Link] AS user, \ LEFT JOIN
mydb = [Link]( [Link] AS favorite \ import [Link]
host="localhost", FROM users \ mydb = [Link](
user="myusername", INNER JOIN products ON [Link] = host="localhost",
passwd="mypassword", [Link]" user="myusername",
database="mydatabase" [Link](sql) passwd="mypassword",
) myresult = [Link]() database="mydatabase"
) print(x) sql = "SELECT \
mycursor = [Link]() [Link] AS user, \
sql = "SELECT \ RIGHT JOIN [Link] AS favorite \
[Link] AS user, \ import [Link] FROM users \
[Link] AS favorite \ mydb = [Link]( RIGHT JOIN products ON [Link] =
FROM users \ host="localhost", [Link]"
LEFT JOIN products ON [Link] = user="myusername", [Link](sql)
[Link]" passwd="mypassword", myresult = [Link]()
[Link](sql) database="mydatabase" for x in myresult:
myresult = [Link]() ) print(x)
for x in myresult: mycursor = [Link]()
Python MongoDB
Create a database Check if a database exist Create a collection
import pymongo import pymongo import pymongo
myclient = myclient = myclient =
[Link]('mongodb://localho [Link]('mongodb://localho [Link]('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 = [Link]("mongodb://localhost:27017/") myclient = [Link]("mongodb://localhost:27017/")
mydb = myclient["mydatabase"] mydb = myclient["mydatabase"]
mycol = mydb["customers"] mycol = mydb["customers"]
x mycol.find_one() for x in [Link]():
print(x) print(x)
Find only some fields Filter the result
import pymongo import pymongo
myclient = [Link]("mongodb://localhost:27017/") myclient = [Link]("mongodb://localhost:27017/")
mydb = myclient["mydatabase"] mydb = myclient["mydatabase"]
mycol = mydb["customers"] mycol = mydb["customers"]
for x in [Link]({},{ "_id": 0, "name": 1, "address": 1 }): myquery = { "address": "Park Lane 38" }
print(x) mydoc = [Link](myquery)
for x in mydoc:
print(x)
Sort the result alphabetically Sort the result descending (reverse alphabetically)
import pymongo import pymongo
myclient = [Link]("mongodb://localhost:27017/") myclient = [Link]("mongodb://localhost:27017/")
mydb = myclient["mydatabase"] mydb = myclient["mydatabase"]
mycol = mydb["customers"] mycol = mydb["customers"]
mydoc = [Link]().sort("name") mydoc = [Link]().sort("name", -1)
for x in mydoc: for x in mydoc:
print(x) print(x)









