Python Tutorial
Python Tutorial
Aniel Bhulai
Vrije Universiteit Amsterdam
A short introduction to Python by Aniel Bhulai 2
Contents
1. Introduction .........................................................................................................................7
2. Overview..............................................................................................................................8
3. Reserved keywords ..............................................................................................................9
4. Operators...........................................................................................................................10
4.1. Arithmetic operators ...................................................................................................10
4.2. Assignment operators .................................................................................................11
4.3. Comparison (relational) operators ..............................................................................12
4.4. Logical operators.........................................................................................................12
4.5. Identity operators .......................................................................................................13
4.6. Bitwise operators ........................................................................................................13
4.7. Membership operators ...............................................................................................14
5. Strings ................................................................................................................................15
6. Escape characters ..............................................................................................................16
7. Numbers ............................................................................................................................17
7.1. Numerical data types ..................................................................................................17
7.2. Number type conversion .............................................................................................18
7.3. Mathematical functions ..............................................................................................19
7.4. Trigonometric functions ..............................................................................................20
7.5. Random number functions ..........................................................................................21
8. Data types ..........................................................................................................................22
9. Variables ............................................................................................................................23
10. Lists....................................................................................................................................24
10.1. Creating lists ............................................................................................................24
10.2. Accessing values in lists ...........................................................................................24
10.3. Updating lists...........................................................................................................25
10.4. Deleting values from lists.........................................................................................25
10.5. Basic list operations .................................................................................................26
10.6. Built-in list functions ................................................................................................26
10.7. Built-in list methods ................................................................................................27
A short introduction to Python by Aniel Bhulai 3
11. Tuples ................................................................................................................................28
11.1. Creating tuples ........................................................................................................28
11.2. Accessing values in tuples ........................................................................................28
11.3. Updating tuples .......................................................................................................29
11.4. Deleting values from tuples .....................................................................................29
11.5. Basic tuple operations .............................................................................................30
11.6. Built-in tuple functions ............................................................................................30
12. Dictionary ..........................................................................................................................31
12.1. Creating dictionaries................................................................................................31
12.2. Accessing values in dictionaries ...............................................................................31
12.3. Updating dictionaries ..............................................................................................32
12.4. Deleting dictionaries ................................................................................................32
12.5. Built-in dictionary functions .....................................................................................33
12.6. Built-in dictionary methods .....................................................................................34
13. Decision-making.................................................................................................................35
13.1. if-statement ............................................................................................................35
13.2. if…else-statement....................................................................................................36
13.3. if…elif…else-statement ............................................................................................37
13.4. Nested if-statement ................................................................................................38
14. Loops .................................................................................................................................39
14.1. While-loop...............................................................................................................39
14.2. For-loop...................................................................................................................40
14.3. Nested loop .............................................................................................................42
14.4. Loop control statements..........................................................................................42
14.4.1. Break statement ...............................................................................................42
14.4.2. Continue statement..........................................................................................43
14.4.3. Pass statement .................................................................................................43
15. Functions ...........................................................................................................................45
15.1. Creating a function ..................................................................................................45
In the interactive mode, the Python script can be executed directly to the Python prompt
without passing the script file to the interpreter. The interactive mode is useful when dealing
with small pieces of code as you can type and execute them directly at the Python prompt.
In the script mode, the Python script file is stored with the .py extension. The interpreter is then
used to execute the contents of the script file. The name of the script file is passed to the
interpreter to be executed. The script mode is useful when the code is more than 4 lines and
when you want to use the code in future. Example 1 shows how to run the script file
[Link] on a UNIX/LINUX system.
Example
python [Link]
Example
10 + 2 = 12
In Example 2 we see two operands (i.e., 10 and 2) and a plus symbol (+) which is the operator.
The plus symbol performs the addition. The output of the operation is 12.
• Arithmetic operators
• Assignment operators
• Comparison (relational) operators
• Logical operators
• Identity operators
• Bitwise operators
• Membership operators
+ Addition 10 + 2 = 12 This operator adds the values on either side of the operator.
This operator subtracts the right side value from the left side
- Subtraction 6–3=3
value.
This operator multiplies the values on both sides of the
* Multiplication 8 * 2 = 16
operator.
This operator divides the left side value with the right side
/ Division 4/2=2
value.
This operator returns the remainder by dividing the left side
% Modulus 7%2=1
value with right side value.
This operator calculates the sum of the value of the right side
= Equal 11 + 2 = 13
operand and the left side operand.
Example
Example 3: Strings
Example 3 shows a few examples of strings. We can take a subset of strings using the slice
operator ( [ ] and [:] ) with index numbers. The plus (+) sign is the string concatenation operator
and the asterisk (*) is the repetition operator. Table 9 shows the output of Example 3.
Output example
Study algorithms.
S
y algo
y algorithms.
Study [Link] algorithms.
Study [Link]
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\M-\C-x Meta-Control-x
\n 0x0a Newline
Octal notation,
\nnn
n is in the range 0-7
\r 0x0d Carriage return
\s 0x20 Space
\t 0x09 Tab
\x Character x
Hexadecimal notation,
\xnn
n is in the range 0-9, a-f, or A-F
Table 10: Escape characters in Python
Example
var1 = 20
var2 = 7.3
The reference to a number object can be deleted by using the del statement, see Example 5.
Example
del var1
del var1, var2
Mathematical Output
Description Example
function example
The absolute value of 𝑥: the positive abs(-30) 30
abs(𝑥)
distance between 𝑥 and zero. abs(202.19) 202.19
The ceiling of 𝑥: the smallest integer [Link](-30.6) -30.0
ceil(𝑥)
not less than 𝑥. [Link](20.12) 21
[Link](-30) 30.0
fabs(𝑥) The absolute value of 𝑥.
[Link](202.19) 202.19
The floor of 𝑥: the largest integer not [Link](-30.6) -31.0
floor(𝑥)
greater than 𝑥. [Link](20.12) 20.0
round(10.23167,
𝑥 rounded to 𝑛 digits from the decimal 2) 10.23
round(𝑥 [, 𝑛])
point. round(10.23167, 10.2317
4)
Trigonometric Output
Description Example
functions example
This function returns the arc cosine of 𝑥
acos(𝑥) [Link](0) 1.57079632679
in radians.
This function returns the arc sine of 𝑥 in
asin(𝑥) [Link](0) 0.0
radians.
This function returns the arc tangent of 𝑥
atan(𝑥) [Link](0) 0.0
in radians.
This function returns atan(𝑦/𝑥) in
atan2(𝑦, 𝑥) math.atan2(5, 5) 0.785398163397
radians.
This function returns the cosine of 𝑥 in
cos(𝑥) [Link](0) 1.0
radians.
This function converts angle 𝑥 from [Link](0) 0.0
degrees(𝑥)
radians to degrees. [Link]([Link]) 180.0
This function returns the Euclidean norm,
hypot(𝑥, 𝑦) [Link](0, 3) 3.0
sqrt(𝑥 ∗ 𝑥 + 𝑦 ∗ 𝑦).
This function returns the sine of 𝑥 in
sin(𝑥) [Link](0) 0.0
radians.
This function returns the tangent of 𝑥 in
tan(𝑥) [Link](0) 0.0
radians.
This function converts angle 𝑥 from
radians(𝑥) [Link](0) 0.0
degrees to radians.
Table 14: Trigonometric functions
Formally, we can say that variables are reserved memory locations to store values (e.g., a letter
or a number). When we create a variable we reserve some space in memory. These variables
hold values temporarily during program execution. Based on the data type of a variable, the
Python interpreter allocates memory and decides what can be stored in the reserved memory.
Different data types like integers, decimals, characters, etc. can be stored in these variables.
Variables do not need to be declared in Python as the Python interpreter determines what type
of data is stored. To assign values to a variable we use an equal sign ( = ) in the Python
programming language. The equal sign assigns the value of right side operand to left side
operand. The left side operand is the name of the variable and the right side operand is the
assigned value.
Example
To create variable names in Python we should comply with the following rules:
• Variable names must begin with a letter or underscore.
• Variable names are case-sensitive.
• A variable name does not contain spaces.
• A variable name can only contain alphanumeric characters (i.e., a-z, A-Z, and 0-9) and
underscore ( _ ).
• Reserved keywords cannot be used as variable names.
Example
Example
Output example
list1[0]= John
list2[2]= 500
list3[1:3]= [10, 'Tina']
Example
Output example
Example
Output example
Output
List functions Description Example
example
This function returns the list = [1, 2, 3]
len(list) 3
number of elements in the list. print (len(list))
This function returns the list = [10, 280, 38]
max(list) 280
elements from the list with print (max(list))
Output
List methods Description Example
example
list1 = [1, 2]
This method appends an object
[Link](obj) [Link](3)
obj to list. [1, 2, 3]
print (list1)
This method returns count of
list1 = [1, 2, 1, 1]
[Link](obj) how many times obj occurs in 3
print ([Link](1))
list.
list1 = [1, 2]
This method appends the list2 = [3, 4]
[Link](seq) [1, 2, 3, 4]
contents of seq to list. [Link](list2)
print (list1)
This method returns the lowest list1 = ['Zara', 'John', 'Joe']
[Link](obj) 1
index in list that obj appears. print ([Link]('John'))
list1 = ['a', 'b', 'd', 'e']
This method inserts object obj
[Link](index, obj) [Link](2, 'c') ['a', 'b', 'c', 'd', 'e']
into list at offset index.
print (list1)
This method removes and list1 = ['a', 'b', 'd', 'e']
e
[Link](obj=list[-1]) returns last object or obj from print ([Link]())
d
list. print ([Link](2))
list1 = ['a', 'b', 'c', 'd', 'e']
This method removes object obj
[Link](obj) [Link]('c') ['a', 'b', 'd', 'e']
from list.
print (list1)
list1 = ['a', 'b', 'c', 'd', 'e']
This method reverses objects of
[Link]() [Link]() ['e', 'd', 'c', 'b', 'a']
list in place.
print (list1)
list1 = [34, 23, 'd', 'a', 'j']
This method sorts objects of list;
[Link]([func]) [Link]() [23, 34, 'a', 'd', 'j']
use compare func if given.
print (list1)
Table 21: Built-in list methods in Python
Like in lists, in tuples each element of a sequence is assigned a number, i.e., the index number
or the position of the element. The first index number is zero, the second index number is one,
the third index number is two, and so forth. We can apply operations like indexing, adding,
multiplying, slicing, and checking for membership on tuples and other sequence types (e.g.,
lists).
Example
Example
tuple1[0]= John
tuple2[2]= 500
tuple3[1:3]= (10, 'Tina')
Example
print (tuple3)
Output example
Example
del tuple1
Output
Tuple functions Description Example
example
This function returns the
tuple = (1, 2, 3)
len(tuple) number of elements in the 3
print (len(tuple))
tuple.
This function returns the
tuple = (10, 280, 38)
max(tuple) elements from the tuple with 280
print (max(tuple))
maximum value.
This function returns the
tuple = (10, 280, 38)
min(tuple) elements from the tuple with 10
print (min(tuple))
minimum value.
list = ['x', 1 ,'r', 10]
This function converts a list into
tuple(seq) tuple = tuple(list) ('x', 1, 'r', 10)
tuple.
print (tuple)
Table 25: Built-in tuple functions in Python
Example
Example
Output example
Name: Catherine
Age: 18
Gender: Female
Example 17 shows how you can update an existing entry and how you can add an entry in a
dictionary.
Example
Output example
Name: Catherine
Age: 20
Gender: Female
Residence: Amsterdam
Example
Dictionary Output
Description Example
functions example
This function returns the dict = {'Name': 'Jean',
len(dict) number of items in the 'Age': 17} 2
dictionary. print (len(dict))
This function produces a dict = {'Name': 'Jean',
{'Name': 'Jean', 'Age':
str(dict) printable string representation 'Age': 17}
17}
of a dictionary. print (str(dict))
This function returns the type of
the passed variable. If the dict = {'Name': 'Jean',
type(variable) passed variable is dictionary 'Age': 17} <type 'dict'>
then it would return a dictionary print (type(dict))
type.
Table 28: Built-in dictionary functions in Python
Dictionary Output
Description Example
methods example
dict = {'Name': 'Tina', 'Age':
This method removes all 18}
[Link]() {}
elements of dictionary dict. [Link]()
print (dict)
dict1 = {'Name': 'Tina', 'Age':
This method returns a shallow 18} {'Name': 'Tina', 'Age':
[Link]()
copy of dictionary dict. dict2 = [Link]() 18, }
print (str(dict2))
This method creates a new
seq = ('Name', 'Age')
[Link](seq[, dictionary with keys from seq {'Name': 20, 'Age':
dict = [Link](seq, 20)
value]) and values set to value if 20}
print (str(dict))
provided.
dict = {'Name': 'Tina', 'Age':
This method returns a value
18}
[Link](key, for the given key. Default is Tina
print ([Link]('Name'))
default=none) the value that is returned in Does not exist
print ([Link]('Gender', "Does
case the key does not exist.
not exist"))
dict = {'Name': 'Tina', 'Age':
This method returns a view of dict_items([('Name',
[Link]() 18}
dict's (key, value) tuple pairs 'Tina'), ('Age', 18)])
print ([Link]())
This method returns a view of dict = {'Name': 'Tina', 'Age':
dict_keys(['Name',
[Link]() all available keys in the 18}
'Age'])
dictionary. print ([Link]())
dict = {'Name': 'Tina', 'Age': Tina
18}
None
This method is similar to get(), print (dict. setdefault ('Name',
[Link](key,
but will set dict[key]=default if "None"))
default=none)
key is not already in dict. print (dict. setdefault New dict: {'Name':
('Gender', "None")) 'Tina', 'Age': 18,
print ("New dict: %s" % dict) 'Gender': 'None'}
dict1 = {'Name': 'Tina', 'Age':
This method adds dictionary 18} {'Name': 'Tina', 'Age':
[Link](dict2) dict2's key-values pairs to dict2 = {'Gender': 'female'} 18, 'Gender':
dict1. [Link](dict2) 'female'}
print (dict1)
This method returns a view of dict = {'Name': 'Tina', 'Age':
dict_values(['Tina',
[Link]() all the values in a given 18}
18])
dictionary. print ([Link]())
Table 29: Built-in dictionary methods in Python
Flowcharts are very helpful in understanding and recognizing decision making structures. The
following decision-making statements are available in Python.
• if-statements
• if…else statements
• if...elif…else statements
• nested if-statements
13.1. if-statement
If-statements consists of a Boolean expression which evaluates to TRUE or FALSE (see Figure 1).
If the Boolean expression evaluates to TRUE, then the block of statement(s) inside the if-
statement is executed. If the Boolean expression evaluates to FALSE, then the first set of code
after the end of the if-statement(s) is executed.
Example
13.2. if…else-statement
In the if…else-statement, the if-statement is followed by an optional else-statement. The
if…else-statement contains a Boolean expression (see Figure 2) which if evaluates to FALSE, the
else-statement is executed.
Example
𝑥=1
if 𝑥 > 5: # Boolean evaluates to TRUE
print("𝑥 is greater than 5")
else: # Boolean evaluates to FALSE
print("𝑥 is less than 5")
13.3. if…elif…else-statement
To check multiple expressions we use the if…elif…else-statement. Elif is short for else if. It is also
called the chained conditional statement (see Figure 3). The condition of the next elif-statement
is checked if the condition for the if-statement is FALSE. If the condition of the next elif-
statement is FALSE, then the condition of the next elif-statement is checked and so on. If all the
conditions are FALSE, the else-statement is executed. The if…elif…else-statement can have only
one else-statement and multiple elif-statements. Note that only one elif statement is executed
according to the condition.
Example
𝑥=1
𝑦=5
if 𝑥 > 𝑦:
print("𝑥 is greater than 𝑦")
elif 𝑥 < 𝑦:
print("𝑥 is less than 𝑦")
else:
print("𝑥 is equal to 𝑦")
Example 22 shows a nesting code in Python in which the condition of the elif-statement is
evaluated two times to TRUE before the program quits.
Example
𝑥 = 10
if 𝑥 < 11:
print("𝑥 is less than 11")
if 𝑥 == 5:
print("𝑥 is 5")
elif 𝑥 > 5:
print("𝑥 is greater than 5")
elif 𝑥 < 5:
print("𝑥 is less than 5")
else:
print("Cannot guess 𝑥")
print("Leaving program")
14.1. While-loop
The while-loop is the simplest form of a programming loop. The statements in a while-loop are
repeated as long as a given condition is TRUE (see Figure 4).
Example 23 shows loop created with the while-loop. Note that 𝑥 is incremented with one after
every iteration, or else the loop will continue forever.
𝑥=1
while 𝑥 < 5:
print("Iteration:", 𝑥)
𝑥 = 𝑥+1
Output example
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
14.2. For-loop
The for-loop is used when we want to repeat a piece of code ‘n’ times (see Figure 5) or when
we want to iterate over a sequence (i.e., a list, a tuple or a string).
Example
Output example
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Example
Output example
apple
banana
pineapple
Example
Output example
1 * 1 = 1
1 * 2 = 2
2 * 1 = 2
2 * 2 = 4
Example
apple
Example
Output example
apple
pineapple
Example
P
y
t
pass block
h
o
n
Example
def my_function():
print("Hello World")
Example
def my_function():
print("Hello World")
my_function()
def my_function(name):
print("Hello " + name)
my_function("John")
my_function("Catherine")
Example 33 shows how to use a default parameter value in a Python function. When the
function is called without a parameter, the default value is used.
Example
my_function("John")
my_function("Catherine")
my_function()
Example
avg = average(2, 6)
# We can print avg outside the function
# because it is returned by the function
print("Outside: Average is: ", avg)
Example
def my_function(name):
print("Hello " + name)
my_function("John")
Example
def greeting(name):
print("Hello " + name)
Example
import my_module
my_module.greeting("John")
def greeting(name):
print("Hello " + name)
def gb(name):
print("Goodbye " + name)
To import only the gb function from the module my_module, we use the syntax from
module_name import name (see Example 39).
Example
gb("John")
Note that when import specific attributes from a module using the from keyword we do not use
the module name when we refer to elements in the module, e.g., not
my_module.gb("John"), but gb("John").
Example
person1 = {
"Name": "Catherine",
"Age": "24",
"Residence": "Amsterdam"
}
We can access the person1 dictionary by importing the module named my_module (see
Example 41).
import my_module
country = my_module.person1["Residence"]
print(country)
Example
import my_module as MM
[Link]("John")
Example
import math
list_of_names = dir(math)
print(list_of_names)
Example
import time
ticks = [Link]()
print ("Number of ticks:", ticks)
Output example
Another way to work with time is using Python’s datetime module (see Example 45). The
method strftime() is used to format date objects into readable strings. This method takes one
parameter, format, to specify the format of the returned string. Table 40 shows a reference of
all the legal format codes for the strftime() method.
Example
current = [Link]()
print("Current date and time: ", current)
print("Today's date is: ", [Link]("%Y-%m-%d"))
print("Year: ", [Link])
print("Month: ", [Link])
print("Day: ", [Link])
We can store the data in variables while a program runs. But this data get lost if we terminate
the program. If we want to keep the data after the termination of the program, we have to
store the data in a file. The print function converts the expressions you pass into a string and
writes the result to standard output ().
Example
Output example
Hello world
The input() function interpret the user’s input. If the user, e.g., puts in an integer value, the
input function returns this integer value. If the user, on the other hand, inputs a list, the
function will return a list. A prompt is displayed to enter the string.
Example
Example 47: The use of input() function to read from standard input
Output example
Mode Description
This mode opens a file for writing only. It overwrites the file if the file exists. If the
w
file does not exist, it creates a new file for writing.
This mode opens a file for writing only in binary format. It overwrites the file if the
wb
file exists. If the file does not exist, it creates a new file for writing in binary format.
This mode opens a file for both writing and reading. It overwrites the file if the file
w+
exists. If the file does not exist, it creates a new file for writing and reading.
This mode opens a file for both writing and reading in binary format. It overwrites
wb+ the file if the file exists. If the file does not exist, it creates a new file for writing and
reading in binary format.
This mode opens a file for appending (pointer is at the end of the file). If the file
a
does not exist, it creates a new file for writing.
This mode opens a file for appending in binary format (pointer is at the end of the
ab
file). If the file does not exist, it creates a new file for writing in binary format.
This mode opens a file for both appending and reading (pointer is at the end of the
a+
file). If the file does not exist, it creates a new file for reading and writing.
This mode opens a file for both appending and reading in binary format (pointer is at
ab+ the end of the file). If the file does not exist, it creates a new file for reading and
writing in binary format.
We can get various information related to a file once the file is open by using attributes related
to the file object. Table 44 shows the attributes which can be used with the file object.
Mode Description
[Link] This attribute returns TRUE if the file is closed and FALSE otherwise.
[Link] This attribute returns the access mode with which file was opened.
Example
Example 48: Opening a file and the use of the related attributes
Output example
Example
Example
Example
Example
Example
Example
Example 55 shows how we can overwrite an existing file. The write mode ("w")overwrites any
existing content.
Example
Example 56 shows how a file named, [Link], is created if the file does not exist.
Example
Example
import os
rename(src, dst) This method renames the file or directory src to dst. [Link]("tut", "tutorial")
Python ([Link]
Trademarks
Python and PyCon are trademarks or registered trademarks of the Python Software
Foundation.
Licenses
Python, its standard libraries, and Jython, are distributed under the Python License. The
intellectual property rights behind Python and Jython are held and managed by the Python
Software Foundation.
The licenses, trademarks, and copyrights for other implementations of Python (such as
IronPython, Stackless Python, and PyPy) may vary and are managed by their respective
owners.