Python Tutorial by VADDI As On July 3
Python Tutorial by VADDI As On July 3
Python Tutorial by VADDI As On July 3
Where in other programming languages the indentation in code is for readability only, in Python the indentation is very
important.
Example
if 5 > 2:
print("Five is greater than two!")
Example
if 5 > 2:
print("Five is greater than two!")
Comments
Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a comment:
Example
Comments in Python:
#This is a comment.
print("Hello, World!")
Docstrings
Python uses triple quotes at the beginning and end of the docstring:
Example
"""This is a
multiline docstring."""
print("Hello, World!")
Page 1
Python Variables
Creating Variables
Unlike other programming languages, Python has no command for declaring a variable.
Example
x = 5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type and can even change type after they have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for
Python variables:
Output Variables
The Python print statement is often used to output variables.
Example
x = "awesome"
print("Python is " + x)
You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z = x + y
print(z)
Page 2
For numbers, the + character works as a mathematical operator:
Example
x = 5
y = 10
print(x + y)
If you try to combine a string and a number, Python will give you an error:
Example
x = 5
y = "John"
print(x + y)
Python Numbers
There are three numeric types in Python:
int
float
complex
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Example
Integers:
x = 1
y = 35656222554887711
z = -3255522
Page 3
print(type(x))
print(type(y))
print(type(z))
Float
Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
Example
Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example
Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex
Complex numbers are written with a "j" as the imaginary part:
Example
Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Page 4
Python Casting
Specify a Variable Type
There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-
orientated language, and as such it uses classes to define data types, including its primitive types.
int() - constructs an integer number from an integer literal, a float literal (by rounding down to the previous
whole number) literal, or a string literal (providing the string represents a whole number)
float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string
represents a float or an integer)
str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals
Example
Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Example
Floats:
Example
Strings:
Python Strings
String Literals
String literals in python are surrounded by either single quotation marks, or double quotation marks.
Strings can be output to screen using the print function. For example: print("hello").
Page 5
Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
However, Python does not have a character data type, a single character is simply a string with a length of 1. Square
brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
Example
b = "Hello, World!"
print(b[2:4])
Example
The strip() method removes any whitespace from the beginning or the end:
Example
a = "Hello, World!"
print(len(a))
Example
a = "Hello, World!"
print(a.lower())
Example
a = "Hello, World!"
print(a.upper())
Example
a = "Hello, World!"
print(a.replace("H", "J"))
Page 6
Example
The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
The following example asks for the user's name, then, by using the input() method, the program prints the name to the
screen:
Example
demo_string_input.py
Save this file as demo_string_input.py, and load it through the command line:
Linus
Hello, Linus
Python Operators
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Page 7
Membership operators
Bitwise operators
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
Page 8
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
== Equal x == y
!= Not equal x != y
Page 9
< Less than x<y
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the result is not(x < 5 and x < 10)
true
is not Returns true if both variables are not the same x is not y
object
Page
10
Membership operators are used to test if a sequence is presented in an object:
not in Returns True if a sequence with the specified value is not x not in y
present in the object
<< Zero fill left Shift left by pushing zeros in from the right and let the leftmost bits fall off
shift
>> Signed right Shift right by pushing copies of the leftmost bit in from the left, and let the
shift rightmost bits fall off
Python Lists
Python Collections (Arrays)
There are four collection data types in the Python programming language:
Page
11
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Set is a collection which is unordered and unindexed. No duplicate members.
Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a
particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.
List
A list is a collection which is ordered and changeable. In Python lists are written with square brackets.
Example
Create a List:
Example
Example
Example
Example
Page
12
thislist = list(("apple", "banana", "cherry"))
thislist.remove("banana")
print(thislist)
Example
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
Page
13
Python Tuples
Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.
Example
Create a Tuple:
Example
Example
Example
Example
Page
14
Python Sets
Set
A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
Example
Create a Set:
Note: the set list is unordered, so the items will appear in a random order.
Example
Example
Example
Example
Page
15
Python Dictionaries
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly
brackets, and they have keys and values.
Example
thisdict = {
"apple": "green",
"banana": "yellow",
"cherry": "red"
}
print(thisdict)
Example
thisdict = {
"apple": "green",
"banana": "yellow",
"cherry": "red"
}
thisdict["apple"] = "red"
print(thisdict)
Example
thisdict = dict(apple="green", banana="yellow", cherry="red")
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example
thisdict = dict(apple="green", banana="yellow", cherry="red")
thisdict["damson"] = "purple"
print(thisdict)
Removing Items
Page
16
Removing a dictionary item must be done using the del() function in python:
Example
thisdict = dict(apple="green", banana="yellow", cherry="red")
del(thisdict["banana"])
print(thisdict)
Example
thisdict = dict(apple="green", banana="yellow", cherry="red")
print(len(thisdict))
Python Conditions
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
Example
If statement:
a = 33
b = 200
if b > a: print("b is greater than a")
In this example we use two variables, a and b, which are used as part of the if statement to test whether bis greater
than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to screen that "b is greater than a".
Indentation
Python relies on indentation, using whitespace, to define scope in the code. Other programming languages often use
curly-brackets for this purpose.
Page
17
Example
a = 33
b = 200
if b > a:
print("b is greater than a")
Example
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
Elif
The elif keyword is pythons way of saying "if the previous conditions were not true, then do this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print to screen that
"a and b are equal".
Else
The else keyword catches anything which isn't caught by the preceding conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater to b, so the first condition is not true, also the elif condition is not true, so we go to
the else condition and print to screen that "a is greater than b".
Page
18
Python While Loops
Python Loops
Python has two primitive loop commands:
while loops
for loops
Example
i = 1
while i < 6:
print(i)
i += 1
The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which
we set to 1.
Example
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Page
19
Example
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
This is less like the for keyword in other programming language, and works more like an iterator method as found in
other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Example
The for loop does not require an indexing variable to set beforehand, as the for command itself allows for this.
Example
Page
20
Example
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and
ends at a specified number.
Example
for x in range(6):
print(x)
The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a
parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
Example
The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by
adding a third parameter: range(2, 30, 3):
Example
Recursion
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit
of meaning that you can loop through data to reach a result.
Page
21
The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never
terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion
can be a very efficient and mathematically-elegant approach to programming.
In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use the kvariable as the
data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0 (i.e.
when it is 0).
To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and
modifying it.
Example
Recursion Example
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result
Python Functions
A function is a block of code which only runs when it is called.
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Page
22
Example
def my_function():
print("Hello from a function")
my_function()
Parameters
Information can be passed to functions as parameter.
Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want,
just separate them with a comma.
The following example has a function with one parameter (fname). When the function is called, we pass along a first
name, which is used inside the function to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Return Values
To let a function return a value, use the return statement:
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Page
23
Python Lambda
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
Syntax
lambda arguments : expression
Example
A lambda function that adds 10 to the number passed in as an argument, and print the result:
x = lambda a : a + 10
print(x(5))
Example
A lambda function that multiplies argument a with argument b and print the result:
x = lambda a, b : a * b
print(x(5, 6))
Example
A lambda function that sums argument a, b, and c and print the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown
number:
def myfunc(n):
return lambda a : a * n
Use that function definition to make a function that always doubles the number you send in:
Example
def myfunc(n):
return lambda a : a * n
Page
24
mydoubler = myfunc(2)
print(mydoubler(11))
Or, use the same function definition to make a function that always triples the number you send in:
Example
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
Or, use the same function definition to make both functions, in the same program:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Use lambda functions when an anonymous function is required for a short period of time.
Python Arrays
Arrays
Arrays are used to store multiple values in one single variable:
Example
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
car1 = "Ford";
car2 = "Volvo";
car3 = "BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
Page
25
The solution is an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.
Note: Python does not have built-in support for Arrays, but Python lists can be used instead.
Example
x = cars[0]
Example
cars[0] = "Toyota"
Example
x = len(cars)
Note: The length of an array is always one more than the highest array index.
Example
for x in cars:
print(x)
Page
26
You can use the append() method to add an element to an array.
Example
cars.append("Honda")
Example
cars.pop(1)
You can also use the remove() method to remove an element from the array.
Example
cars.remove("Volvo")
Note: The remove() method only removes the first occurrence of the specified value.
Array Methods
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
Page
27
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
Create a Class
To create a class, use the keyword class:
Example
class MyClass:
x = 5
Create Object
Now we can use the class named myClass to create objects:
Page
28
Example
p1 = MyClass()
print(p1.x)
To understand the meaning of classes we have to understand the built-in __init__() function.
All classes have a function called __init__(), which is always executed when the class is being initiated.
Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the
object is being created:
Example
Create a class named Person, use the __init__() function to assign values for name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Note: The __init__() function is called automatically every time the class is being used to create a new object.
Object Methods
Objects can also contain methods. Methods in objects are functions that belongs to the object.
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Page
29
Note: The self parameter is a reference to the class itself, and is used to access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function
in the class:
Example
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Example
p1.age = 40
Example
del p1.age
Delete Objects
You can delete objects by using the del keyword:
Page
30
Example
del p1
Python Modules
What is a Module?
Consider a module to be the same as a code library.
Create a Module
To create a module just save the code you want in a file with the file extension .py:
Example
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
Note: When using a function from a module, use the syntax: module_name.function_name.
Variables in Module
The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):
Page
31
Example
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
Naming a Module
You can name the module file whatever you like, but it must have the file extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Example
import mymodule as mx
a = mx.person1["age"]
print(a)
Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.
Example
import platform
x = platform.system()
print(x)
Page
32
There is a built-in function to list all the function names (or variable names) in a module. The dir()function:
Example
import platform
x = dir(platform)
print(x)
Note: The dir() function can be used on all modules, also the ones you create yourself.
Example
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
print (person1["age"])
Note: When importing using the from keyword, do not use the module name when referring to elements in the module.
Example: person1.age, not mymodule.person1.age
Python Datetime
Python Dates
A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date
objects.
Page
33
Example
import datetime
x = datetime.datetime.now()
print(x)
Date Output
When we execute the code from the example above the result will be:
2018-07-27 12:47:18.092211
The date contains year, month, day, hour, minute, second, and microsecond.
The datetime module has many methods to return information about the date object.
Here are a few examples, you will learn more about them later in this chapter:
Example
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
The datetime() class requires three parameters to create a date: year, month, day.
Example
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
The datetime() class also takes parameters for time and timezone (hour, minute, second, microsecond, tzone), but they
are optional, and has a default value of 0, (None for timezone).
Page
34
The datetime object has a method for formatting date objects into readable strings.
The method is called strftime(), and takes one parameter, format, to specify the format of the returned string:
Example
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
%H Hour 00-23 17
%I Hour 00-12 05
Page
35
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%Z Timezone CST
%% A % character %
Python JSON
JSON is a syntax for storing and exchanging data.
Page
36
JSON in Python
Python has a built-in package called json, which can be use to work with JSON data.
Example
import json
Example
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
Example
import json
Page
37
# the result is a JSON string:
print(y)
You can convert Python objects of the following types, into JSON strings:
dict
list
tuple
string
int
float
True
False
None
Example
Convert Python objects into JSON strings, and print the values:
import json
When you convert from Python to JSON, Python objects are converted into the JSON (JavaScript) equivalent:
Python JSON
dict Object
list Array
tuple Array
str String
int Number
Page
38
float Number
True true
False false
None null
Example
import json
x = {
"name": "John",
"age": 62,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
print(json.dumps(x))
The json.dumps() method has parameters to make it easier to read the result:
Example
json.dumps(x, indent=4)
You can also define the separators, default value is (", ", ": "), which means using a comma and a space to separate each
object, and a colon and a space to separate keys from values:
Page
39
Example
Example
Use the sort_keys parameter to specify if the result should be sorted or not:
Python PIP
What is PIP?
PIP is a package manager for Python packages, or modules if you like.
Note: If you have Python version 3.4 or later, PIP is included by default.
What is a Package?
A package contains all the files you need for a module.
Modules are Python code libraries you can include in your project.
Example
Install PIP
If you do not have PIP installed, you can download and install it from this page: https://pypi.org/project/pip/
Download a Package
Page
40
Downloading a package is very easy.
Open the command line interface and tell PIP to download the package you want.
Navigate your command line to the location of Python's script directory, and type the following:
Example
Using a Package
Once the package is installed, it is ready to use.
Example
import camelcase
c = camelcase.CamelCase()
print(c.hump(txt))
Find Packages
Find more packages at https://pypi.org/.
Python has several functions for creating, reading, updating, and deleting files.
File Handling
The key function for working with files in Python is the open() function.
Page
41
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure the file exist, or else you will get an error.
demofile.txt
The open() function returns a file object, which has a read() method for reading the content of the file:
Example
f = open("demofile.txt", "r")
print(f.read())
Page
42
Example
f = open("demofile.txt", "r")
print(f.read(5))
Read Lines
You can return one line by using the readline() method:
Example
f = open("demofile.txt", "r")
print(f.readline())
By calling readline() two times, you can read the two first lines:
Example
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
By looping through the lines of the file, you can read the whole file, line by line:
Example
f = open("demofile.txt", "r")
for x in f:
print(x)
Page
43
Example
f = open("demofile.txt", "a")
f.write("Now the file has one more line!")
Example
f = open("demofile.txt", "w")
f.write("Woops! I have deleted the content!")
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example
f = open("myfile.txt", "x")
Example
f = open("myfile.txt", "w")
Page
44
Example
import os
os.remove("demofile.txt")
Example
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exists")
Delete Folder
To delete an entire folder, use the os.rmdir() method:
Example
import os
os.rmdir("myfolder")
Page
45
Python Built in Functions
Python has a set of built-in functions.
Function Description
ascii() Returns a readable version of an object. Replaces none-ascii characters with escape
character
delattr() Deletes the specified attribute (property or method) from the specified object
Page
46
dict() Returns a dictionary (Array)
divmod() Returns the quotient and the remainder when argument1 is divided by argument2
hasattr() Returns True if the specified object has the specified attribute (property/method)
Page
47
input() Allowing user input
map() Returns the specified iterator with the specified function applied to each item
Page
48
pow() Returns the value of x to the power of y
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
Page
49
zip() Returns an iterator, from two or more iterators
Note: All string methods returns new values. They do not change the original string.
Method Description
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where it was found
index() Searches the string for a specified value and returns the position of where it was found
Page
50
isalpha() Returns True if all characters in the string are in the alphabet
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
Page
51
rfind() Searches the string for a specified value and returns the last position of where it was
found
rindex() Searches the string for a specified value and returns the last position of where it was
found
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
zfill() Fills the string with a specified number of 0 values at the beginning
Note: All string methods returns new values. They do not change the original string.
Method Description
Page
52
append() Adds an element at the end of the list
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
Page
53
Python MySQL
Python can be used in database applications.
MySQL Database
To be able experiment with the code examples in this tutorial, you should have MySQL installed on your computer.
Navigate your command line to the location of PIP, and type the following:
demo_mysql_test.py:
import mysql.connector
If the above code was executed with no errors, "MySQL Connector" is installed and ready to be used.
Page
54
Create Connection
Start by creating a connection to the database.
demo_mysql_connection.py:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
print(mydb)
Now you can start querying the database using SQL statements.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
If the above code was executed with no errors, you have successfully created a database.
Example
Page
55
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
Or you can try to access the database when making the connection:
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
Make sure you define the name of the database when you create the connection
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
Page
56
If the above code was executed with no errors, you have now successfully created a table.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW TABLES")
for x in mycursor:
print(x)
Primary Key
When creating a table, you should also create a column with a unique key for each record.
We use the statement "INT AUTO_INCREMENT PRIMARY KEY" which will insert a unique number for each record. Starting
at 1, and increased by one for each record.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql = "CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255),
address VARCHAR(255))")
Page
57
If the table already exists, use the ALTER TABLE keyword:
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mydb.commit()
Important!: Notice the statement: mydb.commit(). It is required to make the changes, otherwise no changes are made
to the table.
Page
58
To insert multiple rows into a table, use the executemany() method.
The second parameter of the executemany() method is a list of tuples, containing the data you want to insert:
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.executemany(sql, val)
mydb.commit()
Get Inserted ID
You can get the id of the row you just inserted by asking the cursor object.
Note: If you insert more that one row, the id of the last inserted row is returned.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
Page
59
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mydb.commit()
Example
Select all records from the "customers" table, and display the result:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Note: We use the fetchall() method, which fetches all rows from the last executed statement.
Selecting Columns
To select only some of the columns in a table, use the "SELECT" statement followed by the column name(s):
Example
Page
60
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
myresult = mycursor.fetchall()
for x in myresult:
print(x)
The fetchone() method will return the first row of the result:
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
myresult = mycursor.fetchone()
print(myresult)
Example
Page
61
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Wildcard Characters
You can also select the records that starts, includes, or ends with a given letter or phrase.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
This is to prevent SQL injections, which is a common web hacking technique to destroy or misuse your database.
Page
62
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql, adr)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
The ORDER BY keyword sorts the result ascending by default. To sort the result in descending order, use the DESC
keyword.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql)
myresult = mycursor.fetchall()
Page
63
for x in myresult:
print(x)
ORDER BY DESC
Use the DESC keyword to sort the result in a descending order.
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql)
Page
64
mydb.commit()
Important!: Notice the statement: mydb.commit(). It is required to make the changes, otherwise no changes are made
to the table.
Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which record(s) that should be deleted.
If you omit the WHERE clause, all records will be deleted!
This is to prevent SQL injections, which is a common web hacking technique to destroy or misuse your database.
The mysql.connector module uses the placeholder %s to escape values in the delete statement:
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql, adr)
mydb.commit()
Example
Page
65
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql)
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql)
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
Page
66
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
mycursor.execute(sql)
mydb.commit()
Important!: Notice the statement: mydb.commit(). It is required to make the changes, otherwise no changes are made
to the table.
Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies which record or records that should be
updated. If you omit the WHERE clause, all records will be updated!
This is to prevent SQL injections, which is a common web hacking technique to destroy or misuse your database.
The mysql.connector module uses the placeholder %s to escape values in the delete statement:
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql, val)
mydb.commit()
Page
67
Python MySQL Limit
Limit the Result
You can limit the number of records returned from the query, by using the "LIMIT" statement:
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Page
68
Python MySQL Join
Join Two or More Tables
You can combine rows from two or more tables, based on a related column between them, by using a JOIN statement.
users
{ id: 1, name: 'John', fav: 154},
{ id: 2, name: 'Peter', fav: 154},
{ id: 3, name: 'Amy', fav: 155},
{ id: 4, name: 'Hannah', fav:},
{ id: 5, name: 'Michael', fav:}
products
{ id: 154, name: 'Chocolate Heaven' },
{ id: 155, name: 'Tasty Lemons' },
{ id: 156, name: 'Vanilla Dreams' }
These two tables can be combined by using users' fav field and products' id field.
Example
Join users and products to see the name of the users favorite product:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
INNER JOIN products ON users.fav = products.id"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Note: You can use JOIN instead of INNER JOIN. They will both give you the same result.
Page
69
LEFT JOIN
In the example above, Hannah, and Michael were excluded from the result, that is because INNER JOIN only shows the
records where there is a match.
If you want to show all users, even if they do not have a favorite product, use the LEFT JOIN statement:
Example
sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
LEFT JOIN products ON users.fav = products.id"
RIGHT JOIN
If you want to return all products, and the users who have them as their favorite, even if no user have them as their
favorite, use the RIGHT JOIN statement:
Example
Select all products, and the user(s) who have them as their favorite:
sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
RIGHT JOIN products ON users.fav = products.id"
Note: Hannah and Michael, who have no favorite product, are not included in the result.
Page
70