Python Tutorial
(Codes)
Mustafa GERMEC, PhD
TABLE OF CONTENTS
PYTHON TUTORIAL
1 Introduction to Python 4
2 Strings in Python 15
3 Lists in Python 24
4 Tuples in Python 37
5 Sets in Python 46
6 Dictionaries in Python 55
7 Conditions in Python 64
8 Loops in Python 73
9 Functions in Python 84
10 Exception Handling in Python 98
11 Built-in Functions in Python 108
12 Classes and Objects in Python 143
13 Reading Files in Python 158
14 Writing Files in Python 166
15 String Operators and Functions in Python 176
16 Arrays in Python 190
17 Lambda Functions in Python 200
18 Math Module Functions in Python 206
19 List Comprehension in Python 227
20 Decorators in Python 235
21 Generators in Python 249
To my family…
5.06.2022 15:57 01. introduction_python - Jupyter Notebook
Python Tutorial
Created by Mustafa Germec, PhD
1. Introduction to Python
First code
In [4]:
1 import handcalcs.render
In [2]:
1 # First python output with 'Print' functions
2 print('Hello World!')
3 print('Hi, Python!')
Hello World!
Hi, Python!
Version control
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 1/11
5.06.2022 15:57 01. introduction_python - Jupyter Notebook
In [10]:
1 # Python version check
2 import sys
3 print(sys.version) # version control
4 print(sys.winver) # [Windows only] version number of the Python DLL
5 print(sys.gettrace) # get the global debug tracing function
6 print(sys.argv) # keeps the parameters used while running the program we wrote in a list.
7
3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)]
3.10
<built-in function gettrace>
['c:\\Users\\test\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\ipykernel_laun
cher.py', '--ip=127.0.0.1', '--stdin=9008', '--control=9006', '--hb=9005', '--Session.signature_scheme="hm
ac-sha256"', '--Session.key=b"ca6e4e4e-b431-4942-98fd-61b49a098170"', '--shell=9007', '--transport="t
cp"', '--iopub=9009', '--f=c:\\Users\\test\\AppData\\Roaming\\jupyter\\runtime\\kernel-17668h2JS6UX
2d6li.json']
help() function
In [11]:
1 # The Python help function is used to display the documentation of modules, functions, classes, keywords, etc.
2 help(sys) # here the module name is 'sys'
Help on built-in module sys:
NAME
sys
MODULE REFERENCE
https://docs.python.org/3.10/library/sys.html (https://docs.python.org/3.10/library/sys.html)
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.
DESCRIPTION
This module provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
Dynamic objects:
Comment
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 2/11
5.06.2022 15:57 01. introduction_python - Jupyter Notebook
In [12]:
1 # This is a comment, and to write a comment, '#' symbol is used.
2 print('Hello World!') # This line prints a string.
3
4 # Print 'Hello'
5 print('Hello')
Hello World!
Hello
Errors
In [13]:
1 # Print string as error message
2 frint('Hello, World!')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_13804/1191913539.py in <module>
1 # Print string as error message
----> 2 frint('Hello, World!')
NameError: name 'frint' is not defined
In [14]:
1 # Built-in error message
2 print('Hello, World!)
File "C:\Users\test\AppData\Local\Temp/ipykernel_13804/974508531.py", line 2
print('Hello, World!)
SyntaxError: unterminated string literal (detected at line 2)
In [15]:
1 # Print both string and error to see the running order
2 print('This string is printed')
3 frint('This gives an error message')
4 print('This string will not be printed')
This string is printed
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_13804/3194197137.py in <module>
1 # Print both string and error to see the running order
2 print('This string is printed')
----> 3 frint('This gives an error message')
4 print('This string will not be printed')
NameError: name 'frint' is not defined
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 3/11
5.06.2022 15:57 01. introduction_python - Jupyter Notebook
Basic data types in Python
In [27]:
1 # String
2 print("Hello, World!")
3 # Integer
4 print(12)
5 # Float
6 print(3.14)
7 # Boolean
8 print(True)
9 print(False)
10 print(bool(1)) # Output = True
11 print(bool(0)) # Output = False
12
Hello, World!
12
3.14
True
False
True
False
type() function
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 4/11
5.06.2022 15:57 01. introduction_python - Jupyter Notebook
In [29]:
1 # String
2 print(type('Hello, World!'))
3
4 # Integer
5 print(type(15))
6 print(type(-24))
7 print(type(0))
8 print(type(1))
9
10 # Float
11 print(type(3.14))
12 print(type(0.5))
13 print(type(1.0))
14 print(type(-5.0))
15
16 # Boolean
17 print(type(True))
18 print(type(False))
<class 'str'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'float'>
<class 'float'>
<class 'float'>
<class 'float'>
<class 'bool'>
<class 'bool'>
In [25]:
1 # to obtain the information about 'interger' and 'float'
2 print(sys.int_info)
3 print() # to add a space between two outputs, use 'print()' function
4 print(sys.float_info)
sys.int_info(bits_per_digit=30, sizeof_digit=4)
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585
072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-
16, radix=2, rounds=1)
Converting an abject type to another object type
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 5/11
5.06.2022 15:57 01. introduction_python - Jupyter Notebook
In [35]:
1 # Let's convert the integer number 6 to a string and a float
2
3 number = 6
4
5 print(str(number))
6 print(float(number))
7 print(type(number))
8 print(type(str(number)))
9 print(type(float(number)))
10 str(number)
6.0
<class 'int'>
<class 'str'>
<class 'float'>
Out[35]:
'6'
In [37]:
1 # Let's conver the float number 3.14 to a string and an integer
2
3 number = 3.14
4
5 print(str(number))
6 print(int(number))
7 print(type(number))
8 print(type(str(number)))
9 print(type(int(number)))
10 str(number)
3.14
<class 'float'>
<class 'str'>
<class 'int'>
Out[37]:
'3.14'
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 6/11
5.06.2022 15:57 01. introduction_python - Jupyter Notebook
In [42]:
1 # Let's convert the booleans to an integer, a float, and a string
2
3 bool_1 = True
4 bool_2 = False
5
6 print(int(bool_1))
7 print(int(bool_2))
8 print(float(bool_1))
9 print(float(bool_2))
10 print(str(bool_1))
11 print(str(bool_2))
12 print(bool(1))
13 print(bool(0))
1.0
0.0
True
False
True
False
In [46]:
1 # Let's find the data types of 9/3 and 9//4
2
3 print(9/3)
4 print(9//4)
5 print(type(9/3))
6 print(type(9//4))
3.0
<class 'float'>
<class 'int'>
Experesion and variables
In [47]:
1 # Addition
2
3 x = 56+65+89+45+78.5+98.2
4 print(x)
5 print(type(x))
431.7
<class 'float'>
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 7/11
5.06.2022 15:57 01. introduction_python - Jupyter Notebook
In [48]:
1 # Substraction
2
3 x = 85-52-21-8
4 print(x)
5 print(type(x))
<class 'int'>
In [49]:
1 # Multiplication
2
3 x = 8*74
4 print(x)
5 print(type(x))
592
<class 'int'>
In [50]:
1 # Division
2
3 x = 125/24
4 print(x)
5 print(type(x))
5.208333333333333
<class 'float'>
In [51]:
1 # Floor division
2
3 x = 125//24
4 print(x)
5 print(type(x))
<class 'int'>
In [52]:
1 # Modulus
2
3 x = 125%24
4 print(x)
5 print(type(x))
<class 'int'>
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 8/11
5.06.2022 15:57 01. introduction_python - Jupyter Notebook
In [54]:
1 # Exponentiation
2
3 x = 2**3
4 print(x)
5 print(type(x))
<class 'int'>
In [56]:
1 # An example: Let's calculate how many minutes there are in 20 hours?
2
3 one_hour = 60 # 60 minutes
4 hour = 20
5 minutes = one_hour *hour
6 print(minutes)
7 print(type(minutes))
8
9 # An example: Let's calculate how many hours there are in 348 minutes?
10
11 minutes = 348
12 one_hour = 60
13 hours = 348/60
14 print(hours)
15 print(type(hours))
1200
<class 'int'>
5.8
<class 'float'>
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 9/11
5.06.2022 15:57 01. introduction_python - Jupyter Notebook
In [57]:
1 # Mathematica expression
2 x = 45+3*89
3 y = (45+3)*89
4 print(x)
5 print(y)
6 print(x+y)
7 print(x-y)
8 print(x*y)
9 print(x/y)
10 print(x**y)
11 print(x//y)
12 print(x%y)
312
4272
4584
-3960
1332864
0.07303370786516854
1067641991672876496055543763730817849611894303069314938895568785412634039540022
1668842874389034129806306214264361154798836623794212717734310359113620187307704
8553130787246373784413835009801652141537511130496428252345316433301059252139523
9103385944143088194316106218470432254894248261498724877893090946822825581242099
3242205445735594289393570693328984019619118774730111283010744851323185842999276
1218679164101636444032930435771562516453083564435414559235582600151873226528287
4086778132273334129052616885240052566240386236622942378082773719975939989126678
9683171279214118065400092433700677527805247487272637725301042917923096127461019
9709972018821656789423406359174060212611294727986571959777654952011794250637017
9853580809082166014475884812255990200313907285732712182897968690212853238136253
3527097401887285523369419688233628863002122383440451166119429893245226499915609
9033727713855480854355371150599738557878712977577549271433343813379749929657561
1090329888355805852160926406122231645709135255126700296738346241869701327318850
6363349028686981626711602285071129130073002939818468972496440163596801441600675
Variables
In [58]:
1 # Store the value 89 into the variabe 'number'
2
3 number = 90
4 print(number)
5 print(type(number))
90
<class 'int'>
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 10/11
5.06.2022 15:57 01. introduction_python - Jupyter Notebook
In [62]:
1 x = 25
2 y = 87
3 z = 5*x - 2*y
4 print(z)
5
6 t = z/7
7 print(t)
8
9 z = z/14
10 print(z)
-49
-7.0
-3.5
In [68]:
1 x, y, z = 8, 4, 2 # the values of x, y, and z can be written in one line.
2 print(x, y, z)
3 print(x)
4 print(y)
5 print(z)
6 print(x/y)
7 print(x/z)
8 print(y/z)
9 print(x+y+z)
10 print(x*y*z)
11 print(x-y-z)
12 print(x/y/z)
13 print(x//y//z)
14 print(x%y%z)
15
8 4 2
2.0
4.0
2.0
14
64
1.0
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 11/11
5.06.2022 15:55 02. strings_python - Jupyter Notebook
Python Tutorial
Created by Mustafa Germec, PhD
2. Strings
In [1]:
1 # Employ double quotation marks for describing a string
2 "Hello World!"
Out[1]:
'Hello World!'
In [2]:
1 # Employ single quotation marks for describing a string
2 'Hello World!'
Out[2]:
'Hello World!'
In [3]:
1 # Digitals and spaces in a string
2 '3 6 9 2 6 8'
Out[3]:
'3 6 9 2 6 8'
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 1/9
5.06.2022 15:55 02. strings_python - Jupyter Notebook
In [4]:
1 # Specific characters in a string
2 '@#5_]*$%^&'
Out[4]:
'@#5_]*$%^&'
In [5]:
1 # printing a string
2 print('Hello World!')
Hello World!
In [6]:
1 # Assigning a string to a variable 'message'
2 message = 'Hello World!'
3 print(message)
4 message
Hello World!
Out[6]:
'Hello World!'
Indexing of a string
In [7]:
1 # printing the first element in a string
2
3 message = 'Hello World!'
4 print(message[0])
In [8]:
1 # Printing the element on index 8 in a string
2 print(message[8])
In [9]:
1 # lenght of a string includign spaces
2
3 len(message)
Out[9]:
12
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 2/9
5.06.2022 15:55 02. strings_python - Jupyter Notebook
In [10]:
1 # Printing the last element in a string
2 print(message[11])
3
4 # Another comment writing type is as follows using triple quotes.
5
6 """
7 Although the length of the string is 12, since the indexing in Python starts with 0,
8 the number of the last element is therefore 11.
9 """
Out[10]:
'\nAlthough the length of the string is 12, since the indexing in Python starts with 0, \nthe number of th
e last element is therefore 11.\n'
Negative indexing of a string
In [11]:
1 # printing the last element of a string
2
3 message[-1]
Out[11]:
'!'
In [12]:
1 # printing the first element of a string
2
3 message[-12]
4
5 """
6 Since the negative indexing starts with -1, in this case, the negative index number
7 of the first element is equal to -12.
8 """
Out[12]:
'\nSince the negative indexing starts with -1, in this case, the negative index number \nof the first eleme
nt is equal to -12.\n'
In [13]:
1 print(len(message))
2 len(message)
12
Out[13]:
12
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 3/9
5.06.2022 15:55 02. strings_python - Jupyter Notebook
In [14]:
1 len('Hello World!')
Out[14]:
12
Slicing of a string
In [15]:
1 # Slicing on the variable 'message' with only index 0 to index 5
2 message[0:5]
Out[15]:
'Hello'
In [16]:
1 # Slicing on the variable 'message' with only index 6 to index 12
2 message[6:12]
Out[16]:
'World!'
Striding in a string
In [17]:
1 # to select every second element in the variable 'message'
2
3 message[::2]
Out[17]:
'HloWrd'
In [18]:
1 # corporation of slicing and striding
2 # get every second element in range from index 0 to index 6
3
4 message[0:6:2]
Out[18]:
'Hlo'
Concatenate of strings
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 4/9
5.06.2022 15:55 02. strings_python - Jupyter Notebook
In [19]:
1 message = 'Hello World!'
2 question = ' How many people are living on the earth?'
3 statement = message+question
4 statement
Out[19]:
'Hello World! How many people are living on the earth?'
In [20]:
1 # printing a string for 4 times
2 4*" Hello World!"
Out[20]:
' Hello World! Hello World! Hello World! Hello World!'
Escape sequences
In [21]:
1 # New line escape sequence
2 print('Hello World! \nHow many people are living on the earth?')
Hello World!
How many people are living on the earth?
In [22]:
1 # Tab escape sequence
2 print('Hello World! \tHow many people are living on the earth?')
Hello World! How many people are living on the earth?
In [23]:
1 # back slash in a string
2 print('Hello World! \\ How many people are living on the earth?')
3
4 # r will say python that a string will be show as a raw string
5 print(r'Hello World! \ How many people are living on the earth?')
Hello World! \ How many people are living on the earth?
Hello World! \ How many people are living on the earth?
String operations
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 5/9
5.06.2022 15:55 02. strings_python - Jupyter Notebook
In [24]:
1 message = 'hello python!'
2 print('Before uppercase: ', message )
3
4 # convert uppercase the elements in a string
5 message_upper = message.upper()
6 print('After uppercase: ', message_upper)
7
8 # convert lowercase the elements in a string
9 message_lower = message.lower()
10 print('Again lowercase: ', message_lower)
11
12 # convert first letter of string to uppercase
13 message_title = message.title()
14 print('The first element of the string is uppercase: ', message_title)
Before uppercase: hello python!
After uppercase: HELLO PYTHON!
Again lowercase: hello python!
The first element of the string is uppercase: Hello Python!
In [25]:
1 # replace() method in a string
2 message = 'Hello Python!'
3 message_hi = message.replace('Hello', 'Hi')
4 message_python = message.replace('Python', 'World')
5 print(message_hi)
6 print(message_python)
Hi Python!
Hello World!
In [26]:
1 # find() method application in a string
2 message = 'Hello World!'
3 print(message.find('Wo'))
4
5 # the output is the index number of the first element of the substring
In [27]:
1 # find() method application to obtain a substring in a string
2 message.find('World!')
Out[27]:
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 6/9
5.06.2022 15:55 02. strings_python - Jupyter Notebook
In [28]:
1 # if cannot find the substring in a string, the output is -1.
2 message.find('cndsjnd')
Out[28]:
-1
In [30]:
1 text = 'Jean-Paul Sartre somewhere observed that we each of us make our own hell out of the people around us. Had
2
3 # find the first index of the substring 'Nancy'
4 text.find('Nancy')
Out[30]:
122
In [31]:
1 # replace the substring 'Nancy' with 'Nancy Lier Cosgrove Mullis'
2 text.replace('Nancy', 'Nancy Lier Cosgrove Mullis')
Out[31]:
'Jean-Paul Sartre somewhere observed that we each of us make our own hell out of the people around
us. Had Jean-Paul known Nancy Lier Cosgrove Mullis, he may have noted that at least one man, someda
y, might get very lucky, and make his own heaven out of one of the people around him. She will be his m
orning and his evening star, shining with the brightest and the softest light in his heaven. She will be the
end of his wanderings, and their love will arouse the daffodils in the spring to follow the crocuses and pr
ecede the irises. Their faith in one another will be deeper than time and their eternal spirit will be seaml
ess once again.'
In [32]:
1 # convet the text to lower case
2 text.lower()
Out[32]:
'jean-paul sartre somewhere observed that we each of us make our own hell out of the people around u
s. had jean-paul known nancy, he may have noted that at least one man, someday, might get very lucky,
and make his own heaven out of one of the people around him. she will be his morning and his evening
star, shining with the brightest and the softest light in his heaven. she will be the end of his wanderings,
and their love will arouse the daffodils in the spring to follow the crocuses and precede the irises. their f
aith in one another will be deeper than time and their eternal spirit will be seamless once again.'
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 7/9
5.06.2022 15:55 02. strings_python - Jupyter Notebook
In [33]:
1 # convert the first letter of the text to capital letter
2 text.capitalize()
Out[33]:
'Jean-paul sartre somewhere observed that we each of us make our own hell out of the people around
us. had jean-paul known nancy, he may have noted that at least one man, someday, might get very luck
y, and make his own heaven out of one of the people around him. she will be his morning and his evenin
g star, shining with the brightest and the softest light in his heaven. she will be the end of his wandering
s, and their love will arouse the daffodils in the spring to follow the crocuses and precede the irises. thei
r faith in one another will be deeper than time and their eternal spirit will be seamless once again.'
In [34]:
1 # casefold() method returns a string where all the characters are in lower case
2 text.casefold()
Out[34]:
'jean-paul sartre somewhere observed that we each of us make our own hell out of the people around u
s. had jean-paul known nancy, he may have noted that at least one man, someday, might get very lucky,
and make his own heaven out of one of the people around him. she will be his morning and his evening
star, shining with the brightest and the softest light in his heaven. she will be the end of his wanderings,
and their love will arouse the daffodils in the spring to follow the crocuses and precede the irises. their f
aith in one another will be deeper than time and their eternal spirit will be seamless once again.'
In [35]:
1 # center() method will center align the string, using a specified character (space is the default) as the fill character.
2 message = 'Hallo Leute!'
3 message.center(50, '-')
Out[35]:
'-------------------Hallo Leute!-------------------'
In [36]:
1 # count() method returns the number of elements with the specified value
2 text.count('and')
Out[36]:
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 8/9
5.06.2022 15:55 02. strings_python - Jupyter Notebook
In [37]:
1 # format() method
2 """
3 The format() method formats the specified value(s) and insert them inside the string's placeholder.
4 The placeholder is defined using curly brackets: {}.
5 """
6
7 txt = "Hello {word}"
8 print(txt.format(word = 'World!'))
9
10 message1 = 'Hi, My name is {} and I am {} years old.'
11 print(message1.format('Bob', 36))
12
13 message2 = 'Hi, My name is {name} and I am {number} years old.'
14 print(message2.format(name ='Bob', number = 36))
15
16 message3 = 'Hi, My name is {0} and I am {1} years old.'
17 print(message3.format('Bob', 36))
Hello World!
Hi, My name is Bob and I am 36 years old.
Hi, My name is Bob and I am 36 years old.
Hi, My name is Bob and I am 36 years old.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 9/9
5.06.2022 15:52 03. lists_python - Jupyter Notebook
Python Tutorial
Created by Mustafa Germec, PhD
3. Lists
Lists are ordered.
Lists can contain any arbitrary objects.
List elements can be accessed by index.
Lists can be nested to arbitrary depth.
Lists are mutable.
Lists are dynamic.
Indexing
In [1]:
1 # creatinng a list
2 nlis = ['python', 25, 2022]
3 nlis
Out[1]:
['python', 25, 2022]
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 1/13
5.06.2022 15:52 03. lists_python - Jupyter Notebook
In [7]:
1 print('Positive and negative indexing of the first element: \n - Positive index:', nlis[0], '\n - Negative index:', nlis[-3])
2 print()
3 print('Positive and negative indexing of the second element: \n - Positive index:', nlis[1], '\n - Negative index:', nlis[-2])
4 print()
5 print('Positive and negative indexing of the third element: \n - Positive index:', nlis[2], '\n - Negative index:', nlis[-1])
Positive and negative indexing of the first element:
- Positive index: python
- Negative index: python
Positive and negative indexing of the second element:
- Positive index: 25
- Negative index: 25
Positive and negative indexing of the third element:
- Positive index: 2022
- Negative index: 2022
What can content a list?
Strings
Floats
Integer
Boolean
Nested List
Nested Tuple
Other data structures
In [8]:
1 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
2 nlis
Out[8]:
['python',
3.14,
2022,
[1, 1, 2, 3, 5, 8, 13, 21, 34],
('hello', 'python', 3, 14, 2022)]
List operations
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 2/13
5.06.2022 15:52 03. lists_python - Jupyter Notebook
In [10]:
1 # take a list
2 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
3 nlis
Out[10]:
['python',
3.14,
2022,
[1, 1, 2, 3, 5, 8, 13, 21, 34],
('hello', 'python', 3, 14, 2022)]
In [11]:
1 # length of the list
2 len(nlis)
Out[11]:
Slicing
In [20]:
1 # slicing of a list
2 print(nlis[0:2])
3 print(nlis[2:4])
4 print(nlis[4:6])
['python', 3.14]
[2022, [1, 1, 2, 3, 5, 8, 13, 21, 34]]
[('hello', 'python', 3, 14, 2022)]
Extending the list
we use the extend() function to add a new element to the list.
With this function, we add more than one element to the list.
In [25]:
1 # take a list
2 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
3 nlis.extend(['hello world!', 1.618])
4 nlis
Out[25]:
['python',
3.14,
2022,
[1, 1, 2, 3, 5, 8, 13, 21, 34],
('hello', 'python', 3, 14, 2022),
'hello world!',
1.618]
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 3/13
5.06.2022 15:52 03. lists_python - Jupyter Notebook
append() method
As different from the extend() method, with the append() method, we add only one element to the list
You can see the difference by comparing the above and below codes.
In [27]:
1 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
2 nlis.append(['hello world!', 1.618])
3 nlis
Out[27]:
['python',
3.14,
2022,
[1, 1, 2, 3, 5, 8, 13, 21, 34],
('hello', 'python', 3, 14, 2022),
['hello world!', 1.618]]
len(), append(), count(), index(), insert(), max(), min(), sum() functions
In [99]:
1 lis = [1,2,3,4,5,6,7]
2 print(len(lis))
3 lis.append(4)
4 print(lis)
5 print(lis.count(4)) # How many 4 are on the list 'lis'?
6 print(lis.index(2)) # What is the index of the number 2 in the list 'lis'?
7 lis.insert(8, 9) # Add number 9 to the index 8.
8 print(lis)
9 print(max(lis)) # What is the maximum number in the list?
10 print(min(lis)) # What is the minimum number in the list?
11 print(sum(lis)) # What is the sum of the numbers in the list?
[1, 2, 3, 4, 5, 6, 7, 4]
[1, 2, 3, 4, 5, 6, 7, 4, 9]
41
Changing the element of a list since it is mutable
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 4/13
5.06.2022 15:52 03. lists_python - Jupyter Notebook
In [31]:
1 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
2 print('Before changing:', nlis)
3 nlis[0] = 'hello python!'
4 print('After changing:', nlis)
5 nlis[1] = 1.618
6 print('After changing:', nlis)
7 nlis[2] = [3.14, 2022]
8 print('After changing:', nlis)
Before changing: ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
After changing: ['hello python!', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
After changing: ['hello python!', 1.618, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
After changing: ['hello python!', 1.618, [3.14, 2022], [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2
022)]
Deleting the element from the list using del() function
In [34]:
1 print('Before changing:', nlis)
2 del(nlis[0])
3 print('After changing:', nlis)
4 del(nlis[-1])
5 print('After changing:', nlis)
Before changing: [1.618, [3.14, 2022], [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
After changing: [[3.14, 2022], [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
After changing: [[3.14, 2022], [1, 1, 2, 3, 5, 8, 13, 21, 34]]
In [81]:
1 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
2 print('Before deleting:', nlis)
3 del nlis
4 print('After deleting:', nlis)
Before deleting: ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_13488/2190443850.py in <module>
2 print('Before deleting:', nlis)
3 del nlis
----> 4 print('After deleting:', nlis)
NameError: name 'nlis' is not defined
Conversion of a string into a list using split() function
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 5/13
5.06.2022 15:52 03. lists_python - Jupyter Notebook
In [36]:
1 message = 'Python is a programming language.'
2 message.split()
Out[36]:
['Python', 'is', 'a', 'programming', 'language.']
Use of split() function with a delimiter
In [57]:
1 text = 'p,y,t,h,o,n'
2 text.split("," )
Out[57]:
['p', 'y', 't', 'h', 'o', 'n']
Basic operations
In [90]:
1 nlis_1 = ['a', 'b', 'hello', 'Python']
2 nlis_2 = [1,2,3,4, 5, 6]
3 print(len(nlis_1))
4 print(len(nlis_2))
5 print(nlis_1+nlis_2)
6 print(nlis_1*3)
7 print(nlis_2*3)
8 for i in nlis_1:
9 print(i)
10 for i in nlis_2:
11 print(i)
12 print(4 in nlis_1)
13 print(4 in nlis_2)
['a', 'b', 'hello', 'Python', 1, 2, 3, 4, 5, 6]
['a', 'b', 'hello', 'Python', 'a', 'b', 'hello', 'Python', 'a', 'b', 'hello', 'Python']
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
hello
Python
False
True
Copy the list
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 6/13
5.06.2022 15:52 03. lists_python - Jupyter Notebook
In [62]:
1 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
2 copy_list = nlis
3 print('nlis:', nlis)
4 print('copy_list:', copy_list)
nlis: ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
copy_list: ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
In [70]:
1 # The element in the copied list also changes when the element in the original list was changed.
2 # See the following example
3
4 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
5 print(nlis)
6 copy_list = nlis
7 print(copy_list)
8 print('copy_list[0]:', copy_list[0])
9 nlis[0] = 'hello python!'
10 print('copy_list[0]:', copy_list[0])
['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
copy_list[0]: python
copy_list[0]: hello python!
Clone the list
In [72]:
1 # The cloned list is a new copy or clone of the original list.
2 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
3 clone_lis = nlis[:]
4 clone_lis
Out[72]:
['python',
3.14,
2022,
[1, 1, 2, 3, 5, 8, 13, 21, 34],
('hello', 'python', 3, 14, 2022)]
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 7/13
5.06.2022 15:52 03. lists_python - Jupyter Notebook
In [74]:
1 # When an element in the original list is changed, the element in the cloned list does not change.
2 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
3 print(nlis)
4 clone_list = nlis[:]
5 print(clone_list)
6 print('clone_list[0]:', clone_list[0])
7 nlis[0] = 'hello, python!'
8 print('nlis[0]:', nlis[0])
['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
clone_list[0]: python
nlis[0]: hello, python!
Concatenate the list
In [78]:
1 a_list = ['a', 'b', ['c', 'd'], 'e']
2 b_list = [1,2,3,4,5,(6,7), True, False]
3 new_list = a_list + b_list
4 print(new_list)
['a', 'b', ['c', 'd'], 'e', 1, 2, 3, 4, 5, (6, 7), True, False]
As different from the list, I also find significant the following information.
input() function
input() function in Python provides a user of a program supply inputs to the program at runtime.
In [6]:
1 text = input('Enter a string:')
2 print('The text is', text)
3 print(type(text))
The text is Hello, Python!
<class 'str'>
In [12]:
1 # Although the function wants an integer, the type of the entered number is a string.
2 number = input('Enter an integer: ')
3 print('The number is', number)
4 print(type(number))
The number is 15
<class 'str'>
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 8/13
5.06.2022 15:52 03. lists_python - Jupyter Notebook
In [15]:
1 number = int(input('Enter an integer:'))
2 print('The number is', number)
3 print(type(number))
The number is 15
<class 'int'>
In [16]:
1 number = float(input('Enter an integer:'))
2 print('The number is', number)
3 print(type(number))
The number is 15.0
<class 'float'>
eval() functions
This function serves the aim of converting a string to an integer or a float
In [17]:
1 expression = '8+7'
2 total = eval(expression)
3 print('Sum of the expression is', total)
4 print(type(expression))
5 print(type(total))
Sum of the expression is 15
<class 'str'>
<class 'int'>
format() function
This function helps to format the output printed on the secreen with good look and attractive.
In [22]:
1 a = float(input('Enter the pi number:'))
2 b = float(input('Enter the golden ratio:'))
3 total = a + b
4 print('Sum of {} and {} is {}.'.format(a, b, total))
Sum of 3.14 and 1.618 is 4.758.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 9/13
5.06.2022 15:52 03. lists_python - Jupyter Notebook
In [25]:
1 a = input('Enter your favorite fruit:')
2 b = input('Enter your favorite food:')
3 print('I like {} and {}.'.format(a, b))
4 print('I like {0} and {1}.'.format(a, b))
5 print('I like {1} and {0}.'.format(a, b))
I like apple and kebab.
I like apple and kebab.
I like kebab and apple.
Comparison operators
The operators such as <, >, <=, >=, ==, and != compare the certain two operands and return True or False.
In [27]:
1 a = 3.14
2 b = 1.618
3 print('a>b is:', a>b)
4 print('a<b is:', a<b)
5 print('a<=b is:', a<=b)
6 print('a>=b is:', a>=b)
7 print('a==b is:', a==b)
8 print('a!=b is:', a!=b)
a>b is: True
a<b is: False
a<=b is: False
a>=b is: True
a==b is: False
a!=b is: True
Logical operators
The operators including and, or, not are utilized to bring two conditions together and assess them. The
output returns True or False
In [35]:
1 a = 3.14
2 b = 1.618
3 c = 12
4 d = 3.14
5 print(a>b and c>a)
6 print(b>c and d>a)
7 print(b<c or d>a)
8 print( not a==b)
9 print(not a==d)
True
False
True
True
False
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 10/13
5.06.2022 15:52 03. lists_python - Jupyter Notebook
Assignment operators
The operators including =, +=, -=, =, /=, %=, //=, *=, &=, |=, ^=, >>=, and <<= are employed to evaluate a
value to a variable.
In [42]:
1 x = 3.14
2 x+=5
3 print(x)
8.14
In [43]:
1 x = 3.14
2 x-=5
3 print(x)
-1.8599999999999999
In [44]:
1 x = 3.14
2 x*=5
3 print(x)
15.700000000000001
In [45]:
1 x = 3.14
2 x/=5
3 print(x)
0.628
In [46]:
1 x = 3.14
2 x%=5
3 print(x)
3.14
In [47]:
1 x = 3.14
2 x//=5
3 print(x)
0.0
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 11/13
5.06.2022 15:52 03. lists_python - Jupyter Notebook
In [48]:
1 x = 3.14
2 x**=5
3 print(x)
305.2447761824001
Identity operators
The operators is or is not are employed to control if the operands or objects to the left and right of these
operators are referring to a value stored in the same momory location and return True or False.
In [74]:
1 a = 3.14
2 b = 1.618
3 print(a is b)
4 print(a is not b)
5 msg1= 'Hello, Python!'
6 msg2 = 'Hello, World!'
7 print(msg1 is msg2)
8 print(msg1 is not msg2)
9 lis1 = [3.14, 1.618]
10 lis2 = [3.14, 1.618]
11 print(lis1 is lis2) # You should see a list copy behavior
12 print(lis1 is not lis2)
False
True
False
True
False
True
Membership operators
These operators inclusing in and not in are employed to check if the certain value is available in the
sequence of values and return True or False.
In [79]:
1 # take a list
2 nlis = [4, 6, 7, 8, 'hello', (4,5), {'name': 'Python'}, {1,2,3}, [1,2,3]]
3 print(5 in nlis)
4 print(4 not in nlis)
5 print((4,5) in nlis)
6 print(9 not in nlis)
False
False
True
True
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 12/13
5.06.2022 15:52 03. lists_python - Jupyter Notebook
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 13/13
5.06.2022 15:50 04. tuples_python - Jupyter Notebook
Python Tutorial
Created by Mustafa Germec, PhD
4. Tuples in Python
Tuples are immutable lists and cannot be changed in any way once it is created.
Tuples are defined in the same way as lists.
They are enclosed within parenthesis and not within square braces.
Tuples are ordered, indexed collections of data.
Similar to string indices, the first value in the tuple will have the index [0], the second value [1]
Negative indices are counted from the end of the tuple, just like lists.
Tuple also has the same structure where commas separate the values.
Tuples can store duplicate values.
Tuples allow you to store several data items including string, integer, float in one variable.
In [9]:
1 # Take a tuple
2 tuple_1 = ('Hello', 'Python', 3.14, 1.618, True, False, 32, [1,2,3], {1,2,3}, {'A': 3, 'B': 8}, (0, 1))
3 tuple_1
Out[9]:
('Hello',
'Python',
3.14,
1.618,
True,
False,
32,
[1, 2, 3],
{1, 2, 3},
{'A': 3, 'B': 8},
(0, 1))
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 1/9
5.06.2022 15:50 04. tuples_python - Jupyter Notebook
In [10]:
1 print(type(tuple_1))
2 print(len(tuple_1))
<class 'tuple'>
11
Indexing
In [12]:
1 # Printing the each value in a tuple using both positive and negative indexing
2 tuple_1 = ('Hello', 'Python', 3.14, 1.618, True, False, 32, [1,2,3], {1,2,3}, {'A': 3, 'B': 8}, (0, 1))
3 print(tuple_1[0])
4 print(tuple_1[1])
5 print(tuple_1[2])
6 print(tuple_1[-1])
7 print(tuple_1[-2])
8 print(tuple_1[-3])
Hello
Python
3.14
(0, 1)
{'A': 3, 'B': 8}
{1, 2, 3}
In [11]:
1 # Printing the type of each value in the tuple
2 tuple_1 = ('Hello', 'Python', 3.14, 1.618, True, False, 32, [1,2,3], {1,2,3}, {'A': 3, 'B': 8}, (0, 1))
3 print(type(tuple_1[0]))
4 print(type(tuple_1[2]))
5 print(type(tuple_1[4]))
6 print(type(tuple_1[6]))
7 print(type(tuple_1[7]))
8 print(type(tuple_1[8]))
9 print(type(tuple_1[9]))
10 print(type(tuple_1[10]))
<class 'str'>
<class 'float'>
<class 'bool'>
<class 'int'>
<class 'list'>
<class 'set'>
<class 'dict'>
<class 'tuple'>
Concatenation of tuples
To concatenate tuples, + sign is used
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 2/9
5.06.2022 15:50 04. tuples_python - Jupyter Notebook
In [13]:
1 tuple_2 = tuple_1 + ('Hello World!', 2022)
2 tuple_2
Out[13]:
('Hello',
'Python',
3.14,
1.618,
True,
False,
32,
[1, 2, 3],
{1, 2, 3},
{'A': 3, 'B': 8},
(0, 1),
'Hello World!',
2022)
Repetition of a tuple
In [48]:
1 rep_tup = (1,2,3,4)
2 rep_tup*2
Out[48]:
(1, 2, 3, 4, 1, 2, 3, 4)
Membership
In [49]:
1 rep_tup = (1,2,3,4)
2 print(2 in rep_tup)
3 print(2 not in rep_tup)
4 print(5 in rep_tup)
5 print(5 not in rep_tup)
6
True
False
False
True
Iteration
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 3/9
5.06.2022 15:50 04. tuples_python - Jupyter Notebook
In [50]:
1 rep_tup = (1,2,3,4)
2 for i in rep_tup:
3 print(i)
cmp() function
It is to compare two tuples and returs True or False
In [55]:
1 def cmp(t1, t2):
2 return bool(t1 > t2) - bool(t1 < t2)
3 def cmp(t31, t4):
4 return bool(t3 > t4) - bool(t3 < t4)
5 def cmp(t5, t6):
6 return bool(t5 > t6) - bool(t5 < t6)
7 t1 = (1,3,5) # Here t1 is lower than t2, since the output is -1
8 t2 = (2,4,6)
9
10 t3 = (5,) # Here t3 is higher than t4 since the output is 1
11 t4 = (4,)
12
13 t5 = (3.14,) # Here t5 is equal to t6 since the output is 0
14 t6 = (3.14,)
15
16 print(cmp(t1, t2))
17 print(cmp(t3, t4))
18 print(cmp(t5, t6))
-1
min() function
In [56]:
1 rep_tup = (1,2,3,4)
2 min(rep_tup)
Out[56]:
max() function
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 4/9
5.06.2022 15:50 04. tuples_python - Jupyter Notebook
In [58]:
1 rep_tup = (1,2,3,4)
2 max(rep_tup)
Out[58]:
tup(seq) function
It converts a specific sequence to a tuple
In [60]:
1 seq = 'ATGCGTATTGCCAT'
2 tuple(seq)
Out[60]:
('A', 'T', 'G', 'C', 'G', 'T', 'A', 'T', 'T', 'G', 'C', 'C', 'A', 'T')
Slicing
To obtain a new tuple from the current tuple, the slicing method is used.
In [14]:
1 # Obtaining a new tuple from the index 2 to index 6
2
3 tuple_1 = ('Hello', 'Python', 3.14, 1.618, True, False, 32, [1,2,3], {1,2,3}, {'A': 3, 'B': 8}, (0, 1))
4 tuple_1[2:7]
Out[14]:
(3.14, 1.618, True, False, 32)
In [18]:
1 # Obtaining tuple using negative indexing
2 tuple_1 = ('Hello', 'Python', 3.14, 1.618, True, False, 32, [1,2,3], {1,2,3}, {'A': 3, 'B': 8}, (0, 1))
3 tuple_1[-4:-1]
Out[18]:
([1, 2, 3], {1, 2, 3}, {'A': 3, 'B': 8})
len() function
To obtain how many elements there are in the tuple, use len() function.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 5/9
5.06.2022 15:50 04. tuples_python - Jupyter Notebook
In [19]:
1 tuple_1 = ('Hello', 'Python', 3.14, 1.618, True, False, 32, [1,2,3], {1,2,3}, {'A': 3, 'B': 8}, (0, 1))
2 len(tuple_1)
Out[19]:
11
Sorting tuple
In [22]:
1 # Tuples can be sorted and save as a new tuple.
2
3 tuple_3 = (0,9,7,4,6,2,9,8,3,1)
4 sorted_tuple_3 = sorted(tuple_3)
5 sorted_tuple_3
Out[22]:
[0, 1, 2, 3, 4, 6, 7, 8, 9, 9]
Nested tuple
In Python, a tuple written inside another tuple is known as a nested tuple.
In [25]:
1 # Take a nested tuple
2 nested_tuple =('biotechnology', (0, 5), ('fermentation', 'ethanol'), (3.14, 'pi', (1.618, 'golden ratio')) )
3 nested_tuple
Out[25]:
('biotechnology',
(0, 5),
('fermentation', 'ethanol'),
(3.14, 'pi', (1.618, 'golden ratio')))
In [26]:
1 # Now printing the each element of the nested tuple
2 print('Item 0 of nested tuple is', nested_tuple[0])
3 print('Item 1 of nested tuple is', nested_tuple[1])
4 print('Item 2 of nested tuple is', nested_tuple[2])
5 print('Item 3 of nested tuple is', nested_tuple[3])
Element 0 of nested tuple is biotechnology
Element 1 of nested tuple is (0, 5)
Element 2 of nested tuple is ('fermentation', 'ethanol')
Element 3 of nested tuple is (3.14, 'pi', (1.618, 'golden ratio'))
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 6/9
5.06.2022 15:50 04. tuples_python - Jupyter Notebook
In [33]:
1 # Using second index to access other tuples in the nested tuple
2 print('Item 1, 0 of the nested tuple is', nested_tuple[1][0])
3 print('Item 1, 1 of the nested tuple is', nested_tuple[1][1])
4 print('Item 2, 0 of the nested tuple is', nested_tuple[2][0])
5 print('Item 2, 1 of the nested tuple is', nested_tuple[2][1])
6 print('Item 3, 0 of the nested tuple is', nested_tuple[3][0])
7 print('Item 3, 1 of the nested tuple is', nested_tuple[3][1])
8 print('Item 3, 2 of the nested tuple is', nested_tuple[3][2])
9
10 # Accesing to the items in the second nested tuples using a third index
11 print('Item 3, 2, 0 of the nested tuple is', nested_tuple[3][2][0])
12 print('Item 3, 2, 1 of the nested tuple is', nested_tuple[3][2][1])
Item 1, 0 of the nested tuple is 0
Item 1, 1 of the nested tuple is 5
Item 2, 0 of the nested tuple is fermentation
Item 2, 1 of the nested tuple is ethanol
Item 3, 0 of the nested tuple is 3.14
Item 3, 1 of the nested tuple is pi
Item 3, 2 of the nested tuple is (1.618, 'golden ratio')
Item 3, 2, 0 of the nested tuple is 1.618
Item 3, 2, 1 of the nested tuple is golden ratio
Tuples are immutable
In [35]:
1 # Take a tuple
2 tuple_4 = (1,3,5,7,8)
3 tuple_4[0] = 9
4 print(tuple_4)
5
6 # The output shows the tuple is immutable
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_17624/4165256041.py in <module>
1 # Take a tuple
2 tuple_4 = (1,3,5,7,8)
----> 3 tuple_4[0] = 9
4 print(tuple_4)
TypeError: 'tuple' object does not support item assignment
Delete a tuple
An element in a tuple can not be deleted since it is immutable.
But a whole tuple can be deleted
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 7/9
5.06.2022 15:50 04. tuples_python - Jupyter Notebook
In [36]:
1 tuple_4 = (1,3,5,7,8)
2 print('Before deleting:', tuple_4)
3 del tuple_4
4 print('After deleting:', tuple_4)
Before deleting: (1, 3, 5, 7, 8)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_17624/736020228.py in <module>
2 print('Before deleting:', tuple_4)
3 del tuple_4
----> 4 print('After deleting:', tuple_4)
NameError: name 'tuple_4' is not defined
count() method
This method returns the number of time an item occurs in a tuple.
In [39]:
1 tuple_5 = (1,1,3,3,5,5,5,5,6,6,7,8,9)
2 tuple_5.count(5)
Out[39]:
index() method
It returns the index of the first occurrence of the specified value in a tuple
In [42]:
1 tuple_5 = (1,1,3,3,5,5,5,5,6,6,7,8,9)
2 print(tuple_5.index(5))
3 print(tuple_5.index(1))
4 print(tuple_5.index(9))
12
One element tuple
if a tuple includes only one element, you should put a comma after the element. Otherwise, it is not considered
as a tuple.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 8/9
5.06.2022 15:50 04. tuples_python - Jupyter Notebook
In [45]:
1 tuple_6 = (0)
2 print(tuple_6)
3 print(type(tuple_6))
4
5 # Here, you see that the output is an integer
<class 'int'>
In [47]:
1 tuple_7 = (0,)
2 print(tuple_7)
3 print(type(tuple_7))
4
5 # You see that the output is a tuple
(0,)
<class 'tuple'>
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 9/9
5.06.2022 15:49 05. sets_python - Jupyter Notebook
Python Tutorial
Created by Mustafa Germec, PhD
5. Sets in Python
Set is one of 4 built-in data types in Python used to store collections of data including List, Tuple, and
Dictionary
Sets are unordered, but you can remove items and add new items.
Set elements are unique. Duplicate elements are not allowed.
A set itself may be modified, but the elements contained in the set must be of an immutable type.
Sets are used to store multiple items in a single variable.
You can denote a set with a pair of curly brackets {}.
In [47]:
1 # The empty set of curly braces denotes the empty dictionary, not empty set
2 x = {}
3 print(type(x))
<class 'dict'>
In [46]:
1 # To take a set without elements, use set() function without any items
2 y = set()
3 print(type(y))
<class 'set'>
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 1/9
5.06.2022 15:49 05. sets_python - Jupyter Notebook
In [2]:
1 # Take a set
2 set1 = {'Hello Python!', 3.14, 1.618, 'Hello World!', 3.14, 1.618, True, False, 2022}
3 set1
Out[2]:
{1.618, 2022, 3.14, False, 'Hello Python!', 'Hello World!', True}
Converting list to set
In [4]:
1 # A list can convert to a set
2 # Take a list
3 nlis = ['Hello Python!', 3.14, 1.618, 'Hello World!', 3.14, 1.618, True, False, 2022]
4
5 # Convert the list to a set
6 set2 = set(nlis)
7 set2
Out[4]:
{1.618, 2022, 3.14, False, 'Hello Python!', 'Hello World!', True}
Set operations
In [5]:
1 # Take a set
2 set3 = set(['Hello Python!', 3.14, 1.618, 'Hello World!', 3.14, 1.618, True, False, 2022])
3 set3
Out[5]:
{1.618, 2022, 3.14, False, 'Hello Python!', 'Hello World!', True}
add() function
To add an element into a set, we use the function add(). If the same element is added to the set, nothing will
happen because the set accepts no duplicates.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 2/9
5.06.2022 15:49 05. sets_python - Jupyter Notebook
In [6]:
1 # Addition of an element to a set
2 set3 = set(['Hello Python!', 3.14, 1.618, 'Hello World!', 3.14, 1.618, True, False, 2022])
3 set3.add('Hi, Python!')
4 set3
Out[6]:
{1.618,
2022,
3.14,
False,
'Hello Python!',
'Hello World!',
'Hi, Python!',
True}
In [7]:
1 # Addition of the same element
2 set3.add('Hi, Python!')
3 set3
4
5 # As you see that there is only one from the added element 'Hi, Python!'
Out[7]:
{1.618,
2022,
3.14,
False,
'Hello Python!',
'Hello World!',
'Hi, Python!',
True}
update() function
To add multiple elements into the set
In [49]:
1 x_set = {6,7,8,9}
2 print(x_set)
3 x_set.update({3,4,5})
4 print(x_set)
{8, 9, 6, 7}
{3, 4, 5, 6, 7, 8, 9}
remove() function
To remove an element from the set
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 3/9
5.06.2022 15:49 05. sets_python - Jupyter Notebook
In [16]:
1 set3.remove('Hello Python!')
2 set3
3
Out[16]:
{1.618, 2022, 3.14, False, 'Hello World!', True}
discard() function
It leaves the set unchanged if the element to be deleted is not available in the set.
In [50]:
1 set3.discard(3.14)
2 set3
Out[50]:
{1.618, 2022, False, 'Hello World!', True}
In [17]:
1 # To verify if the element is in the set
2 1.618 in set3
Out[17]:
True
Logic operations in Sets
In [18]:
1 # Take two sets
2 set4 = set(['Hello Python!', 3.14, 1.618, 'Hello World!'])
3 set5 = set([3.14, 1.618, True, False, 2022])
4
5 # Printing two sets
6 set4, set5
Out[18]:
({1.618, 3.14, 'Hello Python!', 'Hello World!'},
{False, True, 1.618, 3.14, 2022})
To find the intersect of two sets using &
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 4/9
5.06.2022 15:49 05. sets_python - Jupyter Notebook
In [19]:
1 intersection = set4 & set5
2 intersection
Out[19]:
{1.618, 3.14}
To find the intersect of two sets, use intersection() function
In [21]:
1 set4.intersection(set5) # The output is the same as that of above
Out[21]:
{1.618, 3.14}
difference() function
To find the difference between two sets
In [61]:
1 print(set4.difference(set5))
2 print(set5.difference(set4))
3
4 # The same process can make using subtraction operator as follows:
5 print(set4-set5)
6 print(set5-set4)
{'Hello Python!', 'Hello World!'}
{False, True, 2022}
{'Hello Python!', 'Hello World!'}
{False, True, 2022}
Set comparison
In [62]:
1 print(set4>set5)
2 print(set5>set4)
3 print(set4==set5)
False
False
False
union() function
it corresponds to all the elements in both sets
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 5/9
5.06.2022 15:49 05. sets_python - Jupyter Notebook
In [24]:
1 set4.union(set5)
Out[24]:
{1.618, 2022, 3.14, False, 'Hello Python!', 'Hello World!', True}
issuperset() and issubset() functions
To control if a set is a superset or a subset of another set
In [25]:
1 set(set4).issuperset(set5)
Out[25]:
False
In [27]:
1 set(set4).issubset(set5)
Out[27]:
False
In [34]:
1 print(set([3.14, 1.618]).issubset(set5))
2 print(set([3.14, 1.618]).issubset(set4))
3 print(set4.issuperset([3.14, 1.618]))
4 print(set5.issuperset([3.14, 1.618]))
True
True
True
True
min(), max() and sum() functions
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 6/9
5.06.2022 15:49 05. sets_python - Jupyter Notebook
In [36]:
1 A = [1,1,2,2,3,3,4,4,5,5] # Take a list
2 B = {1,1,2,2,3,3,4,4,5,5} # Take a set
3
4 print('The minimum number of A is', min(A))
5 print('The minimum number of B is', min(B))
6 print('The maximum number of A is', max(A))
7 print('The maximum number of B is', max(B))
8 print('The sum of A is', sum(A))
9 print('The sum of B is', sum(B))
10
11 # As you see that the sum of A and B is different. Because the set takes no duplicate.
The minimum number of A is 1
The minimum number of B is 1
The maximum number of A is 5
The maximum number of B is 5
The sum of A is 30
The sum of B is 15
No mutable sequence in a set
A set can not have mutable elements such as list or dictionary in it. If any, it returns error as follows:
In [39]:
1 set6 = {'Python', 1,2,3, [1,2,3]}
2 set6
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_10540/2974310107.py in <module>
----> 1 set6 = {'Python', 1,2,3, [1,2,3]}
2 set6
TypeError: unhashable type: 'list'
index() function
This function does not work in set since the set is unordered collection
In [48]:
1 set7 = {1,2,3,4}
2 set7[1]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_10540/893084458.py in <module>
1 set7 = {1,2,3,4}
----> 2 set7[1]
TypeError: 'set' object is not subscriptable
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 7/9
5.06.2022 15:49 05. sets_python - Jupyter Notebook
Copy the set
In [54]:
1 set8 = {1,3,5,7,9}
2 print(set8)
3 set9 = set8
4 print(set9)
5 set8.add(11)
6 print(set8)
7 print(set9)
8
9 """
10 As you see that although the number 8 is added into the set 'set8', the added number
11 is also added into the set 'set9'
12 """
{1, 3, 5, 7, 9}
{1, 3, 5, 7, 9}
{1, 3, 5, 7, 9, 11}
{1, 3, 5, 7, 9, 11}
copy() function
it returns a shallow copy of the original set.
In [56]:
1 set8 = {1,3,5,7,9}
2 print(set8)
3 set9 = set8.copy()
4 print(set9)
5 set8.add(11)
6 print(set8)
7 print(set9)
8
9 """
10 When this function is used, the original set stays unmodified.
11 A new copy stored in another set of memory locations is created.
12 The change made in one copy won't reflect in another.
13 """
{1, 3, 5, 7, 9}
{1, 3, 5, 7, 9}
{1, 3, 5, 7, 9, 11}
{1, 3, 5, 7, 9}
Out[56]:
"\nWhen this function is used, the original set stays unmodified.\nA new copy stored in another set of
memory locations is created.\nThe change made in one copy won't reflect in another.\n"
celar() function
it removes all elements in the set and then do the set empty.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 8/9
5.06.2022 15:49 05. sets_python - Jupyter Notebook
In [57]:
1 x = {0, 1,1,2,3,5,8,13, 21,34}
2 print( x)
3 x.clear()
4 print(x)
{0, 1, 2, 3, 34, 5, 8, 13, 21}
set()
pop() function
It removes and returns an arbitrary set element.
In [60]:
1 x = {0, 1,1,2,3,5,8,13,21,34}
2 print(x)
3 x.pop()
4 print(x)
{0, 1, 2, 3, 34, 5, 8, 13, 21}
{1, 2, 3, 34, 5, 8, 13, 21}
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 9/9
5.06.2022 15:48 06. dictionaries_python - Jupyter Notebook
Python Tutorial
Created by Mustafa Germec, PhD
6. Dictionaries in Python
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered, changeable or mutable and do not allow duplicates.
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has
been created.
Dictionaries cannot have two items with the same key.
A dictionary can nested and can contain another dictionary.
In [1]:
1 # Take a sample dictionary
2
3 sample_dict = {'key_1': 3.14, 'key_2': 1.618,
4 'key_3': True, 'key_4': [3.14, 1.618],
5 'key_5': (3.14, 1.618), 'key_6': 2022, (3.14, 1.618): 'pi and golden ratio'}
6 sample_dict
Out[1]:
{'key_1': 3.14,
'key_2': 1.618,
'key_3': True,
'key_4': [3.14, 1.618],
'key_5': (3.14, 1.618),
'key_6': 2022,
(3.14, 1.618): 'pi and golden ratio'}
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 1/9
5.06.2022 15:48 06. dictionaries_python - Jupyter Notebook
Note: As you see that the whole dictionary is enclosed in curly braces, each key is separated from its value by
a column ":", and commas are used to separate the items in the dictionary.
In [4]:
1 # Accessing to the value using the key
2 print(sample_dict['key_1'])
3 print(sample_dict['key_2'])
4 print(sample_dict['key_3'])
5 print(sample_dict['key_4'])
6 print(sample_dict['key_5'])
7 print(sample_dict['key_6'])
8 print(sample_dict[(3.14, 1.618)]) # Keys can be any immutable object like tuple
3.14
1.618
True
[3.14, 1.618]
(3.14, 1.618)
2022
pi and golden ratio
Keys
In [26]:
1 # Take a sample dictionary
2 product = {'Aspergillus niger': 'inulinase', 'Saccharomyces cerevisiae': 'ethanol',
3 'Scheffersomyces stipitis': 'ethanol', 'Aspergillus sojae_1': 'mannanase',
4 'Streptococcus zooepidemicus': 'hyaluronic acid', 'Lactobacillus casei': 'lactic acid',
5 'Aspergillus sojae_2': 'polygalacturonase'}
6 product
7
Out[26]:
{'Aspergillus niger': 'inulinase',
'Saccharomyces cerevisiae': 'ethanol',
'Scheffersomyces stipitis': 'ethanol',
'Aspergillus sojae_1': 'mannanase',
'Streptococcus zooepidemicus': 'hyaluronic acid',
'Lactobacillus casei': 'lactic acid',
'Aspergillus sojae_2': 'polygalacturonase'}
In [27]:
1 # Retrieving the value by keys
2 print(product['Aspergillus niger'])
3 print(product['Saccharomyces cerevisiae'])
4 print(product['Scheffersomyces stipitis'])
inulinase
ethanol
ethanol
keys() function to get the keys in the dictionary
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 2/9
5.06.2022 15:48 06. dictionaries_python - Jupyter Notebook
In [28]:
1 # What are the keys in the dictionary?
2 product.keys()
Out[28]:
dict_keys(['Aspergillus niger', 'Saccharomyces cerevisiae', 'Scheffersomyces stipitis', 'Aspergillus sojae_
1', 'Streptococcus zooepidemicus', 'Lactobacillus casei', 'Aspergillus sojae_2'])
values() function to get the values in the dictionary
In [29]:
1 # What are the values in the dictionary?
2 product.values()
Out[29]:
dict_values(['inulinase', 'ethanol', 'ethanol', 'mannanase', 'hyaluronic acid', 'lactic acid', 'polygalacturona
se'])
Addition of a new key:value pair in the dictionary
In [31]:
1 product['Yarrovia lipolytica'] = 'microbial oil'
2 product
Out[31]:
{'Aspergillus niger': 'inulinase',
'Saccharomyces cerevisiae': 'ethanol',
'Scheffersomyces stipitis': 'ethanol',
'Aspergillus sojae_1': 'mannanase',
'Streptococcus zooepidemicus': 'hyaluronic acid',
'Lactobacillus casei': 'lactic acid',
'Aspergillus sojae_2': 'polygalacturonase',
'Yarrovia lipolytica': 'microbial oil'}
Delete an item using del() function in the dictionary by key
In [32]:
1 del(product['Aspergillus niger'])
2 del(product['Aspergillus sojae_1'])
3 product
Out[32]:
{'Saccharomyces cerevisiae': 'ethanol',
'Scheffersomyces stipitis': 'ethanol',
'Streptococcus zooepidemicus': 'hyaluronic acid',
'Lactobacillus casei': 'lactic acid',
'Aspergillus sojae_2': 'polygalacturonase',
'Yarrovia lipolytica': 'microbial oil'}
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 3/9
5.06.2022 15:48 06. dictionaries_python - Jupyter Notebook
In [1]:
1 del product
2 print(product)
3
4 # The dictionary was deleted.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_2904/1117454704.py in <module>
----> 1 del product
2 print(product)
4 # The dictionary was deleted.
NameError: name 'product' is not defined
Verification using in or not in
In [17]:
1 print('Saccharomyces cerevisiae' in product)
2 print('Saccharomyces cerevisiae' not in product)
True
False
dict() function
This function is used to create a dictionary
In [19]:
1 dict_sample = dict(family = 'music', type='pop', year='2022' , name='happy new year')
2 dict_sample
Out[19]:
{'family': 'music', 'type': 'pop', 'year': '2022', 'name': 'happy new year'}
In [21]:
1 # Numerical index is not used to take the dictionary values. It gives a KeyError
2 dict_sample[1]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_3576/4263495629.py in <module>
1 # Numerical index is not used to take the dictionary values. It gives a KeyError
----> 2 dict_sample[1]
KeyError: 1
clear() functions
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 4/9
5.06.2022 15:48 06. dictionaries_python - Jupyter Notebook
It removes all the items in the dictionary and returns an empty dictionary
In [34]:
1 dict_sample = dict(family = 'music', type='pop', year='2022' , name='happy new year')
2 dict_sample.clear()
3 dict_sample
Out[34]:
{}
copy() function
It returns a shallow copy of the main dictionary
In [35]:
1 sample_original = dict(family = 'music', type='pop', year='2022' , name='happy new year')
2 sample_copy = sample_original.copy()
3 print(sample_original)
4 print(sample_copy)
{'family': 'music', 'type': 'pop', 'year': '2022', 'name': 'happy new year'}
{'family': 'music', 'type': 'pop', 'year': '2022', 'name': 'happy new year'}
In [36]:
1 # This method can be made usign '=' sign
2 sample_copy = sample_original
3 print(sample_copy)
4 print(sample_original)
{'family': 'music', 'type': 'pop', 'year': '2022', 'name': 'happy new year'}
{'family': 'music', 'type': 'pop', 'year': '2022', 'name': 'happy new year'}
pop() function
This function is used to remove a specific item from the dictionary
In [38]:
1 sample_original = dict(family = 'music', type='pop', year='2022' , name='happy new year')
2 print(sample_original.pop('type'))
3 print(sample_original)
4
pop
{'family': 'music', 'year': '2022', 'name': 'happy new year'}
popitem() function
It is used to remove the abitrary items from the dictionary and returns as a tuple.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 5/9
5.06.2022 15:48 06. dictionaries_python - Jupyter Notebook
In [39]:
1 sample_original = dict(family = 'music', type='pop', year='2022' , name='happy new year')
2 print(sample_original.popitem())
3 print(sample_original)
('name', 'happy new year')
{'family': 'music', 'type': 'pop', 'year': '2022'}
get() function
This method returns the value for the specified key if it is available in the dictionary. If the key is not available, it
returns None.
In [41]:
1 sample_original = dict(family = 'music', type='pop', year='2022' , name='happy new year')
2 print(sample_original.get('family'))
3 print(sample_original.get(3))
music
None
fromkeys() function
It returns a new dictionary with the certain sequence of the items as the keys of the dictionary and the values
are assigned with None.
In [44]:
1 keys = {'A', 'T', 'C', 'G'}
2 sequence = dict.fromkeys(keys)
3 print(sequence)
{'C': None, 'T': None, 'A': None, 'G': None}
update() function
It integrates a dictionary with another dictionary or with an iterable of key:value pairs.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 6/9
5.06.2022 15:48 06. dictionaries_python - Jupyter Notebook
In [45]:
1 product = {'Aspergillus niger': 'inulinase', 'Saccharomyces cerevisiae': 'ethanol',
2 'Scheffersomyces stipitis': 'ethanol', 'Aspergillus sojae_1': 'mannanase',
3 'Streptococcus zooepidemicus': 'hyaluronic acid', 'Lactobacillus casei': 'lactic acid',
4 'Aspergillus sojae_2': 'polygalacturonase'}
5
6 sample_original = dict(family = 'music', type='pop', year='2022' , name='happy new year')
7
8 product.update(sample_original)
9 print(product)
{'Aspergillus niger': 'inulinase', 'Saccharomyces cerevisiae': 'ethanol', 'Scheffersomyces stipitis': 'ethanol',
'Aspergillus sojae_1': 'mannanase', 'Streptococcus zooepidemicus': 'hyaluronic acid', 'Lactobacillus case
i': 'lactic acid', 'Aspergillus sojae_2': 'polygalacturonase', 'family': 'music', 'type': 'pop', 'year': '2022', 'na
me': 'happy new year'}
items() function
It returns a list of key:value pairs in a dictionary. The elements in the lists are tuples.
In [46]:
1 product = {'Aspergillus niger': 'inulinase', 'Saccharomyces cerevisiae': 'ethanol',
2 'Scheffersomyces stipitis': 'ethanol', 'Aspergillus sojae_1': 'mannanase',
3 'Streptococcus zooepidemicus': 'hyaluronic acid', 'Lactobacillus casei': 'lactic acid',
4 'Aspergillus sojae_2': 'polygalacturonase'}
5
6 product.items()
Out[46]:
dict_items([('Aspergillus niger', 'inulinase'), ('Saccharomyces cerevisiae', 'ethanol'), ('Scheffersomyces sti
pitis', 'ethanol'), ('Aspergillus sojae_1', 'mannanase'), ('Streptococcus zooepidemicus', 'hyaluronic acid'),
('Lactobacillus casei', 'lactic acid'), ('Aspergillus sojae_2', 'polygalacturonase')])
Iterating dictionary
A dictionary can be iterated using the for loop
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 7/9
5.06.2022 15:48 06. dictionaries_python - Jupyter Notebook
In [11]:
1 # 'for' loop print all the keys in the dictionary
2
3 product = {'Aspergillus niger': 'inulinase', 'Saccharomyces cerevisiae': 'ethanol',
4 'Scheffersomyces stipitis': 'ethanol', 'Aspergillus sojae_1': 'mannanase',
5 'Streptococcus zooepidemicus': 'hyaluronic acid', 'Lactobacillus casei': 'lactic acid',
6 'Aspergillus sojae_2': 'polygalacturonase'}
7
8 for k in product:
9 print(k)
Aspergillus niger
Saccharomyces cerevisiae
Scheffersomyces stipitis
Aspergillus sojae_1
Streptococcus zooepidemicus
Lactobacillus casei
Aspergillus sojae_2
In [15]:
1 # 'for' loop to print the values of the dictionary by using values() and other method
2
3 product = {'Aspergillus niger': 'inulinase', 'Saccharomyces cerevisiae': 'ethanol',
4 'Scheffersomyces stipitis': 'ethanol', 'Aspergillus sojae_1': 'mannanase',
5 'Streptococcus zooepidemicus': 'hyaluronic acid', 'Lactobacillus casei': 'lactic acid',
6 'Aspergillus sojae_2': 'polygalacturonase'}
7 for x in product.values():
8 print(x)
9
10 print()
11 # 'for' loop to print the values of the dictionary by using values() and other method
12 for x in product:
13 print(product[x])
inulinase
ethanol
ethanol
mannanase
hyaluronic acid
lactic acid
polygalacturonase
inulinase
ethanol
ethanol
mannanase
hyaluronic acid
lactic acid
polygalacturonase
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 8/9
5.06.2022 15:48 06. dictionaries_python - Jupyter Notebook
In [16]:
1 # 'for' loop to print the items of the dictionary by using items() method
2 product = {'Aspergillus niger': 'inulinase', 'Saccharomyces cerevisiae': 'ethanol',
3 'Scheffersomyces stipitis': 'ethanol', 'Aspergillus sojae_1': 'mannanase',
4 'Streptococcus zooepidemicus': 'hyaluronic acid', 'Lactobacillus casei': 'lactic acid',
5 'Aspergillus sojae_2': 'polygalacturonase'}
6
7 for x in product.items():
8 print(x)
('Aspergillus niger', 'inulinase')
('Saccharomyces cerevisiae', 'ethanol')
('Scheffersomyces stipitis', 'ethanol')
('Aspergillus sojae_1', 'mannanase')
('Streptococcus zooepidemicus', 'hyaluronic acid')
('Lactobacillus casei', 'lactic acid')
('Aspergillus sojae_2', 'polygalacturonase')
In [17]:
1 product = {'Aspergillus niger': 'inulinase', 'Saccharomyces cerevisiae': 'ethanol',
2 'Scheffersomyces stipitis': 'ethanol', 'Aspergillus sojae_1': 'mannanase',
3 'Streptococcus zooepidemicus': 'hyaluronic acid', 'Lactobacillus casei': 'lactic acid',
4 'Aspergillus sojae_2': 'polygalacturonase'}
5
6 for x, y in product.items():
7 print(x, y)
Aspergillus niger inulinase
Saccharomyces cerevisiae ethanol
Scheffersomyces stipitis ethanol
Aspergillus sojae_1 mannanase
Streptococcus zooepidemicus hyaluronic acid
Lactobacillus casei lactic acid
Aspergillus sojae_2 polygalacturonase
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 9/9
5.06.2022 15:59 07. conditions_python - Jupyter Notebook
Python Tutorial
Created by Mustafa Germec, PhD
7. Conditions in Python
Comparison operators
Comparison operations compare some value or operand and based on a condition, produce a Boolean. Python
has six comparison operators as below:
Less than (<)
Less than or equal to (<=)
Greater than (>)
Greater than or equal to (>=)
Equal to (==)
Not equal to (!=)
In [1]:
1 # Take a variable
2 golden_ratio = 1.618
3
4 # Condition less than
5 print(golden_ratio<2) # The golden ratio is lower than 2, thus the output is True
6 print(golden_ratio<1) # The golden ratio is greater than 1, thus the output is False
True
False
In [4]:
1 # Take a variable
2 golden_ratio = 1.618
3
4 # Condition less than or equal to
5 print(golden_ratio<=2) # The golden ratio is lower than 2, thus the condition is True.
6 print(golden_ratio<=1) # The golden ratio is greater than 1, thus the condition is False.
7 print(golden_ratio<=1.618) # The golden ratio is equal to 1.618, thus the condition is True.
True
False
True
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 1/9
5.06.2022 15:59 07. conditions_python - Jupyter Notebook
In [5]:
1 # Take a variable
2 golden_ratio = 1.618
3
4 # Condition greater than
5 print(golden_ratio>2) # The golden ratio is lower than 2, thus the condition is False.
6 print(golden_ratio>1) # The golden ratio is greater than 1, thus the condition is True.
False
True
In [7]:
1 # Take a variable
2 golden_ratio = 1.618
3
4 # Condition greater than or equal to
5 print(golden_ratio>=2) # The golden ratio is not greater than 2, thus the condition is False.
6 print(golden_ratio>=1) # The golden ratio is greater than 1, thus the condition is True.
7 print(golden_ratio>=1.618) # The golden ratio is equal to 1.618, thus the condition is True.
False
True
True
In [8]:
1 # Take a variable
2 golden_ratio = 1.618
3
4 # Condition equal to
5 print(golden_ratio==2) # The golden ratio is not equal to 1.618, thus the condition is False.
6 print(golden_ratio==1.618) # The golden ratio is equal to 1.618, thus the condition is True.
False
True
In [11]:
1 # Take a variable
2 golden_ratio = 1.618
3
4 # Condition not equal to
5 print(golden_ratio!=2) # The golden ratio is not equal to 1.618, thus the condition is True.
6 print(golden_ratio!=1.618) # The golden ratio is equal to 1.618, thus the condition is False.
True
False
The comparison operators are also employed to compare the letters/words/symbols according to the ASCII
(https://www.asciitable.com/) value of letters.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 2/9
5.06.2022 15:59 07. conditions_python - Jupyter Notebook
In [17]:
1 # Compare strings
2 print('Hello' == 'Python')
3 print('Hello' != 'Python')
4 print('Hello' <= 'Python')
5 print('Hello' >= 'Python')
6 print('Hello' < 'Python')
7 print('Hello' > 'Python')
8 print('B'>'A') # According to ASCII table, the values of A and B are equal 65 and 66, respectively.
9 print('a'>'b') # According to ASCII table, the values of a and b are equal 97 and 98, respectively.
10 print('CD'>'DC') # According to ASCII table, the value of C (67) is lower than that of D (68)
11
12 # The values of uppercase and lowercase letters are different since python is case sensitive.
False
True
True
False
True
False
True
False
False
Branching (if, elif, else)
Decision making is required when we want to execute a code only if a certain condition is satisfied.
The if/elif/else statement is used in Python for decision making.
An else statement can be combined with an if statement.
An else statement contains the block of code that executes if the conditional expression in the if statement
resolves to 0 or a False value
The else statement is an optional statement and there could be at most only one else statement following
if.
The elif statement allows you to check multiple expressions for True and execute a block of code as soon
as one of the conditions evaluates to True.
Similar to the else, the elif statement is optional.
However, unlike else, for which there can be at most one statement, there can be an arbitrary number of
elif statements following an if.
If statement
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 3/9
5.06.2022 15:59 07. conditions_python - Jupyter Notebook
In [6]:
1 pi = 3.14
2 golden_ratio = 1.618
3
4 # This statement can be True or False.
5 if pi > golden_ratio:
6
7 # If the conditions is True, the following statement will be printed.
8 print(f'The number pi {pi} is greater than the golden ratio {golden_ratio}.')
9
10 # The following statement will be printed in each situtation.
11 print('Done!')
The number pi 3.14 is greater than the golden ratio 1.618.
Done!
In [2]:
1 if 2:
2 print('Hello, python!')
Hello, python!
In [5]:
1 if True:
2 print('This is true.')
This is true.
else statement
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 4/9
5.06.2022 15:59 07. conditions_python - Jupyter Notebook
In [8]:
1 pi = 3.14
2 golden_ratio = 1.618
3
4 if pi < golden_ratio:
5 print(f'The number pi {pi} is greater than the golden ratio {golden_ratio}.')
6 else:
7 print(f'The golden ratio {golden_ratio} is lower than the number pi {pi}.')
8 print('Done!')
The golden ratio 1.618 is lower than the number pi 3.14.
Done!
elif statement
In [23]:
1 age = 5
2
3 if age > 6:
4 print('You can go to primary school.' )
5 elif age == 5:
6 print('You should go to kindergarten.')
7 else:
8 print('You are a baby' )
9
10 print('Done!')
You should go to kindergarten.
Done!
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 5/9
5.06.2022 15:59 07. conditions_python - Jupyter Notebook
In [25]:
1 album_year = 2000
2 album_year = 1990
3
4 if album_year >= 1995:
5 print('Album year is higher than 1995.')
6
7 print('Done!')
Done!
In [26]:
1 album_year = 2000
2 # album_year = 1990
3
4 if album_year >= 1995:
5 print('Album year is higher than 1995.')
6 else:
7 print('Album year is lower than 1995.')
8
9 print('Done!')
Album year is higher than 1995.
Done!
In [43]:
1 imdb_point = 9.0
2 if imdb_point > 8.5:
3 print('The movie could win Oscar.')
The movie could win Oscar.
In [13]:
1 movie_rating = float(input('Enter a rating number:'))
2
3 print(f'The entered movie rating is: {movie_rating}')
4
5 if movie_rating > 8.5:
6 print('The movie is awesome with {} rating and you should watch it.'.format(movie_rating))
7 else:
8 print('The movie has merit to be watched with {} rating.'.format(movie_rating))
The entered movie rating is: 8.2
The movie has merit to be watched with 8.2 rating.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 6/9
5.06.2022 15:59 07. conditions_python - Jupyter Notebook
In [18]:
1 note = float(input('Enter a note:'))
2
3 print(f'The entered note value is: {note}')
4
5 if note >= 90 and note <= 100:
6 print('The letter grade is AA.')
7 elif note >= 85 and note <= 89:
8 print('The letter grade is BA.')
9 elif note >= 80 and note <= 84:
10 print('The letter grade is BB.')
11 elif note >= 75 and note <= 79:
12 print('The letter grade is CB.')
13 elif note >= 70 and note <= 74:
14 print('The letter grade is CC.')
15 elif note >= 65 and note <= 69:
16 print('The letter grade is DC.')
17 elif note >= 60 and note <= 64:
18 print('The letter grade is DD.')
19 elif note >=55 and note <= 59:
20 print('The letter grade is ED.')
21 elif note >=50 and note <= 54:
22 print('The letter grade is EE.')
23 elif note >=45 and note <=49:
24 print('The letter grade is FE.')
25 else:
26 print('The letter grade is FF.')
The entered note value is: 74.0
The letter grade is CC.
In [17]:
1 number = int(input('Enter a number:'))
2
3 print(f'The entered number is: {number}')
4
5 if number %2 == 0:
6 print(f'The entered number {number} is even')
7 else:
8 print(f'The entered number {number} is odd')
The entered number is 12
The entered number 12 is even
Logical operators
Logical operators are used to combine conditional statements.
and: Returns True if both statements are true
or: Returns True if one of the statements is true
not: Reverse the result, returns False if the result is true
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 7/9
5.06.2022 15:59 07. conditions_python - Jupyter Notebook
and
In [27]:
1 birth_year = 1990
2 if birth_year > 1989 and birth_year < 1995:
3 print('You were born between 1990 and 1994')
4 print('Done!')
You were born between 1990 and 1994
Done!
In [23]:
1 x = int(input('Enter a number:'))
2 y = int(input('Enter a number: '))
3 z = int(input('Enter a number:'))
4
5 print(f'The entered numbers for x, y, and z are {x}, {y}, and {z}, respectively.')
6
7 if x>y and x>z:
8 print(f'The number x with {x} is the greatest number.')
9 elif y>x and y>z:
10 print(f'The number y with {y} is the greatest number.')
11 else:
12 print(f'The number z with {z} is the greatest number.')
The entered numbers for x, y, and z are 36, 25, and 21, respectively.
The number x with 36 is the greatest number.
or
In [28]:
1 birth_year = 1990
2 if birth_year < 1980 or birth_year > 1989:
3 print('You were not born in 1980s.')
4 else:
5 print('You were born in 1990s.')
6 print('Done!')
You were not born in 1980s.
Done!
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 8/9
5.06.2022 15:59 07. conditions_python - Jupyter Notebook
not
In [29]:
1 birth_year = 1990
2 if not birth_year == 1991:
3 print('The year of birth is not 1991.')
The year of birth is not 1991.
In [15]:
1 birth_year = int(input('Enter a year of birth: '))
2
3 print(f'The entered year of birth is: {birth_year}')
4
5 if birth_year < 1985 or birth_year == 1991 or birth_year == 1995:
6 print(f'You were born in {birth_year}')
7 else:
8 # For instance, if your year of birth is 1993
9 print(f'Your year of birth with {birth_year} is wrong.')
The entered year of birth is: 1993
Your year of birth with 1993 is wrong.
In [16]:
1 birth_year = int(input('Enter a year of birth: '))
2
3 print(f'The entered year of birth is: {birth_year}')
4
5 if birth_year < 1985 or birth_year == 1991 or birth_year == 1995:
6 # For instance, if your year of birth is 1995
7 print(f'You were born in {birth_year}')
8 else:
9 print(f'Your year of birth with {birth_year} is wrong.')
The entered year of birth is: 1995
You were born in 1995
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteboo… 9/9
5.06.2022 16:00 08. loops_python - Jupyter Notebook
Python Tutorial
Created by Mustafa Germec, PhD
8. Loops in Python
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
This is less like the for keyword in other programming languages, 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.
The for loop does not require an indexing variable to set beforehand.
With the while loop we can execute a set of statements as long as a condition is true.
Note: remember to increment i, or else the loop will continue forever.
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.
range() function
It is helpful to think of the range object as an ordered list.
To loop through a set of code a specified number of times, we can use the range() function,
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.
In [3]:
1 # Take a range() function
2 print(range(5))
3 print(range(10))
range(0, 5)
range(0, 10)
for loop
The for loop enables you to execute a code block multiple times.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 1/11
5.06.2022 16:00 08. loops_python - Jupyter Notebook
In [4]:
1 # Take an example
2 # Diectly accessing to the elements in the list
3
4 years = [2005, 2006, 2007, 2008, 2009, 2010]
5
6 for i in years:
7 print(i)
2005
2006
2007
2008
2009
2010
In [10]:
1 # Again, directly accessing to the elements in the list
2 years = [2005, 2006, 2007, 2008, 2009, 2010]
3
4 for year in years:
5 print(year)
2005
2006
2007
2008
2009
2010
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 2/11
5.06.2022 16:00 08. loops_python - Jupyter Notebook
In [6]:
1 # Take an example
2 years = [2005, 2006, 2007, 2008, 2009, 2010]
3
4 for i in range(len(years)):
5 print(years[i])
2005
2006
2007
2008
2009
2010
In [8]:
1 # Another for loop example
2 for i in range(2, 12):
3 print(i)
10
11
In [16]:
1 # Striding in for loop
2 for i in range(2, 12, 3):
3 print(i)
11
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 3/11
5.06.2022 16:00 08. loops_python - Jupyter Notebook
In [12]:
1 # Changing the elements in the list
2 languages = ['Java', 'JavaScript', 'C', 'C++', 'PHP']
3
4 for i in range(len(languages)):
5 print('Before language', i, 'is', languages[i])
6 languages[i] = 'Python'
7 print('After language', i, 'is', languages[i])
Before language 0 is Java
After language 0 is Python
Before language 1 is JavaScript
After language 1 is Python
Before language 2 is C
After language 2 is Python
Before language 3 is C++
After language 3 is Python
Before language 4 is PHP
After language 4 is Python
In [14]:
1 # Enumaeration of the elements in the list
2 languages = ['Python', 'Java', 'JavaScript', 'C', 'C++', 'PHP']
3
4 for index, language in enumerate(languages):
5 print(index, language)
0 Python
1 Java
2 JavaScript
3 C
4 C++
5 PHP
In [30]:
1 # Take the numbers between -3 and 6 using for loop
2 # Use range() function
3
4 for i in range(-3, 7):
5 print(i)
-3
-2
-1
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 4/11
5.06.2022 16:00 08. loops_python - Jupyter Notebook
In [31]:
1 # Take a list and print the elements using for loop
2 languages = ['Python', 'Java', 'JavaScript', 'C', 'C++', 'PHP']
3
4 for i in range(len(languages)):
5 print(i, languages[i])
0 Python
1 Java
2 JavaScript
3 C
4 C++
5 PHP
In [120]:
1 number1 = int(input('Enter a number:'))
2 number2 = int(input('Enter a number:'))
3 print(f'The entered numbers are {number1} and {number2}.')
4 for i in range(0, 11):
5 print(('%d x %d = %d' %(number1, i, number1*i)), ',', ('%d x %d = %d' %(number2, i, number2*i )))
The entered numbers are 7 and 9.
7 x 0 = 0 , 9 x 0 = 0
7 x 1 = 7 , 9 x 1 = 9
7 x 2 = 14 , 9 x 2 = 18
7 x 3 = 21 , 9 x 3 = 27
7 x 4 = 28 , 9 x 4 = 36
7 x 5 = 35 , 9 x 5 = 45
7 x 6 = 42 , 9 x 6 = 54
7 x 7 = 49 , 9 x 7 = 63
7 x 8 = 56 , 9 x 8 = 72
7 x 9 = 63 , 9 x 9 = 81
7 x 10 = 70 , 9 x 10 = 90
Addition and average calculation in for loop
In [2]:
1 # Take a list
2 nlis = [0.577, 2.718, 3.14, 1.618, 1729, 6, 37]
3
4 # Write a for loop for addition
5 count = 0
6 for i in nlis:
7 count+=i
8 print('The total value of the numbers in the list is', count)
9
10 # Calculate the average using len() function
11 print('The avearge value of the numbers in the list is', count/len(nlis))
The total value of the numbers in the list is 1780.053
The total value of the numbers in the list is 254.29328571428573
for-else statement
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 5/11
5.06.2022 16:00 08. loops_python - Jupyter Notebook
for else statement
In [19]:
1 for i in range(1,6):
2 print(i, end=", ")
3 else:
4 print('These are numbers from 1 to 5.')
1, 2, 3, 4, 5, These are numbers from 1 to 5.
nested for loop
In [112]:
1 num = int(input('Enter a number:'))
2
3 print(f'The entered the number is {num}.')
4 i, j = 0, 0
5 for i in range(0, num):
6 print()
7 for j in range(0, i+1):
8 print('+', end='')
The entered the number is 10.
++
+++
++++
+++++
++++++
+++++++
++++++++
+++++++++
++++++++++
continue in for loop
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 6/11
5.06.2022 16:00 08. loops_python - Jupyter Notebook
In [116]:
1 # Take a list
2 nlis = [1,2,4,5,6,7,8,9,10,11,12,13,14]
3 for i in nlis:
4 if i == 5:
5 continue
6 print(i)
7
8 """
9 You see that the output includes the numbers without 5.
10 The continue function jumps when it meets with the reference.
11 """
10
11
12
13
14
Out[116]:
'\nYou see that the output includes the numbers without 5. \nThe continue function jumps when it mee
ts with the reference.\n'
break in for loop
In [118]:
1 # Take a list
2 nlis = [1,2,4,5,6,7,8,9,10,11,12,13,14]
3 for i in nlis:
4 if i == 5:
5 break
6 print(i)
7
8 """
9 You see that the output includes the numbers before 5.
10 The break function terminate the loop when it meets with the reference.
11 """
Out[118]:
'\nYou see that the output includes the numbers before 5. \nThe break function terminate the loop whe
n it meets with the reference.\n'
while loop
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 7/11
5.06.2022 16:00 08. loops_python - Jupyter Notebook
The while loop exists as a tool for repeated execution based on a condition. The code block will keep being
executed until the given logical condition returns a False boolean value.
In [21]:
1 # Take an example
2 i = 22
3 while i<27:
4 print(i)
5 i+=1
22
23
24
25
26
In [22]:
1 #Take an example
2 i = 22
3 while i>=17:
4 print(i)
5 i-=1
22
21
20
19
18
17
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 8/11
5.06.2022 16:00 08. loops_python - Jupyter Notebook
In [25]:
1 # Take an example
2 years = [2005, 2006, 2007, 2008, 2009, 2010]
3
4 index = 0
5
6 year = years[0]
7
8 while year !=2008:
9 print(year)
10 index+=1
11 year = years[index]
12 print('It gives us only', index, 'repetititons to get out of loop')
13
2005
2006
2007
It gives us only 3 repetititons to get out of loop
In [37]:
1 # Print the movie ratings gretater than 6.
2 movie_rating = [8.0, 7.5, 5.4, 9.1, 6.3, 6.5, 2.1, 4.8, 3.3]
3
4 index = 0
5 rating = movie_rating[0]
6
7 while rating>=6:
8 print(rating)
9 index += 1
10 rating = movie_rating[index]
11 print('There is only', index, 'movie rating, because the loop stops when it meets with the number lower than 6.')
8.0
7.5
There is only 2 movie rating, because the loop stops when it meets with the number lower than 6.
In [83]:
1 # Print the movie ratings gretater than 6.
2 movie_rating = [8.0, 7.5, 5.4, 9.1, 6.3, 6.5, 2.1, 4.8, 3.3]
3
4 index = 0
5 for i in range(len(movie_rating)):
6 if movie_rating[i] >= 6:
7 index += 1
8 print(index, movie_rating[i])
9 print('There is only', index, 'films gretater than movie rating 6')
1 8.0
2 7.5
3 9.1
4 6.3
5 6.5
There is only 5 films gretater than movie rating 6
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 9/11
5.06.2022 16:00 08. loops_python - Jupyter Notebook
In [91]:
1 # Adding the element in a list to a new list
2 fruits = ['banana', 'apple', 'banana', 'orange', 'kiwi', 'banana', 'Cherry', 'Grapes']
3
4 new_fruits = []
5
6 index = 0
7 while fruits[index] == 'banana':
8 new_fruits.append(fruits[index])
9 index += 1
10 print(new_fruits)
['banana']
In [119]:
1 number1 = int(input('Enter a number:'))
2 number2 = int(input('Enter a number:'))
3 print(f'The entered numbers are {number1} and {number2}.')
4
5 i=0
6 while i<=10:
7 print(('%d x %d = %d' %(number1, i, number1*i)), ',', ('%d x %d = %d' %(number2, i, number2*i )))
8 i+=1
9
The entered numbers are 8 and 9.
8 x 0 = 0 , 9 x 0 = 0
8 x 1 = 8 , 9 x 1 = 9
8 x 2 = 16 , 9 x 2 = 18
8 x 3 = 24 , 9 x 3 = 27
8 x 4 = 32 , 9 x 4 = 36
8 x 5 = 40 , 9 x 5 = 45
8 x 6 = 48 , 9 x 6 = 54
8 x 7 = 56 , 9 x 7 = 63
8 x 8 = 64 , 9 x 8 = 72
8 x 9 = 72 , 9 x 9 = 81
8 x 10 = 80 , 9 x 10 = 90
while-else statement
In [29]:
1 index = 0
2 while index <=5:
3 print(index, end=' ')
4 index += 1
5 else:
6 print('It gives us the numbers between 0 and 5.')
0 1 2 3 4 5 It gives us the numbers between 0 and 5.
continue in while loop
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 10/11
5.06.2022 16:00 08. loops_python - Jupyter Notebook
In [122]:
1 i=0
2
3 while i<=5:
4 print(i)
5 i+=1
6 if i == 3:
7 continue
break in while loop
In [121]:
1 i=0
2
3 while i<=5:
4 print(i)
5 i+=1
6 if i == 3:
7 break
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 11/11
5.06.2022 16:01 09. functions_python - Jupyter Notebook
Python Tutorial
Created by Mustafa Germec, PhD
9. Functions in Python
In Python, a function is a group of related statements that performs a specific task.
Functions help break our program into smaller and modular chunks. * As our program grows larger and
larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes the code reusable.
There are two types of functions :
Pre-defined functions
User defined functions
In Python a function is defined using the def keyword followed by the function name and parentheses ().
Keyword def that marks the start of the function header.
A function name to uniquely identify the function.
Function naming follows the same rules of writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional.
A colon (:) to mark the end of the function header.
Optional documentation string (docstring) to describe what the function does.
One or more valid python statements that make up the function body.
Statements must have the same indentation level (usually 4 spaces).
An optional return statement to return a value from the function.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 1/14
5.06.2022 16:01 09. functions_python - Jupyter Notebook
In [9]:
1 # Take a function sample
2 # Mathematical operations in a function
3
4 def process(x):
5 y1 = x-8
6 y2 = x+8
7 y3 = x*8
8 y4 = x/8
9 y5 = x%8
10 y6 = x//8
11 print(f'If you make the above operations with {x}, the results will be {y1}, {y2}, {y3}, {y4}, {y5}, {y6}.')
12 return y1, y2, y3, y4, y5, y6
13
14 process(5)
If you make the above operations with 5, the results will be -3, 13, 40, 0.625, 5, 0.
Out[9]:
(-3, 13, 40, 0.625, 5, 0)
You can request help using help() function
In [10]:
1 help(process)
Help on function process in module __main__:
process(x)
Call the function again with the number 3.14
In [11]:
1 process(3.14)
If you make the above operations with 3.14, the results will be -4.859999999999999, 11.14, 25.12, 0.39
25, 3.14, 0.0.
Out[11]:
(-4.859999999999999, 11.14, 25.12, 0.3925, 3.14, 0.0)
Functions with multiple parameters
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 2/14
5.06.2022 16:01 09. functions_python - Jupyter Notebook
In [2]:
1 # Define a function with multiple elements
2 def mult(x, y):
3 z = 2*x + 5*y + 45
4 return z
5
6 output = mult(3.14, 1.618) # You can yield the output by assigning to a variable
7 print(output)
8 print(mult(3.14, 1.618)) # You can obtain the result directly
9 mult(3.14, 1.618) # This is also another version
59.370000000000005
59.370000000000005
Out[2]:
59.370000000000005
In [20]:
1 # Call again the defined function with different arguments
2 print(mult(25, 34))
265
Variables
The input to a function is called a formal parameter.
A variable that is declared inside a function is called a local variable.
The parameter only exists within the function (i.e. the point where the function starts and stops).
A variable that is declared outside a function definition is a global variable, and its value is accessible and
modifiable throughout the program.
In [5]:
1 # Define a function
2 def function(x):
3
4 # Take a local variable
5 y = 3.14
6 z = 3*x + 1.618*y
7 print(f'If you make the above operations with {x}, the results will be {z}.')
8 return z
9
10 with_golden_ratio = function(1.618)
11 print(with_golden_ratio)
If you make the above operations with 1.618, the results will be 9.934520000000001.
9.934520000000001
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 3/14
5.06.2022 16:01 09. functions_python - Jupyter Notebook
In [8]:
1 # It starts the gloabal variable
2 a = 3.14
3
4 # call function and return function
5 y = function(a)
6 print(y)
If you make the above operations with 3.14, the results will be 14.500520000000002.
14.500520000000002
In [9]:
1 # Enter a number directly as a parameter
2 function(2.718)
If you make the above operations with 2.718, the results will be 13.23452.
Out[9]:
13.23452
Without return statement, the function returns None
In [10]:
1 # Define a function with and without return statement
2 def msg1():
3 print('Hello, Python!')
4
5 def msg2():
6 print('Hello, World!')
7 return None
8
9 msg1()
10 msg2()
Hello, Python!
Hello, World!
In [15]:
1 # Printing the function after a call indicates a None is the default return statement.
2 # See the following prontings what functions returns are.
3
4 print(msg1())
5 print(msg2())
Hello, Python!
None
Hello, World!
None
Concatetantion of two strings
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 4/14
5.06.2022 16:01 09. functions_python - Jupyter Notebook
In [18]:
1 # Define a function
2 def strings(x, y):
3 return x + y
4
5 # Testing the function 'strings(x, y)'
6 strings('Hello', ' ' 'Python')
Out[18]:
'Hello Python'
Simplicity of functions
In [26]:
1 # The following codes are not used again.
2 x = 2.718
3 y = 0.577
4 equation = x*y + x+y - 37
5 if equation>0:
6 equation = 6
7 else: equation = 37
8
9 equation
Out[26]:
37
In [27]:
1 # The following codes are not used again.
2 x=0
3 y=0
4 equation = x*y + x+y - 37
5 if equation<0:
6 equation = 0
7 else: equation = 37
8
9 equation
Out[27]:
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 5/14
5.06.2022 16:01 09. functions_python - Jupyter Notebook
In [28]:
1 # The following codes can be write as a function.
2 def function(x, y):
3 equation = x*y + x+y - 37
4 if equation>0:
5 equation = 6
6 else: equation = 37
7 return equation
8
9 x = 2.718
10 y = 0.577
11 function(x, y)
Out[28]:
37
In [29]:
1 # The following codes can be write as a function.
2 def function(x, y):
3 equation = x*y + x+y - 37
4 if equation<0:
5 equation = 6
6 else: equation = 37
7 return equation
8
9 x=0
10 y=0
11 function(x, y)
Out[29]:
Predefined functions like print(), sum(), len(), min(), max(), input()
In [31]:
1 # print() is a built-in function
2 special_numbers = [0.577, 2.718, 3.14, 1.618, 1729, 6, 28, 37]
3 print(special_numbers)
[0.577, 2.718, 3.14, 1.618, 1729, 6, 28, 37]
In [32]:
1 # The function sum() add all elements in a list or a tuple
2 sum(special_numbers)
Out[32]:
1808.053
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 6/14
5.06.2022 16:01 09. functions_python - Jupyter Notebook
In [33]:
1 # The function len() gives us the length of the list or tuple
2 len(special_numbers)
Out[33]:
Using conditions and loops in functions
In [44]:
1 # Define a function including conditions if/else
2
3 def fermentation(microorganism, substrate, product, activity):
4 print(microorganism, substrate, product, activity)
5 if activity < 1000:
6 return f'The fermentation process was unsuccessful with the {product} activity of {activity} U/mL from {substrate}
7 else:
8 return f'The fermentation process was successful with the {product} activity of {activity} U/mL from {substrate} us
9
10 result1 = fermentation('Aspergillus niger', 'molasses', 'inulinase', 1800)
11 print(result1)
12 print()
13 result2 = fermentation('Aspergillus niger', 'molasses', 'inulinase', 785)
14 print(result2)
15
Aspergillus niger molasses inulinase 1800
The fermentation process was successful with the inulinase activity of 1800 U/mL from molasses using A
spergillus niger.
Aspergillus niger molasses inulinase 785
The fermentation process was unsuccessful with the inulinase activity of 785 U/mL from molasses using
Aspergillus niger. You should repeat the fermentation process.
In [50]:
1 # Define a function using the loop 'for'
2
3 def fermentation(content):
4 for parameters in content:
5 print(parameters)
6
7 content = ['Stirred-tank bioreactor' ,'30°C temperature', '200 rpm agitation speed', '1 vvm aeration', '1% (v/v) inoculum
8 fermentation(content)
Stirred-tank bioreactor
30°C temperature
200 rpm agitation speed
1 vvm aeration
1% (v/v) inoculum ratio
pH control at 5.0
Adjustiing default values of independent variables in functions
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 7/14
5.06.2022 16:01 09. functions_python - Jupyter Notebook
In [53]:
1 # Define a function adjusting the default value of the variable
2
3 def rating_value(rating = 5.5):
4 if rating < 8:
5 return f'You should not watch this film with the rating value of {rating}'
6 else:
7 return f'You should watch this film with the rating value of {rating}'
8
9 print(rating_value())
10 print(rating_value(8.6))
You should not watch this film with the rating value of 5.5
You should watch this film with the rating value of 8.6
Global variables
Variables that are created outside of a function (as in all of the examples above) are known as global
variables.
Global variables can be used by everyone, both inside of functions and outside.
In [56]:
1 # Define a function for a global variable
2 language = 'Python'
3
4 def lang(language):
5 global_var = language
6 print(f'{language} is a program language.')
7
8 lang(language)
9 lang(global_var)
10
11 """
12 The output gives a NameError, since all variables in the function are local variables,
13 so variable assignment is not persistent outside the function.
14 """
Python is a program language.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_21468/4270999454.py in <module>
8 lang(language)
----> 9 lang(global_var)
NameError: name 'global_var' is not defined
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 8/14
5.06.2022 16:01 09. functions_python - Jupyter Notebook
In [58]:
1 # Define a function for a global variable
2 language = 'JavaScript'
3
4 def lang(language):
5 global global_var
6 global_var = 'Python'
7 print(f'{language} is a programing language.')
8
9 lang(language)
10 lang(global_var)
JavaScript is a programing language.
Python is a programing language.
Variables in functions
The scope of a variable is the part of the program to which that variable is accessible.
Variables declared outside of all function definitions can be accessed from anywhere in the program.
Consequently, such variables are said to have global scope and are known as global variables.
In [76]:
1 process = 'Continuous fermentation'
2
3 def fermentation(process_name):
4 if process_name == process:
5 return '0.5 g/L/h.'
6 else:
7 return '0.25 g/L/h.'
8
9 print('The productiovity in continuous fermentation is', fermentation('Continuous fermentation'))
10 print('The productiovity in batch fermentation is', fermentation('Batch fermentation'))
11 print('Continuous fermentation has many advantages over batch fermentation.')
12 print(f'My favourite process is {process}.')
The productiovity in continuous fermentation is 0.5 g/L/h.
The productiovity in batch fermentation is 0.25 g/L/h.
Continuous fermentation has many advantages over batch fermentation.
My favourite process is Continuous fermentation.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 9/14
5.06.2022 16:01 09. functions_python - Jupyter Notebook
In [77]:
1 # If the variable 'process' is deleted, it returns a NameError as follows
2 del process
3
4 # Since the variable 'process' is deleted, the following function is an example of local variable
5 def fermentation(process_name):
6 process = 'Continuous fermentation'
7 if process_name == process:
8 return '0.5 g/L/h.'
9 else:
10 return '0.25 g/L/h.'
11
12 print('The productiovity in continuous fermentation is', fermentation('Continuous fermentation'))
13 print('The productiovity in batch fermentation is', fermentation('Batch fermentation'))
14 print('Continuous fermentation has many advantages over batch fermentation.')
15 print(f'My favourite process is {process}.')
The productiovity in continuous fermentation is 0.5 g/L/h.
The productiovity in batch fermentation is 0.25 g/L/h.
Continuous fermentation has many advantages over batch fermentation.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_21468/2006816728.py in <module>
13 print('The productiovity in batch fermentation is', fermentation('Batch fermentation'))
14 print('Continuous fermentation has many advantages over batch fermentation.')
---> 15 print(f'My favourite process is {process}.')
NameError: name 'process' is not defined
In [81]:
1 # When the global variable and local variable have the same name:
2
3 process = 'Continuous fermentation'
4
5 def fermentation(process_name):
6 process = 'Batch fermentation'
7 if process_name == process:
8 return '0.5 g/L/h.'
9 else:
10 return '0.25 g/L/h.'
11
12 print('The productiovity in continuous fermentation is', fermentation('Continuous fermentation'))
13 print('The productiovity in batch fermentation is', fermentation('Batch fermentation'))
14 print(f'My favourite process is {process}.')
The productiovity in continuous fermentation is 0.25 g/L/h.
The productiovity in batch fermentation is 0.5 g/L/h.
My favourite process is Continuous fermentation.
(args) and/or (*args) and Functions
When the number of arguments are unkknown for a function, then the arguments can be packet into a tuple or
a dictionary
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 10/14
5.06.2022 16:01 09. functions_python - Jupyter Notebook
In [84]:
1 # Define a function regarding a tuple example
2 def function(*args):
3 print('Number of elements is', len(args))
4 for element in args:
5 print(element)
6
7 function('Aspergillus niger', 'inulinase', 'batch', '1800 U/mL activity')
8 print()
9 function('Saccharomyces cerevisia', 'ethanol', 'continuous', '45% yield', 'carob')
10
Number of elements is 4
Aspergillus niger
inulinase
batch
1800 U/mL activity
Number of elements is 5
Saccharomyces cerevisia
ethanol
continuous
45% yield
carob
In [98]:
1 # Another example regarding 'args'
2 def total(*args):
3 total = 0
4 for i in args:
5 total += i
6 return total
7
8 print('The total of the numbers is', total(0.577, 2.718, 3.14, 1.618, 1729, 6, 37))
The total of the numbers is 1780.053
In [88]:
1 # Define a function regarding a dictionary example
2 def function(**args):
3 for key in args:
4 print(key, ':', args[key])
5
6 function(Micoorganism='Aspergillus niger', Substrate='Molasses', Product='Inulinase', Fermentation_mode='Batch', A
Micoorganism : Aspergillus niger
Substrate : Molasses
Product : Inulinase
Fermentation_mode : Batch
Activity : 1800 U/mL
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 11/14
5.06.2022 16:01 09. functions_python - Jupyter Notebook
In [96]:
1 # Define a function regarding the addition of elements into a list
2 def addition(nlist):
3 nlist.append(3.14)
4 nlist.append(1.618)
5 nlist.append(1729)
6 nlist.append(6)
7 nlist.append(37)
8
9 my_list= [0.577, 2.718]
10 addition(my_list)
11 print(my_list)
12 print(sum(my_list))
13 print(min(my_list))
14 print(max(my_list))
15 print(len(my_list))
[0.577, 2.718, 3.14, 1.618, 1729, 6, 37]
1780.053
0.577
1729
Doctsting in Functions
In [97]:
1 # Define a function
2 def addition(x, y):
3 """The following function returns the sum of two parameters."""
4 z = x+y
5 return z
6
7 print(addition.__doc__)
8 print(addition(3.14, 2.718))
The following function returns the sum of two parameters.
5.8580000000000005
Recursive functions
In [103]:
1 # Calculating the factorial of a certain number.
2
3 def factorial(number):
4 if number == 0:
5 return 1
6 else:
7 return number*factorial(number-1)
8
9 print('The value is', factorial(6))
The value is 720
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 12/14
5.06.2022 16:01 09. functions_python - Jupyter Notebook
In [107]:
1 # Define a function that gives the total of the first ten numbers
2 def total_numbers(number, sum):
3 if number == 11:
4 return sum
5 else:
6 return total_numbers(number+1, sum+number)
7
8 print('The total of first ten numbers is', total_numbers(1, 0))
The total of first ten numbers is 55
Nested functions
In [111]:
1 # Define a function that add a number to another number
2 def added_num(num1):
3 def incremented_num(num1):
4 num1 = num1 + 1
5 return num1
6 num2 = incremented_num(num1)
7 print(num1, '------->>', num2)
8
9 added_num(25)
25 ------->> 26
nonlocal function
In [112]:
1 # Define a function regarding 'nonlocal' function
2 def print_year():
3 year = 1990
4 def print_current_year():
5 nonlocal year
6 year += 32
7 print('Current year is', year)
8 print_current_year()
9 print_year()
Current year is 2022
In [117]:
1 # Define a function giving a message
2 def function(name):
3 msg = 'Hi ' + name
4 return msg
5
6 name = input('Enter a name: ')
7 print(function(name))
Hi Mustafa
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 13/14
5.06.2022 16:01 09. functions_python - Jupyter Notebook
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 14/14
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
Python Tutorial
Created by Mustafa Germec, PhD
10. Exception Handling in Python
An exception is an event, which occurs during the execution of a program that disrupts the normal flow of
the program's instructions.
In general, when a Python script encounters a situation that it cannot cope with, it raises an exception.
An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception immediately otherwise it
terminates and quits.
If you have some suspicious code that may raise an exception, you can defend your program by placing
the suspicious code in a try: block.
After the try: block, include an except: statement, followed by a block of code which handles the problem
as elegantly as possible.
Common exceptions
ZeroDivisionError
NameError
ValueError
IOError
EOFError
IdentationError
ZeroDivisionError
In [1]:
1 # If a number is divided by 0, it gives a ZeroDivisionError.
2 try:
3 1/0
4 except ZeroDivisionError:
5 print('This code gives a ZeroDivisionError.')
6
7 print(1/0)
This code gives a ZeroDivisionError.
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/3605061481.py in <module>
5 print('This code gives a ZeroDivisionError.')
----> 7 print(1/0)
ZeroDivisionError: division by zero
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 1/10
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
In [2]:
1 nlis = []
2 count = 0
3 try:
4 mean = count/len(nlis)
5 print('The mean value is', mean)
6 except ZeroDivisionError:
7 print('This code gives a ZeroDivisionError')
8
9 print(count/len(nlis))
This code gives a ZeroDivisionError
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/2225123637.py in <module>
7 print('This code gives a ZeroDivisionError')
----> 9 print(count/len(nlis))
ZeroDivisionError: division by zero
In [3]:
1 # The following code is like 1/0.
2 try:
3 True/False
4 except ZeroDivisionError:
5 print('The code gives a ZeroDivisionError.')
6
7 print(True/False)
The code gives a ZeroDivisionError.
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/3531407864.py in <module>
5 print('The code gives a ZeroDivisionError.')
----> 7 print(True/False)
ZeroDivisionError: division by zero
NameError
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 2/10
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
In [4]:
1 nlis = []
2 count = 0
3 try:
4 mean = count/len(nlis)
5 print('The mean value is', mean)
6 except ZeroDivisionError:
7 print('This code gives a ZeroDivisionError')
8
9 # Since the variable 'mean' is not defined, it gives us a 'NameError
10 print(mean)
This code gives a ZeroDivisionError
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/1642249892.py in <module>
9 # Since the variable 'mean' is not defined, it gives us a 'NameError
---> 10 print(mean)
NameError: name 'mean' is not defined
In [5]:
1 try:
2 y = x+5
3 except NameError:
4 print('This code gives a NameError.')
5
6 print(y)
This code gives a NameError.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/115043188.py in <module>
4 print('This code gives a NameError.')
----> 6 print(y)
NameError: name 'y' is not defined
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 3/10
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
In [6]:
1 # Define a function giving a NameError
2 def addition(x, y):
3 z=x+y
4 return z
5
6 print('This function gives a NameError.')
7 total = add(3.14, 1.618)
8 print(total)
This function gives a NameError.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/3845321401.py in <module>
6 print('This function gives a NameError.')
----> 7 total = add(3.14, 1.618)
8 print(total)
NameError: name 'add' is not defined
In [7]:
1 # Since 'Mustafa' is not defined, the following code gives us a 'NameError.'
2 try:
3 name = (Mustafa)
4 print(name, 'today is your wedding day.')
5 except NameError:
6 print('This code gives a NameError.')
7
8 name = (Mustafa)
9 print(name, 'today is your wedding day.')
This code gives a NameError.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/367854978.py in <module>
6 print('This code gives a NameError.')
----> 8 name = (Mustafa)
9 print(name, 'today is your wedding day.')
NameError: name 'Mustafa' is not defined
IndexError
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 4/10
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
In [8]:
1 nlis = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]
2 try:
3 nlis[10]
4 except IndexError:
5 print('This code gives us a IndexError.')
6
7 print(nlis[10])
This code gives us a IndexError.
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/4262347625.py in <module>
5 print('This code gives us a IndexError.')
----> 7 print(nlis[10])
IndexError: list index out of range
In [9]:
1 # You can also supplytake this error type with tuple
2 tuple_sample = (0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729)
3 try:
4 tuple_sample[10]
5 except IndexError:
6 print('This code gives us a IndexError.')
7
8 print(tuple_sample[10])
This code gives us a IndexError.
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/3170854299.py in <module>
6 print('This code gives us a IndexError.')
----> 8 print(tuple_sample[10])
IndexError: tuple index out of range
KeyError
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 5/10
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
In [10]:
1 dictionary = {'euler_constant': 0.577, 'golden_ratio': 1.618}
2 try:
3 dictonary = dictionary['euler_number']
4 except KeyError:
5 print('This code gives us a KeyError.')
6
7 dictonary = dictionary['euler_number']
8 print(dictonary)
This code gives us a KeyError.
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/669363184.py in <module>
5 print('This code gives us a KeyError.')
----> 7 dictonary = dictionary['euler_number']
8 print(dictonary)
KeyError: 'euler_number'
You can find more Error Types (https://docs.python.org/3/library/exceptions.html?
utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=N
SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-
2021-01-01) from this connection.
Exception Handling
try/except
In [11]:
1 try:
2 print(name)
3 except NameError:
4 print('Since the variable name is not defined, the function gives a NameError.')
Since the variable name is not defined, the function gives a NameError.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 6/10
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
In [1]:
1 num1 = float(input('Enter a number:'))
2 print('The entered value is', num1)
3 try:
4 num2 = float(input('Enter a number:'))
5 print('The entered value is', num2)
6 value = num1/num2
7 print('This process is running with value = ', value)
8 except:
9 print('This process is not running.')
The entered value is 3.14
The entered value is 0.577
This process is running with value = 5.441941074523397
Multiple Except Blocks
try/except/except etc.
In [2]:
1 num1 = float(input('Enter a number:'))
2 print('The entered value is', num1)
3 try:
4 num2 = float(input('Enter a number:'))
5 print('The entered value is', num2)
6 value = num1/num2
7 print('This process is running with value = ', value)
8 except ZeroDivisionError:
9 print('This function gives a ZeroDivisionError since a number cannot divide by 0.')
10 except ValueError:
11 print('You should provide a number.')
12 except:
13 print('Soething went wrong!')
The entered value is 2.718
The entered value is 0.0
This function gives a ZeroDivisionError since a number cannot divide by 0.
try/except/else
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 7/10
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
In [3]:
1 num1 = float(input('Enter a number:'))
2 print('The entered value is', num1)
3 try:
4 num2 = float(input('Enter a number:'))
5 print('The entered value is', num2)
6 value = num1/num2
7 except ZeroDivisionError:
8 print('This function gives a ZeroDivisionError since a number cannot divide by 0.')
9 except ValueError:
10 print('You should provide a number.')
11 except:
12 print('Soething went wrong!')
13 else:
14 print('This process is running with value = ', value)
The entered value is 37.0
The entered value is 1.618
This process is running with value = 22.867737948084052
try/except/else/finally
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 8/10
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
In [5]:
1 num1 = float(input('Enter a number:'))
2 print('The entered value is', num1)
3 try:
4 num2 = float(input('Enter a number:'))
5 print('The entered value is', num2)
6 value = num1/num2
7 except ZeroDivisionError:
8 print('This function gives a ZeroDivisionError since a number cannot divide by 0.')
9 except ValueError:
10 print('You should provide a number.')
11 except:
12 print('Soething went wrong!')
13 else:
14 print('This process is running with value = ', value)
15 finally:
16 print('The process is completed.')
The entered value is 1.618
The entered value is 0.577
This process is running with value = 2.8041594454072793
The process is completed.
Multiple except clauses
In [6]:
1 num1 = float(input('Enter a number:'))
2 print('The entered value is', num1)
3 try:
4 num2 = float(input('Enter a number:'))
5 print('The entered value is', num2)
6 value = num1/num2
7 except (ZeroDivisionError, NameError, ValueError): #Multiple except clauses
8 print('This function gives a ZeroDivisionError, NameError or ValueError.')
9 except:
10 print('Soething went wrong!')
11 else:
12 print('This process is running with value = ', value)
13 finally:
14 print('The process is completed.')
The entered value is 3.14
The entered value is 0.0
This function gives a ZeroDivisionError, NameError or ValueError.
The process is completed.
Raising in exception
Using the 'raise' keyword, the programmer can throw an exception when a certain condition is reached.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 9/10
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
In [7]:
1 num = int(input('Enter a number:'))
2 print('The entered value is', num)
3 try:
4 if num>1000 and num %2 == 0 or num %2 !=0:
5 raise Exception('Do not allow to the even numbers higher than 1000.')
6 except:
7 print('Even or odd numbers higher than 1000 are not allowed!')
8 else:
9 print('This process is running with value = ', num)
10 finally:
11 print('The process is completed.')
The entered value is 1006
Even or odd numbers higher than 1000 are not allowed!
The process is completed.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 10/10