Python Programming Cheat Sheet

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

Python Syntax

Print "Hello World" Comments in Python Docstrings


print(“Hello world”) #This is a comment """This is a
print("Hello, World!") multiline docstring"""
print("Hello, World!")

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))

Convert a string to lower case Convert a string to upper case


a = "Hello, World!" a = "Hello, World!"
print(a.lower()) print(a.upper())

Replace a string with another string Split a string into substrings


a = "Hello, World!" a = "Hello, World!"
print(a.replace("H", "J")) b = a.split(",")
print(b)
Python Operators
Addition operator Subtraction operator Multiplication operator
x=5 x=5 x=5
y=3 y=3 y=3
print(x + y) print(x - y) print(x * y)

Division operator Modulus operator


x = 12 x=5 Assignment operator
y=3 y=2 x=5
print(x / y) print(x % y) print(x)

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)

Remove the last item Remove an item at a specified index


thislist = ["apple", "banana", "cherry"] thislist = ["apple", "banana", "cherry"]
thislist.pop() del thislist[0]
print(thislist) print(thislist)

Empty a list Using the list() constructor to make a list


thislist = ["apple", "banana", "cherry"] thislist = list(("apple", "banana", "cherry"))
thislist.clear() 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")

Delete a tuple Using the tuple() constructor to create a tuple


thistuple = ("apple", "banana", "cherry") thistuple = tuple(("apple", "banana", "cherry"))
del thistuple print(thistuple)
print(thistuple) #this will raise an error because the tuple no longer
exists

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"}

Check if an item exists Add an item to a set


thisset = {"apple", "banana", "cherry"} thisset = {"apple", "banana", "cherry"}
print("banana" in thisset) thisset.add("orange")
print(thisset)

Add multiple items to a set Get the length of a set


thisset = {"apple", "banana", "cherry"} thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"]) print(len(thisset))
print(thisset)

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

Delete a set Using the set() constructor to create a set


thisset = {"apple", "banana", "cherry"} thisset = set(("apple", "banana", "cherry"))
del thisset print(thisset)
print(thisset) #this will raise an error because the set no longer exists # Note: the set list is unordered, so the result will display the items in
a random order.

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")

Add an item to a dictionary print(thisdict)


thisdict = {
"brand": "Ford", Remove an item from a dictionary
"model": "Mustang", thisdict = {
"year": 1964 "brand": "Ford",
} "model": "Mustang",
thisdict["color"] = "red" "year": 1964
} print(thisdict)
thisdict.pop("model")

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)

Python If ... Else


The if statement The elif statement The else statement
a = 33 a = 33 a = 200
b = 200 b = 33 b = 33
if b > a: if b > a: if b > a:
print("b is greater than a") print("b is greater than a") print("b is greater than a")
elif a == b: elif a == b:
print("a and b are equal") print("a and b are equal")
else:
print("a is greater than b")

Short hand if Short hand if ... else


a = 200 a=2
b = 33 b = 330
if a > b: print("a is greater than b") print("A") if a > b else print("B")

The and keyword The or keyword


a = 200 a = 200
b = 33 b = 33
c = 500n c = 500
if a > b ad c > a: if a > b or a > c:
print("Both conditions are True") print("At least one of the conditions is True")

Python While Loop


The while loop Using the break statement in a while loop Using the continue statement in a while
i=1 i=1 loop
while i < 6: while i < 6: i=0
print(i) print(i) while i < 6:
i += 1 if (i == 3): i += 1
break if i == 3:
i += 1 continue
print(i)
# Note that number 3 is missing in the result

Python For Loop


The for loop Loop through a string
fruits = ["apple", "banana", "cherry"] for x in "banana":
for x in fruits: print(x)
print(x)

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)

Using the range() function in a for loop print(x)


for x in range(6):
Else in for loop print("Finally finished!") fruits = ["apple", "banana", "cherry"]
for x in range(6): for x in adj:
print(x) Nested for loop for y in fruits:
else: adj = ["red", "big", "tasty"] print(x, y)

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")

Let a function return a value Recursion


def my_function(x): def tri_recursion(k):
return 5 * x if(k > 0):
print(my_function(3)) result = k + tri_recursion(k - 1)
print(my_function(5)) print(result)
print(my_function(9)) else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)

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)

Get the length of an array Loop through all elements of an array


cars = ["Ford", "Volvo", "BMW"] cars = ["Ford", "Volvo", "BMW"]
x = len(cars) for x in cars:
print(x) print(x)

Add an element to an array Remove an element from an array


cars = ["Ford", "Volvo", "BMW"] cars = ["Ford", "Volvo", "BMW"]
cars.append("Honda") cars.pop(1)
print(cars) print(cars)

Python Classes and Objects


Create a class Create an object
class MyClass: class MyClass:
x=5 x=5
print(MyClass) p1 = MyClass()
print(p1.x)

The __init__() Function self.name = name print(p1.name)


class Person: self.age = age print(p1.age)
def __init__(self, name, age): p1 = Person("John", 36)
print("Hello my name is " + self.name) mysillyobject.name = name
Create object methods p1 = Person("John", 36) mysillyobject.age = age
class Person: p1.myfunc() def myfunc(abc):
def __init__(self, name, age): print("Hello my name is " + abc.name)
self.name = name The self parameter p1 = Person("John", 36)
self.age = age class Person: p1.myfunc()
def myfunc(self): def __init__(mysillyobject, name, age):

Modify object properties Delete object properties Delete an object


class Person: class Person: class Person:
def __init__(self, name, age): def __init__(self, name, age): def __init__(self, name, age):
self.name = name self.name = name self.name = name
self.age = age self.age = age self.age = age
def myfunc(self): def myfunc(self): def myfunc(self):
print("Hello my name is " + self.name) print("Hello my name is " + self.name) print("Hello my name is " + self.name)
p1 = Person("John", 36) p1 = Person("John", 36) p1 = Person("John", 36)
p1.age = 40 del p1.age del p1
print(p1.age) print(p1.age) print(p1)

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))

Create an iterator Stop iteration


class MyNumbers: class MyNumbers:
def __iter__(self): def __iter__(self):
self.a = 1 self.a = 1
return self return self
def __next__(self): def __next__(self):
x = self.a if self.a <= 20:
self.a += 1 x = self.a
return x self.a += 1
myclass = MyNumbers() return x
myiter = iter(myclass) else:
print(next(myiter)) raise StopIteration
print(next(myiter)) myclass = MyNumbers()
print(next(myiter)) myiter = iter(myclass)
print(next(myiter)) for x in myiter:
print(next(myiter)) print(x)

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)

Built-in modules Using the dir() function Import from module


import platform import platform from mymodule import person1
x = platform.system() x = dir(platform) print(person1["age"])
print(x) print(x)

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"))

Create a date object The strftime() Method


import datetime import datetime
x = datetime.datetime(2020, 5, 17) x = datetime.datetime(2018, 6, 1)
print(x) print(x.strftime("%B"))

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.

Python Try Except


When an error occurs, print a message Many exceptions
#The try block will generate an error, because x is not defined: #The try block will generate a NameError, because x is not defined:
try: try:
print(x) print(x)
except: except NameError:
print("An exception occurred") print("Variable x is not defined")
except:
print("Something else went wrong")

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.

Create a table ) #If this page is executed with no error, you


import mysql.connector mycursor = mydb.cursor() have successfully created a table named
mydb = mysql.connector.connect( mycursor.execute("CREATE TABLE "customers".
host="localhost", customers (name VARCHAR(255), address Check if a table exist
user="myusername", VARCHAR(255))") import mysql.connector
passwd="mypassword", mydb = mysql.connector.connect(
database="mydatabase" host="localhost",
user="myusername", )
passwd="mypassword", mycursor = mydb.cursor()
database="mydatabase" Create primary key when creating a table mycursor.execute("CREATE TABLE
) import mysql.connector customers (id INT AUTO_INCREMENT
mycursor = mydb.cursor() mydb = mysql.connector.connect( PRIMARY KEY, name VARCHAR(255),
mycursor.execute("SHOW TABLES") host="localhost", address VARCHAR(255))")
for x in mycursor: user="yourusername", #If this page is executed with no error, the
print(x) passwd="yourpassword", table "customers" now has a primary key
database="mydatabase"

Insert a record in a table Insert multiple rows Get inserted ID


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",
database="mydatabase" database="mydatabase" database="mydatabase"
) ) )
mycursor = mydb.cursor() mycursor = mydb.cursor() mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, sql = "INSERT INTO customers (name, sql = "INSERT INTO customers (name,
address) VALUES (%s, %s)" address) VALUES (%s, %s)" address) VALUES (%s, %s)"
val = ("John", "Highway 21") val = [ val = ("Michelle", "Blue Village")
mycursor.execute(sql, val) ('Peter', 'Lowstreet 4'), mycursor.execute(sql, val)
mydb.commit() ('Amy', 'Apple st 652'), mydb.commit()
print(mycursor.rowcount, "record ('Hannah', 'Mountain 21'), print("1 record inserted, ID:",
inserted.") ('Michael', 'Valley 345'), mycursor.lastrowid)
('Sandy', 'Ocean blvd 2'),
('Betty', 'Green Grass 1'),
('Richard', 'Sky st 331'),
('Susan', 'One way 98'),
('Vicky', 'Yellow Garden 2'),
('Ben', 'Park Lane 38'),
('William', 'Central st 954'),
('Chuck', 'Main Road 989'),
('Viola', 'Sideway 1633')
]
mycursor.executemany(sql, val)
mydb.commit()
print(mycursor.rowcount, "record was
inserted.")

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)

Select with a filter sql = "SELECT * FROM customers host="localhost",


import mysql.connector WHERE address = 'Park Lane 38'" user="myusername",
mydb = mysql.connector.connect( mycursor.execute(sql) passwd="mypassword",
host="localhost", myresult = mycursor.fetchall() database="mydatabase"
user="myusername", for x in myresult: )
passwd="mypassword", print(x) mycursor = mydb.cursor()
database="mydatabase" sql = "SELECT * FROM customers
) Wildcards characters WHERE address Like '%way%'"
mycursor = mydb.cursor() import mysql.connector mycursor.execute(sql)
mydb = mysql.connector.connect( myresult = mycursor.fetchall()
for x in myresult: user="myusername", adr = ("Yellow Garden 2", )
print(x) passwd="mypassword", mycursor.execute(sql, adr)
database="mydatabase" myresult = mycursor.fetchall()
Prevent SQL injection ) for x in myresult:
import mysql.connector mycursor = mydb.cursor() print(x)
mydb = mysql.connector.connect( sql = "SELECT * FROM customers
host="localhost", WHERE address = %s"

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)

Prevent SQL injection Delete an existing table Delete a table if it 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",
database="mydatabase" database="mydatabase" database="mydatabase"
) ) )
mycursor = mydb.cursor() mycursor = mydb.cursor() mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE sql = "DROP TABLE customers" sql = "DROP TABLE IF EXISTS
address = %s" mycursor.execute(sql) customers"
adr = ("Yellow Garden 2", ) #If this page was executed with no error(s), mycursor.execute(sql)
mycursor.execute(sql, adr) you have successfully deleted the #If this page was executed with no error(s),
mydb.commit() "customers" table. you have successfully deleted the
print(mycursor.rowcount, "record(s) "customers" table.
deleted")

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!

Check if a collection exist Insert into collection Return the id field


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'] mydb = myclient['mydatabase'] mydb = myclient['mydatabase']
mycol = mydb["customers"] mycol = mydb["customers"] mycol = mydb["customers"]
print(mydb.list_collection_names()) mydict = { "name": "John", "address": mydict = { "name": "Peter", "address":
"Highway 37" } "Lowstreet 27" }
x = mycol.insert_one(mydict) x = mycol.insert_one(mydict)
print(x) print(x.inserted_id)

Insert multiple documents Insert multiple documents with specified IDs


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"]
mylist = [ mylist = [
{ "name": "Amy", "address": "Apple st 652"}, { "_id": 1, "name": "John", "address": "Highway 37"},
{ "name": "Hannah", "address": "Mountain 21"}, { "_id": 2, "name": "Peter", "address": "Lowstreet 27"},
{ "name": "Michael", "address": "Valley 345"}, { "_id": 3, "name": "Amy", "address": "Apple st 652"},
{ "name": "Sandy", "address": "Ocean blvd 2"}, { "_id": 4, "name": "Hannah", "address": "Mountain 21"},
{ "name": "Betty", "address": "Green Grass 1"}, { "_id": 5, "name": "Michael", "address": "Valley 345"},
{ "name": "Richard", "address": "Sky st 331"}, { "_id": 6, "name": "Sandy", "address": "Ocean blvd 2"},
{ "name": "Susan", "address": "One way 98"}, { "_id": 7, "name": "Betty", "address": "Green Grass 1"},
{ "name": "Vicky", "address": "Yellow Garden 2"}, { "_id": 8, "name": "Richard", "address": "Sky st 331"},
{ "name": "Ben", "address": "Park Lane 38"}, { "_id": 9, "name": "Susan", "address": "One way 98"},
{ "name": "William", "address": "Central st 954"}, { "_id": 10, "name": "Vicky", "address": "Yellow Garden 2"},
{ "name": "Chuck", "address": "Main Road 989"}, { "_id": 11, "name": "Ben", "address": "Park Lane 38"},
{ "name": "Viola", "address": "Sideway 1633"} { "_id": 12, "name": "William", "address": "Central st 954"},
] { "_id": 13, "name": "Chuck", "address": "Main Road 989"},
x = mycol.insert_many(mylist) { "_id": 14, "name": "Viola", "address": "Sideway 1633"}
#print list of the _id values of the inserted documents: ]
print(x.inserted_ids) x = mycol.insert_many(mylist)
#print a list of the _id values of the inserted documents:
print(x.inserted_ids)

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)

Advanced query Filter with regular expressions


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"]
#address greater than S: #address starts with S:
myquery = { "address": {"$gt": "S"} } myquery = { "address": { "$regex": "^S" } }
mydoc = mycol.find(myquery) mydoc = mycol.find(myquery)
for x in mydoc: for x in mydoc:
print(x) 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)

Delete document Delete many documents


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"]
myquery = { "address": "Mountain 21" } myquery = { "address": {"$regex": "^S"} }
mycol.delete_one(myquery) x = mycol.delete_many(myquery)
#print the customers collection after the deletion: print(x.deleted_count, "documents deleted")
for x in mycol.find():
print(x)

Delete all documents in a collection Delete a collection


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.delete_many({}) mycol.drop()
print(x.deleted_count, "documents deleted")

Update a document Update many/all documents


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"]
myquery = { "address": "Valley 345" } myquery = { "address": { "$regex": "^S" } }
newvalues = { "$set": { "address": "Canyon 123" } } newvalues = { "$set": { "name": "Minnie" } }
mycol.update_one(myquery, newvalues) x = mycol.update_many(myquery, newvalues)
#print "customers" after the update: print(x.modified_count, "documents updated.")
for x in mycol.find():
print(x)

Limit the result


import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myresult = mycol.find().limit(5)
#print the result:
for x in myresult:
print(x)

You might also like