Python Tutorial Codes
Python Tutorial Codes
(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]:
Hello World!
Hi, Python!
Version control
In [10]:
3.10
['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'
NAME
sys
MODULE REFERENCE
https://docs.python.org/3.10/library/sys.html (https://docs.python.org/3.10/library/sys.html)
DESCRIPTION
Dynamic objects:
Comment
In [12]:
Hello World!
Hello
Errors
In [13]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_13804/1191913539.py in <module>
In [14]:
print('Hello, World!)
In [15]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_13804/3194197137.py in <module>
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
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]:
sys.int_info(bits_per_digit=30, sizeof_digit=4)
In [35]:
6.0
<class 'int'>
<class 'str'>
<class 'float'>
Out[35]:
'6'
In [37]:
3.14
<class 'float'>
<class 'str'>
<class 'int'>
Out[37]:
'3.14'
In [42]:
1.0
0.0
True
False
True
False
In [46]:
3.0
<class 'float'>
<class 'int'>
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'>
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'>
In [54]:
1 # Exponentiation
2
3 x = 2**3
4 print(x)
5 print(type(x))
<class 'int'>
In [56]:
1200
<class 'int'>
5.8
<class 'float'>
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]:
90
<class 'int'>
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]:
8 4 2
2.0
4.0
2.0
14
64
1.0
Python Tutorial
Created by Mustafa Germec, PhD
2. Strings
In [1]:
Out[1]:
'Hello World!'
In [2]:
Out[2]:
'Hello World!'
In [3]:
Out[3]:
'3 6 9 2 6 8'
In [4]:
Out[4]:
'@#5_]*$%^&'
In [5]:
1 # printing a string
2 print('Hello World!')
Hello World!
In [6]:
Hello World!
Out[6]:
'Hello World!'
Indexing of a string
In [7]:
In [8]:
In [9]:
Out[9]:
12
In [10]:
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'
In [11]:
Out[11]:
'!'
In [12]:
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
In [14]:
1 len('Hello World!')
Out[14]:
12
Slicing of a string
In [15]:
Out[15]:
'Hello'
In [16]:
Out[16]:
'World!'
Striding in a string
In [17]:
Out[17]:
'HloWrd'
In [18]:
Out[18]:
'Hlo'
Concatenate of strings
In [19]:
Out[19]:
In [20]:
Out[20]:
Escape sequences
In [21]:
Hello World!
In [22]:
In [23]:
String operations
In [24]:
In [25]:
Hi Python!
Hello World!
In [26]:
In [27]:
Out[27]:
In [28]:
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]:
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]:
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.'
In [33]:
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]:
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!
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]:
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 index: 25
- Negative index: 25
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,
List operations
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,
In [11]:
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]
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.618]
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,
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
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)]
In [34]:
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)]
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)]
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_13488/2190443850.py in <module>
3 del nlis
In [36]:
Out[36]:
In [57]:
1 text = 'p,y,t,h,o,n'
2 text.split("," )
Out[57]:
Basic operations
In [90]:
['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
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
In [72]:
Out[72]:
['python',
3.14,
2022,
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
In [78]:
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]:
<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'>
In [15]:
The number is 15
<class 'int'>
In [16]:
<class 'float'>
eval() functions
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))
<class 'str'>
<class 'int'>
format() function
This function helps to format the output printed on the secreen with good look and attractive.
In [22]:
In [25]:
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)
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
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
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
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.
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},
(0, 1))
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]:
<class 'str'>
<class 'float'>
<class 'bool'>
<class 'int'>
<class 'list'>
<class 'set'>
<class 'dict'>
<class 'tuple'>
Concatenation of tuples
In [13]:
Out[13]:
('Hello',
'Python',
3.14,
1.618,
True,
False,
32,
[1, 2, 3],
{1, 2, 3},
(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
In [50]:
1 rep_tup = (1,2,3,4)
2 for i in rep_tup:
3 print(i)
cmp() function
In [55]:
-1
min() function
In [56]:
1 rep_tup = (1,2,3,4)
2 min(rep_tup)
Out[56]:
max() function
In [58]:
1 rep_tup = (1,2,3,4)
2 max(rep_tup)
Out[58]:
tup(seq) function
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]:
Out[14]:
In [18]:
Out[18]:
len() function
To obtain how many elements there are in the tuple, use len() function.
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]:
Out[22]:
[0, 1, 2, 3, 4, 6, 7, 8, 9, 9]
Nested tuple
In [25]:
Out[25]:
('biotechnology',
(0, 5),
('fermentation', 'ethanol'),
In [26]:
In [33]:
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
---------------------------------------------------------------------------
~\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)
Delete a tuple
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)
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_17624/736020228.py in <module>
3 del tuple_4
count() method
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
if a tuple includes only one element, you should put a comma after the element. Otherwise, it is not considered
as a tuple.
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'>
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'>
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]:
In [4]:
Out[4]:
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]:
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.
In [6]:
Out[6]:
{1.618,
2022,
3.14,
False,
'Hello Python!',
'Hello World!',
'Hi, Python!',
True}
In [7]:
Out[7]:
{1.618,
2022,
3.14,
False,
'Hello Python!',
'Hello World!',
'Hi, Python!',
True}
update() function
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
In [16]:
1 set3.remove('Hello Python!')
2 set3
3
Out[16]:
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]:
In [17]:
Out[17]:
True
In [18]:
Out[18]:
In [19]:
Out[19]:
{1.618, 3.14}
In [21]:
Out[21]:
{1.618, 3.14}
difference() function
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)
Set comparison
In [62]:
1 print(set4>set5)
2 print(set5>set4)
3 print(set4==set5)
False
False
False
union() function
In [24]:
1 set4.union(set5)
Out[24]:
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
In [36]:
The sum of A is 30
The sum of B is 15
A set can not have mutable elements such as list or dictionary in it. If any, it returns error as follows:
In [39]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_10540/2974310107.py in <module>
2 set6
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]
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_10540/893084458.py in <module>
1 set7 = {1,2,3,4}
----> 2 set7[1]
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
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.
In [57]:
set()
pop() function
In [60]:
1 x = {0, 1,1,2,3,5,8,13,21,34}
2 print(x)
3 x.pop()
4 print(x)
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]:
Out[1]:
{'key_1': 3.14,
'key_2': 1.618,
'key_3': True,
'key_6': 2022,
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]:
3.14
1.618
True
[3.14, 1.618]
(3.14, 1.618)
2022
Keys
In [26]:
Out[26]:
In [27]:
inulinase
ethanol
ethanol
In [28]:
Out[28]:
In [29]:
Out[29]:
In [31]:
Out[31]:
In [32]:
1 del(product['Aspergillus niger'])
2 del(product['Aspergillus sojae_1'])
3 product
Out[32]:
In [1]:
1 del product
2 print(product)
3
4 # The dictionary was deleted.
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_2904/1117454704.py in <module>
2 print(product)
In [17]:
True
False
dict() function
In [19]:
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]
---------------------------------------------------------------------------
~\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
It removes all the items in the dictionary and returns an empty dictionary
In [34]:
Out[34]:
{}
copy() function
In [35]:
{'family': 'music', 'type': 'pop', 'year': '2022', 'name': 'happy new year'}
{'family': 'music', 'type': 'pop', 'year': '2022', 'name': 'happy new year'}
In [36]:
{'family': 'music', 'type': 'pop', 'year': '2022', 'name': 'happy new year'}
{'family': 'music', 'type': 'pop', 'year': '2022', 'name': 'happy new year'}
pop() function
In [38]:
pop
popitem() function
It is used to remove the abitrary items from the dictionary and returns as a tuple.
In [39]:
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]:
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]:
update() function
In [45]:
items() function
It returns a list of key:value pairs in a dictionary. The elements in the lists are tuples.
In [46]:
Out[46]:
Iterating dictionary
In [11]:
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
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)
In [17]:
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:
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
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.
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
If statement
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!')
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
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!')
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!')
Done!
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!')
Done!
In [43]:
1 imdb_point = 9.0
2 if imdb_point > 8.5:
3 print('The movie could win Oscar.')
In [13]:
In [18]:
In [17]:
Logical operators
Logical operators are used to combine conditional statements.
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!')
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.
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!')
Done!
not
In [29]:
1 birth_year = 1990
2 if not birth_year == 1991:
3 print('The year of birth is not 1991.')
In [15]:
In [16]:
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]:
range(0, 5)
range(0, 10)
for loop
The for loop enables you to execute a code block multiple times.
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]:
2005
2006
2007
2008
2009
2010
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]:
10
11
In [16]:
11
In [12]:
Before language 2 is C
In [14]:
0 Python
1 Java
2 JavaScript
3 C
4 C++
5 PHP
In [30]:
-3
-2
-1
In [31]:
0 Python
1 Java
2 JavaScript
3 C
4 C++
5 PHP
In [120]:
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
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))
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.')
In [112]:
++
+++
++++
+++++
++++++
+++++++
++++++++
+++++++++
++++++++++
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'
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
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
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
In [37]:
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 8.0
2 7.5
3 9.1
4 6.3
5 6.5
In [91]:
['banana']
In [119]:
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.')
In [122]:
1 i=0
2
3 while i<=5:
4 print(i)
5 i+=1
6 if i == 3:
7 continue
In [121]:
1 i=0
2
3 while i<=5:
4 print(i)
5 i+=1
6 if i == 3:
7 break
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.
In [9]:
If you make the above operations with 5, the results will be -3, 13, 40, 0.625, 5, 0.
Out[9]:
In [10]:
1 help(process)
process(x)
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]:
In [2]:
59.370000000000005
59.370000000000005
Out[2]:
59.370000000000005
In [20]:
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
In [8]:
If you make the above operations with 3.14, the results will be 14.500520000000002.
14.500520000000002
In [9]:
If you make the above operations with 2.718, the results will be 13.23452.
Out[9]:
13.23452
In [10]:
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
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]:
Out[26]:
37
In [27]:
Out[27]:
In [28]:
Out[28]:
37
In [29]:
Out[29]:
In [31]:
In [32]:
Out[32]:
1808.053
In [33]:
Out[33]:
In [44]:
The fermentation process was successful with the inulinase activity of 1800 U/mL from molasses using A
spergillus niger.
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]:
Stirred-tank bioreactor
30°C temperature
1 vvm aeration
pH control at 5.0
In [53]:
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]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_21468/4270999454.py in <module>
8 lang(language)
----> 9 lang(global_var)
In [58]:
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]:
In [77]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_21468/2006816728.py in <module>
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}.')
When the number of arguments are unkknown for a function, then the arguments can be packet into a tuple or
a dictionary
In [84]:
Number of elements is 4
Aspergillus niger
inulinase
batch
Number of elements is 5
Saccharomyces cerevisia
ethanol
continuous
45% yield
carob
In [98]:
In [88]:
Substrate : Molasses
Product : Inulinase
Fermentation_mode : Batch
In [96]:
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))
5.8580000000000005
Recursive functions
In [103]:
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))
Nested functions
In [111]:
25 ------->> 26
nonlocal function
In [112]:
In [117]:
Hi Mustafa
Python Tutorial
Created by Mustafa Germec, PhD
ZeroDivisionError
In [1]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_5432/3605061481.py in <module>
----> 7 print(1/0)
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))
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_5432/2225123637.py in <module>
----> 9 print(count/len(nlis))
In [3]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_5432/3531407864.py in <module>
----> 7 print(True/False)
NameError
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)
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_5432/1642249892.py in <module>
---> 10 print(mean)
In [5]:
1 try:
2 y = x+5
3 except NameError:
4 print('This code gives a NameError.')
5
6 print(y)
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_5432/115043188.py in <module>
----> 6 print(y)
In [6]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_5432/3845321401.py in <module>
8 print(total)
In [7]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_5432/367854978.py in <module>
IndexError
In [8]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_5432/4262347625.py in <module>
----> 7 print(nlis[10])
In [9]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_5432/3170854299.py in <module>
----> 8 print(tuple_sample[10])
KeyError
In [10]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_5432/669363184.py in <module>
8 print(dictonary)
KeyError: 'euler_number'
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.
In [1]:
try/except/except etc.
In [2]:
try/except/else
In [3]:
try/except/else/finally
In [5]:
In [6]:
Raising in exception
Using the 'raise' keyword, the programmer can throw an exception when a certain condition is reached.
In [7]:
Python Tutorial
Created by Mustafa Germec, PhD
abs()
Returns the absolute value of a number
In [3]:
all()
Retturns True if all elements in passes iterable are true. When the iterable object is empty, it returns True. Here,
0 and False return False in this function.
In [10]:
True
False
[0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729, 0, False]
False
[]
True
bin()
Returns the binary representation of a specificied integer
In [14]:
bool()
Converts a value to boolean, namely True and False
In [25]:
False
True
bytes()
Returns a btyes object
In [26]:
b'Hello, Python!'
callable()
Checks and returns True if the object passed appears to be callable
In [31]:
1 var = 3.14
2 print(callable(var)) # since the object does not appear callable, it returns False
3
4 def function(): # since the object appears callable, it returns True
5 print('Hi, Python!')
6 msg = function
7 print(callable(msg))
False
True
chr()
It returns a character from the specified Unicode code.
In [134]:
1 print(chr(66))
2 print(chr(89))
3 print(chr(132))
4 print(chr(1500))
5 print(chr(3))
6 print(chr(-500)) # The argument must be inside of the range.
ל
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_16192/1238010354.py in <module>
4 print(chr(1500))
5 print(chr(3))
In [135]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_16192/213842990.py in <module>
compile()
Returns a code object that can subsequently be executed by exec() function
In [35]:
<class 'code'>
Result = 19.87
exec()
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 4/35
7.06.2022 01:23 11. built_in_functions_python - Jupyter Notebook
In [39]:
1 var = 3.14
2 exec('print(var==3.14)')
3 exec('print(var!=3.14)')
4 exec('print(var+2.718)')
True
False
5.8580000000000005
getattr()
It returns the value of the specified attribute (property or method). If it is not found, it returns the default value.
In [42]:
1 class SpecialNumbers:
2 euler_constant = 0.577
3 euler_number = 2.718
4 pi = 3.14
5 golden_ratio = 1.618
6 msg = 'These numbers are special.'
7
8 special_numbers = SpecialNumbers()
9 print('The euler number is', getattr(special_numbers, 'euler_number'))
10 print('The golden ratio is', special_numbers.golden_ratio)
delattr()
It deletes the specified attribute (property or method) from the specified object.
In [143]:
1 class SpecialNumbers:
2 euler_constant = 0.577
3 euler_number = 2.718
4 pi = 3.14
5 golden_ratio = 1.618
6 msg = 'These numbers are special.'
7
8 def parameter(self):
9 print(self.euler_constant, self.euler_number, self.pi, self.golden_ratio, self.msg)
10
11 special_numbers = SpecialNumbers()
12 special_numbers.parameter()
13 delattr(SpecialNumbers, 'msg') # The code deleted the 'msg'.
14 special_numbers.parameter() # Since the code deleted the 'msg', it returns an AttributeError.
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_16192/3892590851.py in <module>
12 special_numbers.parameter()
13 delattr(SpecialNumbers, 'msg')
---> 14 special_numbers.parameter()
~\AppData\Local\Temp/ipykernel_16192/3892590851.py in parameter(self)
8 def parameter(self):
10
11 special_numbers = SpecialNumbers()
dict()
It returns a dictionary (Array).
In [158]:
1 name = dict()
2 print(name)
3
4 dictionary = dict(euler_constant = 0.577, euler_number=2.718, golden_ratio=1.618)
5 print(dictionary)
{}
enumerate()
It takes a collection (e.g. a tuple) and returns it as an enumerate object.
In [156]:
0 Hello Python!
1 Hello, World!
In [155]:
filter()
It excludes items in an iterable object.
In [159]:
1 def filtering(data):
2 if data > 30:
3 return data
4
5 data = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]
6 result = filter(filtering, data)
7 print(list(result))
[37, 1729]
globals()
It returns the current global symbol table as a dictionary.
In [39]:
1 globals()
Out[39]:
{'__name__': '__main__',
'__package__': None,
'__loader__': None,
'__spec__': None,
'_ih': ['',
In [41]:
1 num = 37
2 globals()['num'] = 3.14
3 print(f'The number is {num}.')
frozen()
It returns a frozenset object
In [36]:
any()
It returns True if any iterable is True.
In [10]:
True
[]
False
[0]
False
[0, False]
False
[0, False, True]
True
True
[None]
False
ascii()
It returns a string including a printable representation of an object and escapes non-ASCII characters in the
string employing \u, \x or \U escapes
In [17]:
'Hello, Python!'
'Hello, Pyth\xe4n!'
Hello, Pythän!
'Hell\xfc, World!'
Hellü, World!
bytearray()
It returns a new array of bytes.
In [23]:
bytearray(b'Hello, Python!')
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
bytearray(b'\x00\x01\x01\x02\x03\x05\x08\r\x15"')
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_16192/391563769.py in <module>
6 print(bytearray(nlis))
7 float_num = 3.14
----> 8 print(bytearray(float_num))
hasattr()
It returns True if the specified object has the specified attribute (property/method).
In [47]:
1 class SpecialNumbers:
2 euler_constant = 0.577
3 euler_number = 2.718
4 pi = 3.14
5 golden_ratio = 1.618
6 msg = 'These numbers are special.'
7
8 special_numbers = SpecialNumbers()
9 print('The euler number is', hasattr(special_numbers, 'euler_number'))
10 print('The golden ratio is', hasattr(special_numbers, 'golden_ratio'))
11 print('The golden ratio is', hasattr(special_numbers, 'prime_number')) # Since there is no prime number, the output
hash()
It returns the hash value of a specified object.
In [166]:
1 print(hash(3.14))
2 print(hash(0.577))
3 print(hash('Hello, Python!'))
4 print(hash(1729))
5 n_tuple = (0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729)
6 print(hash(n_tuple))
322818021289917443
1330471416316301312
-7855314544920281827
1729
-6529577050584256413
help()
Executes the built-in help system
In [167]:
1 help()
If this is your first time using Python, you should definitely check out
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
with a one-line summary of what it does; to list the modules whose name
You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
has the same effect as typing a particular string at the help> prompt.
In [169]:
1 import pandas as pd
2 help(pd) # You can find more information about pandas.
NAME
pandas
DESCRIPTION
=====================================================================
easy and intuitive. It aims to be the fundamental high-level building block for
the broader goal of becoming **the most powerful and flexible open source data
Main Features
-------------
H j t f f th thi th t d d ll
id()
Returns the id of an object
In [188]:
1 print(id('Hello, Python!'))
2 print(id(3.14))
3 print(id(1729))
4 special_nums_list = [0.577, 1.618, 2.718, 3.14, 28, 37, 1729]
5 print(id(special_nums_list))
6 special_nums_tuple = (0.577, 1.618, 2.718, 3.14, 28, 37, 1729)
7 print(id(special_nums_tuple))
8 special_nums_set = {0.577, 1.618, 2.718, 3.14, 28, 37, 1729}
9 print(id(special_nums_set))
10 special_nums_dict = {'Euler constant': 0.577, 'Golden ratio': 1.618,
11 'Euler number': 2.718, 'PI number': 3.14,
12 'Perfect number': 28, 'Prime number': 37,
13 'Ramanujan Hardy number': 1729}
14 print(id(special_nums_dict))
1699639717104
1699636902256
1699636902896
1699639562944
1699639414208
1699639822816
1699639515264
eval()
This function evaluates and executes an expression.
In [26]:
1369
map()
It returns the specified iterator with the specified function applied to each item.
In [77]:
len()
It returns the length of an object
In [54]:
In [59]:
min()
Returns the smallest item in an iterable
In [170]:
0.577
max()
Returns the largest item in an iterable
In [171]:
1729
sum()
To get the sum of numbers in a list
In [172]:
1808.0529999999999
float()
It returns a floating point number.
In [28]:
1 int_num = 37
2 print(float(int_num))
3 float_num = 3.14
4 print(float(float_num))
5 txt = '2.718'
6 print(float(txt))
7 msg = 'Hello, Python!' # It resturns a ValueError
8 print(float(msg))
37.0
3.14
2.718
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_16192/162113112.py in <module>
6 print(float(txt))
----> 8 print(float(msg))
locals()
It returns an updated dictionary of the current local symbol table.
In [68]:
1 locals()
Out[68]:
{'__name__': '__main__',
'__package__': None,
'__loader__': None,
'__spec__': None,
'_ih': ['',
In [70]:
1 def function():
2 variable = True
3 print(variable)
4 locals()['variable'] = False # locals() dictionary may not change the information inside the locals table.
5 print(variable)
6
7 function()
True
True
In [75]:
1 def dict_1():
2 return locals()
3
4 def dict_2():
5 program = 'Python'
6 return locals()
7
8 print('If there is no locals(), it returns an empty dictionary', dict_1())
9 print('If there is locals(), it returns a dictionary', dict_2())
format()
This function formats a specified value. d, f, and b are a type.
In [33]:
1 # integer format
2 int_num = 37
3 print(format(num, 'd'))
4 # float numbers
5 float_num = 2.7182818284
6 print(format(float_num, 'f'))
7 # binary format
8 num = 1729
9 print(format(num, 'b'))
37
2.718282
11011000001
hex()
Converts a number into a hexadecimal value
In [184]:
1 print(hex(6))
2 print(hex(37))
3 print(hex(1729))
0x6
0x25
0x6c1
input()
Allowing user input
In [219]:
int()
Returns an integer number
In [223]:
1 num1 = int(6)
2 num2 = int(3.14)
3 num3 = int('28')
4 print(f'The numbers are {num1}, {num2},and {num3}.')
isinstance()
It checks if the object (first argument) is an instance or subclass of classinfo class (second argument).
In [226]:
True
In [225]:
1 class SpecialNumbers:
2 euler_constant = 0.577
3 euler_number = 2.718
4 pi = 3.14
5 golden_ratio = 1.618
6 msg = 'These numbers are very special'
7
8 def __init__(self, euler_constant, euler_number, pi, golden_ratio, msg):
9 self.euler_constant = euler_constant
10 self.euler_number = euler_number
11 self.pi = pi
12 self.golden_ratio = golden_ratio
13 self.msg = msg
14
15 special_numbers = SpecialNumbers(0.577, 2.718, 3.14, 1.618, 'These numbers are very special.')
16 nums = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
17 print(isinstance(special_numbers, SpecialNumbers))
18 print(isinstance(nums, SpecialNumbers))
True
False
issubclass()
Checks if the class argument (first argument) is a subclass of classinfo class (second argument).
In [263]:
1 class Circle:
2 def __init__(circleType):
3 print('Circle is a ', circleType)
4
5 class Square(Circle):
6 def __init__(self):
7
8 Circle.__init__('square')
9
10 print(issubclass(Square, Circle))
11 print(issubclass(Square, list))
12 print(issubclass(Square, (list, Circle)))
13 print(issubclass(Circle, (list, Circle)))
True
False
True
True
iter()
It returns an iterator object.
In [52]:
Pi number is 3.14
6 is a perfect number.
28 is a perfect number.
object()
It returns a new object.
In [97]:
1 name= object()
2 print(type(name))
3 print(dir(name))
<class 'object'>
oct()
It returns an octal string from the given integer number. The oct() function takes an integer number and returns
its octal representation.
In [232]:
In [235]:
1 # decimal to octal
2 print('oct(1729) is:', oct(1729))
3
4 # binary to octal
5 print('oct(0b101) is:', oct(0b101))
6
7 # hexadecimal to octal
8 print('oct(0XA) is:', oct(0XA))
list()
It creates a list in Python.
In [67]:
1 print(list())
2 txt = 'Python'
3 print(list(txt))
4 special_nums_set = {0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729}
5 print(list(special_nums_set))
6 special_nums_tuple = (0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729)
7 print(list(special_nums_tuple))
8 special_nums_dict = {'Euler constant': 0.577,
9 'Golden ratio': 1.618,
10 'Euler number': 2.718,
11 'Pi number': 3.14,
12 'Perfect number': 6,
13 'Prime number': 37,
14 'Ramanujan Hardy number': 1729}
15 print(list(special_nums_dict))
[]
['Euler constant', 'Golden ratio', 'Euler number', 'Pi number', 'Perfect number', 'Prime number', 'Ramanu
jan Hardy number']
memoryview()
It returns a memory view object.
In [91]:
1 ba = bytearray('XYZ', 'utf-8')
2 mv = memoryview(ba)
3 print(mv)
4 print(mv[0])
5 print(mv[1])
6 print(mv[2])
7 print(bytes(mv[0:2]))
8 print(list(mv[:]))
9 print(set(mv[:]))
10 print(tuple(mv[:]))
11 mv[1] = 65 # 'Y' was replaced with 'A'
12 print(list(mv[:]))
13 print(ba)
<memory at 0x0000018BB24C5D80>
88
89
90
b'XY'
bytearray(b'XAZ')
In [ ]:
In [218]:
0.577
1.618
2.718
3.14
28
37
1729
open()
It opens a file and returns a file object.
In [120]:
1 path = "authors.txt"
2 file = open(path, mode = 'r', encoding='utf-8')
3 print(file.name)
4 print(file.read())
authors.txt
English,Charles Severance
English,Sue Blumenberg
English,Elloitt Hauser
In [122]:
English,Charles Severance
English,Sue Blumenberg
English,Elloitt Hauser
complex()
It returns a complex number.
In [138]:
1 print(complex(1))
2 print(complex(2, 2))
3 print(complex(3.14, 1.618))
(1+0j)
(2+2j)
(3.14+1.618j)
dir()
It returns a list of the specified object's properties and methods.
In [148]:
1 name = dir()
2 print(name)
3 print()
4 number = 3.14
5 print(dir(number))
6 print()
7 nlis = [3.14]
8 print(dir(nlis))
9 print()
10 nset = {3.14}
11 print(dir(nset))
['FileContent', 'In', 'Out', 'SpecialNumbers', '_', '_103', '_105', '_107', '_109', '_113', '_114', '_116', '_118',
'_119', '_144', '_39', '_68', '_92', '_98', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '_
_name__', '__package__', '__spec__', '__vsc_ipynb_file__', '_dh', '_i', '_i1', '_i10', '_i100', '_i101', '_i10
2', '_i103', '_i104', '_i105', '_i106', '_i107', '_i108', '_i109', '_i11', '_i110', '_i111', '_i112', '_i113', '_i114',
'_i115', '_i116', '_i117', '_i118', '_i119', '_i12', '_i120', '_i121', '_i122', '_i123', '_i124', '_i125', '_i126', '_i1
27', '_i128', '_i129', '_i13', '_i130', '_i131', '_i132', '_i133', '_i134', '_i135', '_i136', '_i137', '_i138', '_i139',
'_i14', '_i140', '_i141', '_i142', '_i143', '_i144', '_i145', '_i146', '_i147', '_i148', '_i15', '_i16', '_i17', '_i18',
'_i19', '_i2', '_i20', '_i21', '_i22', '_i23', '_i24', '_i25', '_i26', '_i27', '_i28', '_i29', '_i3', '_i30', '_i31', '_i32', '_
i33', '_i34', '_i35', '_i36', '_i37', '_i38', '_i39', '_i4', '_i40', '_i41', '_i42', '_i43', '_i44', '_i45', '_i46', '_i47', '_i
48', '_i49', '_i5', '_i50', '_i51', '_i52', '_i53', '_i54', '_i55', '_i56', '_i57', '_i58', '_i59', '_i6', '_i60', '_i61', '_i6
2', '_i63', '_i64', '_i65', '_i66', '_i67', '_i68', '_i69', '_i7', '_i70', '_i71', '_i72', '_i73', '_i74', '_i75', '_i76', '_i7
7', '_i78', '_i79', '_i8', '_i80', '_i81', '_i82', '_i83', '_i84', '_i85', '_i86', '_i87', '_i88', '_i89', '_i9', '_i90', '_i9
1', '_i92', '_i93', '_i94', '_i95', '_i96', '_i97', '_i98', '_i99', '_ih', '_ii', '_iii', '_oh', 'ba', 'count', 'dict_1', 'dict_
2', 'divided_nums', 'division', 'division_number_iterator', 'exit', 'file', 'float_num', 'frozen_nlis', 'function',
'get_ipython', 'i', 'int_num', 'msg', 'mv', 'name', 'nlis', 'num', 'number', 'os', 'path', 'python', 'quit', 'specia
l_numbers', 'special_nums', 'special_nums_dict', 'special_nums_iter', 'special_nums_set', 'special_nums
_tuple', 'sys', 'text', 'txt']
divmod()
It returns the quotient and the remainder when argument1 is divided by argument2.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 25/35
7.06.2022 01:23 11. built_in_functions_python - Jupyter Notebook
In [152]:
1 print(divmod(3.14, 0.577))
2 print(divmod(9, 3))
3 print(divmod(12, 5))
4 print(divmod('Hello', 'Python!')) # It returns TypeError.
(5.0, 0.25500000000000034)
(3, 0)
(2, 2)
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_16192/798993378.py in <module>
2 print(divmod(9, 3))
3 print(divmod(12, 5))
set()
It returns a new set object.
In [179]:
1 print(set())
2 print(set('3.15'))
3 print(set('Hello Python!'))
4 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]
5 print(set(special_nums))
6 print(set(range(2, 9)))
7 special_nums_dict = {'Euler constant': 0.577, 'Golden ratio': 1.618, 'Euler number': 2.718, 'Pi number': 3.14, 'Perfect n
8 print(set(special_nums_dict))
set()
{' ', 'o', 't', 'e', 'n', 'y', 'P', 'h', '!', 'H', 'l'}
{2, 3, 4, 5, 6, 7, 8}
{'Pi number', 'Euler number', 'Euler constant', 'Golden ratio', 'Perfect number'}
setattr()
Sets an attribute (property/method) of an object
In [195]:
1 class SpecialNumbers:
2 euler_constant = 0.0
3 euler_number = 0.0
4 pi = 0.0
5 golden_ratio = 0.0
6 msg = ''
7
8 def __init__(self, euler_constant, euler_number, pi, golden_ratio, msg):
9 self.euler_constant = euler_constant
10 self.euler_number = euler_number
11 self.pi = pi
12 self.golden_ratio = golden_ratio
13 self.msg = msg
14
15 special_numbers = SpecialNumbers(0.577, 2.718, 3.14, 1.618, 'These numbers are special.')
16 print(special_numbers.euler_constant)
17 print(special_numbers.euler_number)
18 print(special_numbers.pi)
19 print(special_numbers.golden_ratio)
20 print(special_numbers.msg)
21 setattr(special_numbers, 'Ramanujan_Hardy_number', 1729)
22 print(special_numbers.Ramanujan_Hardy_number)
0.577
2.718
3.14
1.618
1729
slice()
Returns a slice object that is used to slice any sequence (string, tuple, list, range, or bytes).
In [210]:
1 print(slice(2.718))
2 print(slice(0.577, 1.618, 3.14))
3 msg = 'Hello, Python!'
4 sliced_msg = slice(5)
5 print(msg[sliced_msg])
6 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]
7 sliced_list = slice(4)
8 print(special_nums[sliced_list])
9 sliced_list = slice(-1, -6, -2)
10 print(special_nums[sliced_list])
11 print(special_nums[0:4]) # Slicing with indexing
12 print(special_nums[-4:-1])
Hello
sorted()
Returns a sorted list
In [213]:
[' ', '!', ',', 'H', 'P', 'e', 'h', 'l', 'l', 'n', 'o', 'o', 't', 'y']
ord()
Convert an integer representing the Unicode of the specified character
1 print(ord('9'))
2 print(ord('X'))
3 print(ord('W'))
4 print(ord('^'))
57
88
87
94
pow()
The pow() function returns the power of a number.
In [247]:
1 print(pow(2.718, 3.14))
2 print(pow(-25, -2))
3 print(pow(16, 3))
4 print(pow(-6, 2))
5 print(pow(6, -2))
23.09634618919156
0.0016
4096
36
0.027777777777777776
print()
It prints the given object to the standard output device (screen) or to the text stream file.
In [248]:
Hello, Python!
range()
Returns a sequence of numbers between the given start integer to the stop integer.
In [254]:
1 print(list(range(0)))
2 print(list(range(9)))
3 print(list(range(2, 9)))
4 for i in range(2, 9):
5 print(i)
[]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[2, 3, 4, 5, 6, 7, 8]
reversed()
Returns the reversed iterator of the given sequence.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 29/35
7.06.2022 01:23 11. built_in_functions_python - Jupyter Notebook
In [260]:
1 txt = 'Python'
2 print(list(reversed(txt)))
3 special_nums = [2.718, 1729, 0.577, 1.618, 28, 3.14, 6, 37]
4 print(list(reversed(special_nums)))
5 nums = range(6, 28)
6 print(list(reversed(nums)))
7 special_nums_tuple = (2.718, 1729, 0.577, 1.618, 28, 3.14, 6, 37)
8 print(list(reversed(special_nums_tuple)))
[27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6]
round()
Returns a floating-point number rounded to the specified number of decimals.
In [261]:
1 print(round(3.14))
2 print(round(2.718))
3 print(round(0.577))
4 print(round(1.618))
5 print(round(1729))
1729
str()
Returns the string version of the given object.
In [268]:
1 num = 3.14
2 val = str(num)
3 print(val)
4 print(type(val))
3.14
<class 'str'>
tuple()
The tuple() builtin can be used to create tuples in Python.
In Python, a tuple is an immutable sequence type.
One of the ways of creating tuple is by using the tuple() construct.
In [271]:
('H', 'e', 'l', 'l', 'o', ',', ' ', 'P', 'y', 't', 'h', 'o', 'n', '!')
type()
It either returns the type of the object or returns a new type object based on the arguments passed.
In [276]:
<class 'list'>
('H', 'e', 'l', 'l', 'o', ',', ' ', 'P', 'y', 't', 'h', 'o', 'n', '!')
<class 'str'>
<class 'dict'>
<class 'set'>
<class '__main__.SpecialNumbers'>
vars()
The vars() function returns the dict attribute of the given object.
In [277]:
1 class SpecialNumbers:
2 euler_constant = 0.577
3 euler_number = 2.718
4 pi = 3.14
5 golden_ratio = 1.618
6 msg = 'These numbers are very special'
7
8 def __init__(self, euler_constant, euler_number, pi, golden_ratio, msg):
9 self.euler_constant = euler_constant
10 self.euler_number = euler_number
11 self.pi = pi
12 self.golden_ratio = golden_ratio
13 self.msg = msg
14
15 special_numbers = SpecialNumbers(0.577, 2.718, 3.14, 1.618, 'These numbers are very special.')
16 print(vars(special_numbers))
{'euler_constant': 0.577, 'euler_number': 2.718, 'pi': 3.14, 'golden_ratio': 1.618, 'msg': 'These numbers a
re very special.'}
zip()
It takes iterables (can be zero or more), aggregates them in a tuple, and returns it.
In [283]:
[]
{('Pi number', 3.14), ('Perfect number', 28), ('Euler number', 2.718), ('Euler constant', 0.577), ('Ramanuja
n-Hardy number', 1729), ('Golden ratio', 1.618), ('Prime number', 37)}
super()
Returns a proxy object (temporary object of the superclass) that allows us to access methods of the base class.
In [292]:
1 class SpecialNumbers(object):
2 def __init__(self, special_numbers):
3 print('6 and 28 are', special_numbers)
4
5 class PerfectNumbers(SpecialNumbers):
6 def __init__(self):
7
8 # call superclass
9 super().__init__('perfect numbers.')
10 print('These numbers are very special in mathematik.')
11
12 nums = PerfectNumbers()
In [294]:
1 class Animal(object):
2 def __init__(self, AnimalName):
3 print(AnimalName, 'lives in a farm.')
4
5 class Cow(Animal):
6 def __init__(self):
7 print('Cow gives us milk.')
8 super().__init__('Cow')
9
10 result = Cow()
import()
It is a function that is called by the import statement.
In [303]:
3.14
2.718
64.0
0.006737946999085467
0.999896315728952
720
In [304]:
1 import math
2 print(math.fabs(3.14))
3 print(math.fabs(-2.718))
4 print(math.pow(4, 3))
5 print(math.exp(-5))
6 print(math.log(2.718))
7 print(math.factorial(6))
3.14
2.718
64.0
0.006737946999085467
0.999896315728952
720
Python Tutorial
Created by Mustafa Germec
Create a class
In [40]:
1 class Data:
2 num = 3.14
3
4 print(Data)
<class '__main__.Data'>
Create an object
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 1/15
8.06.2022 01:57 12. classes_objects_python - Jupyter Notebook
Create an object
In [41]:
1 class Data:
2 num = 3.14
3
4 var = Data()
5 print(var.num)
3.14
Function init()
In [43]:
1 class Data:
2 def __init__(self, euler_number, pi_number, golden_ratio):
3 self.euler_number = euler_number
4 self.pi_number = pi_number
5 self.golden_ratio = golden_ratio
6
7 val = Data(2.718, 3.14, 1.618)
8
9 print(val.euler_number)
10 print(val.golden_ratio)
11 print(val.pi_number)
2.718
1.618
3.14
Methods
In [45]:
1 class Data:
2 def __init__(self, euler_number, pi_number, golden_ratio):
3 self.euler_number = euler_number
4 self.pi_number = pi_number
5 self.golden_ratio = golden_ratio
6 def msg_function(self):
7 print("The euler number is", self.euler_number)
8 print("The golden ratio is", self.golden_ratio)
9 print("The pi number is", self.pi_number)
10
11 val = Data(2.718, 3.14, 1.618)
12 val.msg_function()
Self parameter
The self parameter is a reference to the current instance of the class, and is used to access variables that
belongs to the class.
It does not have to be named self, you can call it whatever you like, but it has to be the first parameter of
any function in the class.
Check the following example:
In [46]:
1 """
2 The following codes are the same as the above codes under the title 'Methods'.
3 You see that the output is the same, but this codes contain 'classFirstParameter' instead of 'self'.
4 """
5 class Data:
6 def __init__(classFirstParameter, euler_number, pi_number, golden_ratio):
7 classFirstParameter.euler_number = euler_number
8 classFirstParameter.pi_number = pi_number
9 classFirstParameter.golden_ratio = golden_ratio
10
11 def msg_function(classFirstParameter):
12 print("The euler number is", classFirstParameter.euler_number)
13 print("The golden ratio is", classFirstParameter.golden_ratio)
14 print("The pi number is", classFirstParameter.pi_number)
15
16 val = Data(2.718, 3.14, 1.618)
17 val.msg_function()
In [1]:
20
10
In [3]:
60 one_Circle.increase_radius(30)
61 print('Increase the radius by 30 units: ', one_Circle.radius)
62 one_Circle.drawCircle()
3.14
blue
100
yellow
Before increment: 15
Some examples
In [36]:
1 class SpecialNumbers:
2 euler_constant = 0.577
3 euler_number = 2.718
4 pi_number = 3.14
5 golden_ratio = 1.618
6 msg = 'These numbers are special.'
7
8 special_numbers = SpecialNumbers()
9 print('The euler number is', getattr(special_numbers, 'euler_number'))
10 print('The golden ratio is', special_numbers.golden_ratio)
11 print('The pi number is', getattr(special_numbers, 'pi_number'))
12 print('The message is ', getattr(special_numbers, 'msg'))
In [37]:
1 class SpecialNumbers:
2 euler_constant = 0.577
3 euler_number = 2.718
4 pi = 3.14
5 golden_ratio = 1.618
6 msg = 'These numbers are special.'
7
8 def parameter(self):
9 print(self.euler_constant, self.euler_number, self.pi, self.golden_ratio, self.msg)
10
11 special_numbers = SpecialNumbers()
12 special_numbers.parameter()
13 delattr(SpecialNumbers, 'msg') # The code deleted the 'msg'.
14 special_numbers.parameter() # Since the code deleted the 'msg', it returns an AttributeError.
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_15364/3719874998.py in <module>
12 special_numbers.parameter()
---> 14 special_numbers.parameter() # Since the code deleted the 'msg', it returns an AttributeErr
or.
~\AppData\Local\Temp/ipykernel_15364/3719874998.py in parameter(self)
8 def parameter(self):
10
11 special_numbers = SpecialNumbers()
In [39]:
1 class ComplexNum:
2 def __init__(self, a, b):
3 self.a = a
4 self.b = b
5
6 def data(self):
7 print(f'{self.a}-{self.b}j')
8
9 var = ComplexNum(3.14, 1.618)
10 var.data()
3.14-1.618j
In [54]:
1 class Data:
2 def __init__(self, genus, species):
3 self.genus = genus
4 self.species = species
5
6 def microorganism(self):
7 print(f'The name of a microorganism is in the form of {self.genus} {self.species}.')
8
9 #Use the Data class to create an object, and then execute the microorganism method
10 value = Data('Aspergillus', 'niger')
11 value.microorganism()
In [56]:
1 class Data:
2 def __init__(self, genus, species):
3 self.genus = genus
4 self.species = species
5
6 def microorganism(self):
7 print(f'The name of a microorganism is in the form of {self.genus} {self.species}.')
8
9 class Recombinant(Data):
10 pass
11
12 value = Recombinant('Aspergillus', 'sojae')
13 value.microorganism()
In [4]:
1 class Data:
2 def __init__(self, genus, species):
3 self.genus = genus
4 self.species = species
5
6 def microorganism(self):
7 print(f'The name of a microorganism is in the form of {self.genus} {self.species}.')
8
9 class Recombinant(Data):
10 def __init__(self, genus, species):
11 Data.__init__(self, genus, species)
12
13 value = Recombinant('Aspergillus', 'sojae')
14 value.microorganism()
In [68]:
1 class SpecialNumbers(object):
2 def __init__(self, special_numbers):
3 print('6 and 28 are', special_numbers)
4
5 class PerfectNumbers(SpecialNumbers):
6 def __init__(self):
7
8 # call superclass
9 super().__init__('perfect numbers.')
10 print('These numbers are very special in mathematik.')
11
12 nums = PerfectNumbers()
In [71]:
1 class Animal(object):
2 def __init__(self, AnimalName):
3 print(AnimalName, 'lives in a farm.')
4
5 class Cow(Animal):
6 def __init__(self):
7 print('Cow gives us milk.')
8 super().__init__('Cow')
9
10 result = Cow()
In [60]:
1 class Data:
2 def __init__(self, genus, species):
3 self.genus = genus
4 self.species = species
5
6 def microorganism(self):
7 print(f'The name of a microorganism is in the form of {self.genus} {self.species}.')
8
9 class Recombinant(Data):
10 def __init__(self, genus, species):
11 super().__init__(genus, species) # 'self' statement in this line was deleted as different from the above codes
12
13 value = Recombinant('Aspergillus', 'sojae')
14 value.microorganism()
In [65]:
1 class Data:
2 def __init__(self, genus, species):
3 self.genus = genus
4 self.species = species
5
6 def microorganism(self):
7 print(f'The name of a microorganism is in the form of {self.genus} {self.species}.')
8
9 class Recombinant(Data):
10 def __init__(self, genus, species):
11 super().__init__(genus, species)
12 self.activity = 2500 # This information was adedd as a Property
13
14 value = Recombinant('Aspergillus', 'sojae')
15 print(f'The enzyme activity increased to {value.activity} U/mL.')
In [66]:
1 class Data:
2 def __init__(self, genus, species):
3 self.genus = genus
4 self.species = species
5
6 def microorganism(self):
7 print(f'The name of a microorganism is in the form of {self.genus} {self.species}.')
8
9 class Recombinant(Data):
10 def __init__(self, genus, species, activity):
11 super().__init__(genus, species)
12 self.activity = activity # This information was adedd as a Property
13
14 value = Recombinant('Aspergillus', 'sojae', 2500)
15 print(f'The enzyme activity increased to {value.activity} U/mL.')
In [67]:
1 class Data:
2 def __init__(self, genus, species):
3 self.genus = genus
4 self.species = species
5
6 def microorganism(self):
7 print(f'The name of a microorganism is in the form of {self.genus} {self.species}.')
8
9 class Recombinant(Data):
10 def __init__(self, genus, species, activity):
11 super().__init__(genus, species)
12 self.activity = activity # This information was adedd as a Property
13
14 def increment(self):
15 print(f'With this new recombinant {self.genus} {self.species} strain, the enzyme activity increased 2-times with {se
16
17 value = Recombinant('Aspergillus', 'sojae', 2500)
18 value.increment()
With this new recombinant Aspergillus sojae strain, the enzyme activity increased 2-times with 2500 U/
mL.
Python Tutorial
Created by Mustafa Germec, PhD
First, open a text file for reading by using the open() function
Second, read text from the text file using the file read(), readline(), or readlines() method of the file object.
Third, close the file using the file close() method. This frees up resources and ensures consistency across
different python versions.
Reading file
In [2]:
Out[2]:
'I dedicate this book to Nancy Lier Cosgrove Mullis.\nJean-Paul Sartre somewhere observed that we eac
h 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 lucky, and make his own heaven out of one of the peopl
e around him. She will be his morning and his evening star, shining with the brightest and the softest lig
ht in his heaven. She will be the end of his wanderings, and their love will arouse the daffodils in the spri
ng to follow the crocuses and precede the irises. Their faith in one another will be deeper than time and
their eternal spirit will be seamless once again.\nOr maybe he would have just said, “If I’d had a woman
like that, my books would not have been about despair.”\nThis book is not about despair. It is about a litt
le bit of a lot of things, and, if not a single one of them is wet with sadness, it is not due to my lack of de
pth; it is due to a year of Nancy, and the prospect of never again being without her.\n\n'
In [3]:
pcr_file.txt
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.
Or maybe he would have just said, “If I’d had a woman like that, my books would not have been about d
espair.”
This book is not about despair. It is about a little bit of a lot of things, and, if not a single one of them is
wet with sadness, it is not due to my lack of depth; it is due to a year of Nancy, and the prospect of neve
r again being without her.
<class 'str'>
In [4]:
In [5]:
Out[5]:
True
In [6]:
1 fname = 'pcr_file.txt'
2 with open(fname, 'r') as f:
3 content = f.read()
4 print(content)
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.
Or maybe he would have just said, “If I’d had a woman like that, my books would not have been about d
espair.”
This book is not about despair. It is about a little bit of a lot of things, and, if not a single one of them is
wet with sadness, it is not due to my lack of depth; it is due to a year of Nancy, and the prospect of neve
r again being without her.
In [7]:
Out[7]:
True
In [8]:
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.
Or maybe he would have just said, “If I’d had a woman like that, my books would not have been about d
espair.”
This book is not about despair. It is about a little bit of a lot of things, and, if not a single one of them is
wet with sadness, it is not due to my lack of depth; it is due to a year of Nancy, and the prospect of neve
r again being without her.
In [9]:
In [10]:
ove Mullis.
at we each of us make our own hell out of the people around us. Had Jean-Paul known Nancy, he may h
a
In [11]:
The first line is: I dedicate this book to Nancy Lier Cosgrove Mullis.
In [12]:
In [13]:
Line number 2 : 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, mig
ht get very lucky, and make his own heaven out of one of the people around him. She will be his mornin
g 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 preced
e the irises. Their faith in one another will be deeper than time and their eternal spirit will be seamless o
nce again.
Line number 3 : Or maybe he would have just said, “If I’d had a woman like that, my books would not ha
ve been about despair.”
Line number 4 : This book is not about despair. It is about a little bit of a lot of things, and, if not a single
one of them is wet with sadness, it is not due to my lack of depth; it is due to a year of Nancy, and the pr
ospect of never again being without her.
Line number 5 :
Methods
read(n) function
Reads atmost n bytes from the file if n is specified, else reads the entire file.
Returns the retrieved bytes in the form of a string.
In [14]:
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.
Or maybe he would have just said, “If I’d had a woman like that, my books would not have been about d
espair.”
This book is not about despair. It is about a little bit of a lot of things, and, if not a single one of them is
wet with sadness, it is not due to my lack of depth; it is due to a year of Nancy, and the prospect of neve
r again being without her.
In [15]:
readline() function
Reads one line at a time from the file in the form of string
In [16]:
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.
Or maybe he would have just said, “If I’d had a woman like that, my books would not have been about d
espair.”
This book is not about despair. It is about a little bit of a lot of things, and, if not a single one of them is
wet with sadness, it is not due to my lack of depth; it is due to a year of Nancy, and the prospect of neve
r again being without her.
readlines() function
Reads all the lines from the file and returns a list of lines.
In [17]:
['I dedicate this book to Nancy Lier Cosgrove Mullis.\n', 'Jean-Paul Sartre somewhere observed that we e
ach of us make our own hell out of the people around us. Had Jean-Paul known Nancy, he may have not
ed that at least one man, someday, might get very lucky, and make his own heaven out of one of the pe
ople 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 s
pring to follow the crocuses and precede the irises. Their faith in one another will be deeper than time a
nd their eternal spirit will be seamless once again.\n', 'Or maybe he would have just said, “If I’d had a wo
man like that, my books would not have been about despair.”\n', 'This book is not about despair. It is ab
out a little bit of a lot of things, and, if not a single one of them is wet with sadness, it is not due to my la
ck of depth; it is due to a year of Nancy, and the prospect of never again being without her.\n', '\n']
strip() function
Removes the leading and trailing spaces from the given string.
In [18]:
The length of the line after removing leading and trailing spaces is 1024.
In [19]:
In [20]:
Python Tutorial
Created by Mustafa Germec, PhD
First, open the text file for writing (or appending) using the open() function.
Second, write to the text file using the write() or writelines() method.
Third, close the file using the close() method.
Writing files
In [17]:
In [18]:
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.
Or maybe he would have just said, 'If I would had a woman like that, my books would not have been abo
ut despair.
'This book is not about despair. It is about a little bit of a lot of things, and, if not a single one of them is
wet with sadness, it is not due to my lack of depth; it is due to a year of Nancy, and the prospect of neve
r again being without her.
This bona-fide wild card of the scientific community writes with eccentric gusto.… Mullis has created a fr
ee-wheeling adventure yarn that just happens to be the story of his life.
In [20]:
Entertaini ng … [Mullis is] usefully cranky and combative, raising provocative questions about received tr
uths from the scientific establishment.
One of the most unusual scientists of our times, a man who would be a joy to put under a microscope.
In this entertaining romp through diverse fields of inquiry, [Mullis] displays the openmindedness, eccent
ricity, brilliance, and general curmudgeonliness that make him the colorful chracter he is. His stories are
engaging, informative, and fun.
Appending files
In [24]:
Overright
In [25]:
Overright
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.
Or maybe he would have just said, 'If I would had a woman like that, my books would not have been abo
ut despair.
'This book is not about despair. It is about a little bit of a lot of things, and, if not a single one of them is
wet with sadness, it is not due to my lack of depth; it is due to a year of Nancy, and the prospect of neve
r again being without her.
This bona-fide wild card of the scientific community writes with eccentric gusto.… Mullis has created a fr
ee-wheeling adventure yarn that just happens to be the story of his life.
Other modes
a+
In [8]:
1 fname = 'pcr_file.txt'
2 with open(fname, 'a+') as f:
3 f.write("From F. Lee Bailey\n")
4 f.write("A very good book by a fascinating man.… [Mullis] enjoys an almost frighteningly brilliant mind and yet some
5 print(f.read())
In [9]:
Overright
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.
Or maybe he would have just said, 'If I would had a woman like that, my books would not have been abo
ut despair.
'This book is not about despair. It is about a little bit of a lot of things, and, if not a single one of them is
wet with sadness, it is not due to my lack of depth; it is due to a year of Nancy, and the prospect of neve
r again being without her.
This bona-fide wild card of the scientific community writes with eccentric gusto.… Mullis has created a fr
ee-wheeling adventure yarn that just happens to be the story of his life.
A very good book by a fascinating man.… [Mullis] enjoys an almost frighteningly brilliant mind and yet so
mehow manages to keep his feet firmly on the ground.… This guy cuts through the nonsense to the quic
k, tells it like it is, and manages to do so with insouciance [and] occasional puckishness.… But lighter mo
ments aside, what he has to say is important.
In [10]:
Read nothing.
Second location: 0
Overright
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.
Or maybe he would have just said, 'If I would had a woman like that, my books would not have been abo
ut despair.
'This book is not about despair. It is about a little bit of a lot of things, and, if not a single one of them is
wet with sadness, it is not due to my lack of depth; it is due to a year of Nancy, and the prospect of neve
r again being without her.
This bona-fide wild card of the scientific community writes with eccentric gusto.… Mullis has created a fr
ee-wheeling adventure yarn that just happens to be the story of his life.
A very good book by a fascinating man.… [Mullis] enjoys an almost frighteningly brilliant mind and yet so
mehow manages to keep his feet firmly on the ground.… This guy cuts through the nonsense to the quic
k, tells it like it is, and manages to do so with insouciance [and] occasional puckishness.… But lighter mo
ments aside, what he has to say is important.
r+
In [13]:
To my family...
...
s 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 lucky, and make his own heaven out of one of the people aro
und 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 faith in one another will be deeper than time and their
eternal spirit will be seamless once again.
Or maybe he would have just said, 'If I would had a woman like that, my books would not have been abo
ut despair.
'This book is not about despair. It is about a little bit of a lot of things, and, if not a single one of them is
wet with sadness, it is not due to my lack of depth; it is due to a year of Nancy, and the prospect of neve
r again being without her.
This bona-fide wild card of the scientific community writes with eccentric gusto.… Mullis has created a fr
ee-wheeling adventure yarn that just happens to be the story of his life.
A very good book by a fascinating man.… [Mullis] enjoys an almost frighteningly brilliant mind and yet so
mehow manages to keep his feet firmly on the ground.… This guy cuts through the nonsense to the quic
k, tells it like it is, and manages to do so with insouciance [and] occasional puckishness.… But lighter mo
ments aside, what he has to say is important.
In [14]:
In [15]:
To my family...
...
s 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 lucky, and make his own heaven out of one of the people aro
und 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 faith in one another will be deeper than time and their
eternal spirit will be seamless once again.
Or maybe he would have just said, 'If I would had a woman like that, my books would not have been abo
ut despair.
'This book is not about despair. It is about a little bit of a lot of things, and, if not a single one of them is
wet with sadness, it is not due to my lack of depth; it is due to a year of Nancy, and the prospect of neve
r again being without her.
This bona-fide wild card of the scientific community writes with eccentric gusto.… Mullis has created a fr
ee-wheeling adventure yarn that just happens to be the story of his life.
A very good book by a fascinating man.… [Mullis] enjoys an almost frighteningly brilliant mind and yet so
mehow manages to keep his feet firmly on the ground.… This guy cuts through the nonsense to the quic
k, tells it like it is, and manages to do so with insouciance [and] occasional puckishness.… But lighter mo
ments aside, what he has to say is important.
Some examples
In [36]:
Daniela
Axel
Leonardo
In [40]:
Daniel
Axel
Leonardo
In [41]:
Hello, World!
Hi, Python!
In [43]:
Hello, World!
Hi, Python!
Hi, Sun!
Hello, Summer!
Hello, Summer!
Hi, See!
Python Tutorial
Created by Mustafa Germec
In [1]:
1 string_hello = 'Hello'
2 string_python = 'Python!'
3 print(string_hello)
4 print(string_python)
Hello
Python!
Deleting the items in a string is not supported since strings are immutable
It returns a TypeError. However, the whole string can be deleted. When it is, it returns a NameError.
In [6]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_18660/4179913587.py in <module>
2 print(text)
4 print(text)
In [7]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_18660/1747540232.py in <module>
2 print(text)
3 del text
----> 4 print(text)
Concetanation of strings
It combines two or more strings using the sign '+' to form a new string.
In [9]:
Hello Python!
Appending (+=) adds a new string the the end of the current string
In [10]:
Hello Python!
In [12]:
In [21]:
Hello
Python!
Python
Striding in slicing
The third parameter specifies the stride, which refers to how many characters to move forward after the first
character is retrieved from the string.
In [29]:
14
Hello, Python!
Hlo yhn
Hl tn
Reverse string
The stride value is equal to -1 if a reverse string is wanted to obtain
In [30]:
!nohtyP ,olleH
in and not in
in returns True when the character or word is in the given string, otherwise False.
not in returns False when the character or word is in the given string, otherwise True.
In [130]:
True
False
True
False
capitalize() function
It converts the first character of the string into uppercase.
In [31]:
casefold() function
It converts the characters in the certain string into lowercase.
In [32]:
center() function
It will center align the string, using a specified character (space is default) as the fill character.
In [43]:
count() function
It returns the number of a certain characters in a string.
In [45]:
endswith() function
It returns True if the strings ends with a certain value.
In [49]:
True
False
find() function
It investigates the string for a certain value and returns the position of where it was found.
In [62]:
-1
format() function
It formats the specified value(s) and insert them inside the string's placeholder.
The placeholder is defined using curly brackets: {}.
In [66]:
index() function
It examines the string for a certain value and returns the position of where it was found.
In [71]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_18660/3544138795.py in <module>
2 print(text.index('Python!'))
3 print(text.index('Hello'))
isalnum() function
It returns True if all characters in the string are alphanumeric.
In [76]:
False
True
isalpha() function
It returns True if all characters in the string are alphabets.
White spaces are not considered as alphabets and thus it returns False.
In [80]:
1 text = 'Hello'
2 print(text.isalpha())
3 text = 'Hello1358' # The text contains numbers.
4 print(text.isalpha())
5 text = 'Hello Python!' # The text contains a white space.
6 print(text.isalpha())
True
False
False
isdecimal() function
It returns True if all the characters in the given string are decimal numbers ( 0-9).
localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebook_files/15. Strings Ope… 8/14
20.06.2022 16:06 15. Strings Operators and Functions in Python - Jupyter Notebook
In [82]:
1 text = 'Hello'
2 print(text.isdecimal())
3 numbered_text = '011235813'
4 print(numbered_text.isdecimal())
False
True
isdigit() function
This function returns True if all the characters in the string and the Unicode characters are digits.
In [83]:
1 numbered_text = '011235813'
2 print(numbered_text.isdigit())
True
isidentifier() function
It returns True if the string is a valid identifier, on the contrary False.
In [85]:
1 numbered_text = '011235813'
2 print(numbered_text.isidentifier())
3 variable = 'numbered_text'
4 print(variable.isidentifier())
False
True
isprintable() function
It returns True if all the characters in the string are printable features.
In [89]:
True
False
True
isspace() function
localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebook_files/15. Strings Ope… 9/14
20.06.2022 16:06 15. Strings Operators and Functions in Python - Jupyter Notebook
p ()
It returns True if all the characters in the string are whitespaces.
In [90]:
False
True
In [94]:
False
True
In [95]:
False
True
join() function
It takes all items in an iterable and joins them into one string.
A string must be specified as the separator.
In [100]:
Hello#World#Hi#Python
Hello+World+Hi+Python
Hello--Python--Hi--World
val1--val2--val3--val4
ljust() function
It returns the left justified version of the certain string.
In [119]:
1 text = 'Python'
2 text = text.ljust(30, '-')
3 print(text, 'is my favorite programming language.')
rjust() function
It returns the right justified version of the certain string.
In [120]:
1 text = 'Python'
2 text = text.rjust(30, '-')
3 print(text, 'is my favorite programming language.')
lstrip() function
It removes characters from the left based on the argument (a string specifying the set of characters to be
removed).
In [103]:
Hello Python!
rstrip() function
localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebook_files/15. Strings Op… 11/14
20.06.2022 16:06 15. Strings Operators and Functions in Python - Jupyter Notebook
It removes characters from the right based on the argument (a string specifying the set of characters to be
removed).
In [104]:
Hello Python!
strip() function
It removes or truncates the given characters from the beginning and the end of the original string.
The default behavior of the strip() method is to remove the whitespace from the beginning and at the end
of the string.
In [105]:
Hello Python!
replace() function
Replaces a specified phrase with another specified phrase.
In [106]:
In [107]:
partition() function
It searches for a specified string, and splits the string into a tuple containing three elements.
The first element contains the part before the specified string.
The second element contains the specified string.
The third element contains the part after the string.
localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebook_files/15. Strings Op… 12/14
20.06.2022 16:06 15. Strings Operators and Functions in Python - Jupyter Notebook
In [114]:
rfind() function
The rfind() method finds the last occurrence of the specified value.
The rfind() method returns -1 if the value is not found.
The rfind() method is almost the same as the rindex() method.
In [125]:
rindex() function
The rindex() method finds the last occurrence of the specified value.
The rindex() method raises a ValueError exception if the value is not found.
The rindex() method is almost the same as the rfind() method.
In [126]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_18660/2547564577.py in <module>
swapcase() function
This function converts the uppercase characters into lowercase and vice versa.
localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebook_files/15. Strings Op… 13/14
20.06.2022 16:06 15. Strings Operators and Functions in Python - Jupyter Notebook
In [116]:
hELLO pYTHON!
Hello Python!
title() function
This function converts the first character in the given string into uppercase.
In [117]:
Python Tutorial
Created by Mustafa Germec, PhD
Creating an array
You should import the module name 'array' as follows:
In [4]:
In [5]:
1 # To access more information regarding array, you can execute the following commands
2 help(arr)
NAME
array
DESCRIPTION
numbers. Arrays are sequence types and behave very much like lists,
CLASSES
builtins.object
array
Type code
Arrays represent basic values and behave very much like lists, except the type of objects stored in them is
constrained.
The type is specified at object creation time by using a type code, which is a single character.
The following type codes are defined:
In [6]:
0.577
1.618
2.718
3.14
6.0
37.0
1729.0
Accessing
In [7]:
Changing or Updating
In [8]:
Deleting
In [9]:
In [10]:
Concatenation
In [11]:
The new array called special_fibonacci_nums is array('d', [0.577, 1.618, 2.718, 3.14, 6.0, 37.0, 1729.0, 1.
0, 1.0, 2.0, 3.0, 5.0, 8.0, 13.0, 21.0, 34.0]).
Creating ID arrays
In [12]:
1 mult = 10
2 one_array = [1]*mult
3 print(one_array)
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
In [13]:
1 mult = 10
2 nums_array = [i for i in range(mult)]
3 print(nums_array)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [14]:
1 1 2 3 5 8 13 21 34
1 1 2 3 5 8 13 21 34 55
1 1 2 3 5 8 13 21 34 55 89
In [15]:
1 1 2 3 5 8 13 21 34
1 1 2 3 5 8 13 21 34 55
1 1 2 3 5 8 13 21 34 55 89
In [16]:
In [17]:
After removing one more element using index from the array
Slicing
In [18]:
In [19]:
In [20]:
In [21]:
In [22]:
Searching
In [23]:
Copying
In [24]:
array('d', [0.577, 1.618, 2.718, 3.14, 6.0, 37.0, 1729.0]) with the ID number 2668250199472
array('d', [0.577, 1.618, 2.718, 3.14, 6.0, 37.0, 1729.0]) with the ID number 2668250199472
In [25]:
[5.770e-01 1.618e+00 2.718e+00 3.140e+00 6.000e+00 3.700e+01 1.729e+03] with the ID number 2668
248532144
[5.770e-01 1.618e+00 2.718e+00 3.140e+00 6.000e+00 3.700e+01 1.729e+03] with the ID number 2668
254732400
In [26]:
[5.770e-01 1.618e+00 2.718e+00 3.140e+00 6.000e+00 3.700e+01 1.729e+03] with the ID number 2668
254735376
[5.770e-01 1.618e+00 2.718e+00 3.140e+00 6.000e+00 3.700e+01 1.729e+03] with the ID number 2668
254736144
Python Tutorial
Created by Mustafa Germec, PhD
In [1]:
9.14
Out[1]:
9.14
In [2]:
In [3]:
Multiplication table
In [4]:
1 def mult_table(n):
2 return lambda x:x*n
3
4 n = int(input('Enter a number: '))
5 y = mult_table(n)
6
7 print(f'The entered number is {n}.')
8 for i in range(11):
9 print(('%d x %d = %d' %(n, i, y(i))))
Enter a number: 6
6 x 0 = 0
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60
filter()
In [5]:
1 # This program returns a new list when the special numbers in the list are divided by 2 and the remainder is equal to 0
2 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]
3 list(filter(lambda x:(x%2==0), special_nums))
Out[5]:
[6, 28]
map()
In [6]:
1 # This program will multiplicate each element of the list with 5 and followed by power of 2.
2 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]
3 print(f'Non special numbers are {list(map(lambda x: x*5, special_nums))}')
4 print(f'Non special numbers list is {list(map(lambda x: pow(x, 2), special_nums))}')
Non special numbers are [2.885, 8.09, 13.59, 15.700000000000001, 30, 140, 185, 8645]
Non special numbers list is [0.332929, 2.6179240000000004, 7.387524, 9.8596, 36, 784, 1369, 298944
1]
List comprehensions
In [7]:
In [8]:
Enter an age: 18
In [9]:
Some examples
In [10]:
1 def func(n):
2 return lambda x: x*n
3
4 mult_pi_number = func(3.14)
5 mult_euler_constant = func(0.577)
6
7 print(f'The multiplication of euler number and pi number is equal to {mult_pi_number(2.718)}.')
8 print(f'The multiplication of euler number and euler constant is equal to {mult_euler_constant(2.718)}.')
In [11]:
In [12]:
In [13]:
1 lambda_list = []
2 # Multiplication of pi number and 12 in one line using lambda function
3 lambda_list.append((lambda x:x*3.14) (12))
4 # Division of pi number and 12 in one line using lambda function
5 lambda_list.append((lambda x: x/3.14) (12))
6 # Addition of pi number and 12 in one line using lambda function
7 lambda_list.append((lambda x: x+3.14) (12))
8 # Subtraction of pi number and 12 in one line using lambda function
9 lambda_list.append((lambda x: x-3.14) (12))
10 # Remainder of pi number and 12 in one line using lambda function
11 lambda_list.append((lambda x: x%3.14) (12))
12 # Floor division of pi number and 12 in one line using lambda function
13 lambda_list.append((lambda x: x//3.14) (12))
14 # Exponential of pi number and 12 in one line using lambda function
15 lambda_list.append((lambda x: x**3.14) (12))
16
17 # Printing the list
18 print(lambda_list)
In [14]:
1 # Using the function reduce() with lambda to get the sum abd average of the list.
2 # You should import the library 'functools' first.
3 import functools
4 from functools import *
5 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]
6 print(f'The sum and average of the numbers in the list are {reduce((lambda a, b: a+b), special_nums)} and {reduce((la
The sum and average of the numbers in the list are 1808.0529999999999 and 226.00662499999999, res
pectively.
In [15]:
1 import itertools
2 from itertools import product
3 from numpy import sqrt
4 X=[1]
5 X1=[2]
6 Y=[1,2,3]
7 print(list(product(Y,X,X1)))
8 print(list(map(lambda x: sqrt(x[1]+x[0]**x[2]),product(Y,X,X1))))
In [16]:
1 help(functools)
NAME
functools - functools.py - Tools for working with functions and callable objects
MODULE REFERENCE
https://docs.python.org/3.9/library/functools (https://docs.python.org/3.9/library/functools)
CLASSES
builtins.object
cached_property
partial
partialmethod
singledispatchmethod
In [1]:
In [2]:
1 # Many functions regarding math modules in python can be find using helf(math) method.
2 help(math)
NAME
math
DESCRIPTION
FUNCTIONS
acos(x, /)
acosh(x, /)
asin(x, /)
acos() function
Return the arc cosine (measured in radians) of x.
The result is between 0 and pi.
The parameter must be a double value between -1 and 1.
In [54]:
1 nlis = []
2 nlis.append(math.acos(1))
3 nlis.append(math.acos(-1))
4 print(nlis)
[0.0, 3.141592653589793]
acosh() function
It is a built-in method defined under the math module to calculate the hyperbolic arc cosine of the given
parameter in radians.
For example, if x is passed as an acosh function (acosh(x)) parameter, it returns the hyperbolic arc cosine
value.
In [56]:
1 print(math.acosh(1729))
8.148445582615551
asin() function
Return the arc sine (measured in radians) of x.
The result is between -pi/2 and pi/2.
In [52]:
1 nlis = []
2 nlis.append(math.asin(1))
3 nlis.append(math.asin(-1))
4 print(nlis)
5
[1.5707963267948966, -1.5707963267948966]
asinh() function
Return the inverse hyperbolic sine of x.
In [55]:
1 print(math.asinh(1729))
8.1484457498709
atan() function
Return the arc tangent (measured in radians) of x.
The result is between -pi/2 and pi/2.
localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebook_files/18. Math Modul… 2/21
15.06.2022 13:55 18. Math Module Functions in Python - Jupyter Notebook
e esu t s bet ee p/ a dp/
In [66]:
1 nlis = []
2 nlis.append(math.atan(math.inf)) # pozitive infinite
3 nlis.append(math.atan(-math.inf)) # negative infinite
4 print(nlis)
[1.5707963267948966, -1.5707963267948966]
atan2() function
Return the arc tangent (measured in radians) of y/x.
Unlike atan(y/x), the signs of both x and y are considered.
In [74]:
1 print(math.atan2(1729, 37))
2 print(math.atan2(1729, -37))
3 print(math.atan2(-1729, -37))
4 print(math.atan2(-1729, 37))
5 print(math.atan2(math.pi, math.inf))
6 print(math.atan2(math.inf, math.e))
7 print(math.atan2(math.tau, math.pi))
1.5493999395414435
1.5921927140483498
-1.5921927140483498
-1.5493999395414435
0.0
1.5707963267948966
1.1071487177940904
atanh() function
Return the inverse hyperbolic tangent of x.
In [91]:
1 nlis=[]
2 nlis.append(math.atanh(-0.9999))
3 nlis.append(math.atanh(0))
4 nlis.append(math.atanh(0.9999))
5 print(nlis)
6
ceil() function
Rounds a number up to the nearest integer
Returns the smalles integer greater than or equal to variable.
In [22]:
comb() function
Number of ways to choose k items from n items without repetition and without order.
Evaluates to n!/(k!*(n - k)!) when k <= n and evaluates to zero when k>n.
Also called the binomial coefficient because it is equivalent to the coefficient of k-th term in polynomial
expansion of the expression (1 + x)**n.
Raises TypeError if either of the arguments are not integers.
Raises ValueError if either of the arguments are negative.
In [19]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_9084/1573976203.py in <module>
copysign() function
Returns a float consisting of the value of the first parameter and the sign of the second parameter.
In [18]:
1 print(f'The copysign of thes two numbers -3.14 and 2.718 is {math.copysign(-3.14, 2.718)}.')
2 print(f'The copysign of thes two numbers 1729 and -0.577 is {math.copysign(1729, -0.577)}.')
cos() function
Return the cosine of x (measured in radians).
In [105]:
1 print(math.cos(0))
2 print(math.cos(math.pi/6))
3 print(math.cos(-1))
4 print(math.cos(1))
5 print(math.cos(1729))
6 print(math.cos(90))
1.0
0.8660254037844387
0.5403023058681398
0.5403023058681398
0.43204202084333315
-0.4480736161291701
cosh() function
Return the hyperbolic cosine of x.
In [114]:
1 nlis = []
2 nlis.append(math.cosh(1))
3 nlis.append(math.cosh(0))
4 nlis.append(math.cosh(-5))
5 print(nlis)
degrees() function
Convert angle x from radians to degrees.
In [122]:
1 nlis = []
2 nlis.append(math.degrees(math.pi/2))
3 nlis.append(math.degrees(math.pi))
4 nlis.append(math.degrees(math.pi/4))
5 nlis.append(math.degrees(-math.pi))
6 print(nlis)
dist() function
Return the Euclidean distance between two points p and q.
The points should be specified as sequences (or iterables) of coordinates.
Both inputs must have the same dimension.
Roughly equivalent to: sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
In [127]:
1 print(math.dist([30], [60]))
2 print(math.dist([0.577, 1.618], [3.14, 2.718]))
3 x = [0.577, 1.618, 2.718]
4 y = [6, 28, 37]
5 print(math.dist(x, y))
30.0
2.7890803143688783
43.59672438383416
erf() function
Error function at x.
This method accepts a value between - inf and + inf, and returns a value between - 1 to + 1.
In [136]:
1 nlis = []
2 nlis.append(math.erf(math.inf))
3 nlis.append(math.erf(math.pi))
4 nlis.append(math.erf(math.e))
5 nlis.append(math.erf(math.tau))
6 nlis.append(math.erf(0))
7 nlis.append(math.erf(6))
8 nlis.append(math.erf(1.618))
9 nlis.append(math.erf(0.577))
10 nlis.append(math.erf(-math.inf))
11 print(nlis)
erfc() function
Complementary error function at x.
This method accepts a value between - inf and + inf, and returns a value between 0 and 2.
In [137]:
1 nlis = []
2 nlis.append(math.erfc(math.inf))
3 nlis.append(math.erfc(math.pi))
4 nlis.append(math.erfc(math.e))
5 nlis.append(math.erfc(math.tau))
6 nlis.append(math.erfc(0))
7 nlis.append(math.erfc(6))
8 nlis.append(math.erfc(1.618))
9 nlis.append(math.erfc(0.577))
10 nlis.append(math.erfc(-math.inf))
11 print(nlis)
exp() function
The math.exp() method returns E raised to the power of x (Ex).
E is the base of the natural system of logarithms (approximately 2.718282) and x is the number passed to
it.
In [139]:
1 nlis = []
2 nlis.append(math.exp(math.inf))
3 nlis.append(math.exp(math.pi))
4 nlis.append(math.exp(math.e))
5 nlis.append(math.exp(math.tau))
6 nlis.append(math.exp(0))
7 nlis.append(math.exp(6))
8 nlis.append(math.exp(1.618))
9 nlis.append(math.exp(0.577))
10 nlis.append(math.exp(-math.inf))
11 print(nlis)
expm1() function
Return exp(x)-1.
This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
In [141]:
1 nlis = []
2 nlis.append(math.expm1(math.inf))
3 nlis.append(math.expm1(math.pi))
4 nlis.append(math.expm1(math.e))
5 nlis.append(math.expm1(math.tau))
6 nlis.append(math.expm1(0))
7 nlis.append(math.expm1(6))
8 nlis.append(math.expm1(1.618))
9 nlis.append(math.expm1(0.577))
10 nlis.append(math.expm1(-math.inf))
11 print(nlis)
fabs() function
Returns the absolute value of a number
In [14]:
factorial() function
Returns the factorial of a number.
In [28]:
In [29]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_9084/3052214312.py in <module>
----> 2 print(math.factorial(-6))
In [30]:
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_9084/3264451390.py in <module>
----> 2 print(math.factorial(3.14))
floor() functions:
Rounds a number down to the nearest integer
In [34]:
1 print(math.floor(3.14))
fmod() function
Returns the remainder of x/y
In [37]:
1 print(math.fmod(37, 6))
2 print(math.fmod(1728, 37))
1.0
26.0
frexp() function
Returns the mantissa and the exponent, of a specified number
In [31]:
1 print(math.frexp(2.718))
(0.6795, 2)
fsum() function
Returns the sum of all items in any iterable (tuples, arrays, lists, etc.)
In [142]:
1808.053
gamma() function
Returns the gamma function at x.
You can find more information about gamma function from this Link.
(https://en.wikipedia.org/wiki/Gamma_function)
In [143]:
1 print(math.gamma(3.14))
2 print(math.gamma(6))
3 print(math.gamma(2.718))
2.2844806338178008
120.0
1.5671127417668826
gcd() function
Returns the greatest common divisor of two integers
In [144]:
1 print(math.gcd(3, 10))
2 print(math.gcd(4, 8))
3 print(math.gcd(0, 0))
hypot() function
Returns the Euclidean norm.
Multidimensional Euclidean distance from the origin to a point.
Roughly equivalent to: sqrt(sum(x**2 for x in coordinates))
For a two dimensional point (x, y), gives the hypotenuse using the Pythagorean theorem: sqrt(xx + yy).
In [148]:
1 print(math.hypot(3, 4))
2 print(math.hypot(5, 12))
3 print(math.hypot(8, 15))
5.0
13.0
17.0
isclose() function
It checks whether two values are close to each other, or not.
Returns True if the values are close, otherwise False.
This method uses a relative or absolute tolerance, to see if the values are close.
Tip: It uses the following formula to compare the values: abs(a-b) <= max(rel_tol * max(abs(a), abs(b)),
abs_tol)
In [11]:
False
False
False
True
True
isfinite() function
Return True if x is neither an infinity nor a NaN, and False otherwise.
In [155]:
1 nlis = []
2 nlis.append(math.isfinite(math.inf))
3 nlis.append(math.isfinite(math.pi))
4 nlis.append(math.isfinite(math.e))
5 nlis.append(math.isfinite(math.tau))
6 nlis.append(math.isfinite(0))
7 nlis.append(math.isfinite(6))
8 nlis.append(math.isfinite(1.618))
9 nlis.append(math.isfinite(0.577))
10 nlis.append(math.isfinite(-math.inf))
11 nlis.append(math.isfinite(float('NaN')))
12 nlis.append(math.isfinite(float('inf')))
13 print(nlis)
[False, True, True, True, True, True, True, True, False, False, False]
isinf() function
Return True if x is a positive or negative infinity, and False otherwise.
In [161]:
1 nlis = []
2 nlis.append(math.isinf(math.inf))
3 nlis.append(math.isinf(math.pi))
4 nlis.append(math.isinf(math.e))
5 nlis.append(math.isinf(math.tau))
6 nlis.append(math.isinf(0))
7 nlis.append(math.isinf(6))
8 nlis.append(math.isinf(1.618))
9 nlis.append(math.isinf(0.577))
10 nlis.append(math.isinf(-math.inf))
11 print(nlis)
isnan() function
Return True if x is a NaN (not a number), and False otherwise.
In [162]:
1 nlis = []
2 nlis.append(math.isnan(float('NaN')))
3 nlis.append(math.isnan(math.inf))
4 nlis.append(math.isnan(math.pi))
5 nlis.append(math.isnan(math.e))
6 nlis.append(math.isnan(math.tau))
7 nlis.append(math.isnan(0))
8 nlis.append(math.isnan(6))
9 nlis.append(math.isnan(1.618))
10 nlis.append(math.isnan(0.577))
11 nlis.append(math.isnan(-math.inf))
12 nlis.append(math.isnan(math.nan))
13 print(nlis)
[True, False, False, False, False, False, False, False, False, False, True]
isqrt() function
Rounds a square root number downwards to the nearest integer.
The returned square root value is the floor value of square root of a non-negative integer number.
It gives a ValueError and TypeError when a negative integer number and a float number are used,
respectively.
In [15]:
1 print(math.isqrt(4))
2 print(math.isqrt(5))
3 print(math.isqrt(-5))
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_20068/2393595883.py in <module>
1 print(math.isqrt(4))
2 print(math.isqrt(5))
----> 3 print(math.isqrt(-5))
In [16]:
1 print(math.isqrt(3.14))
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_20068/4116779010.py in <module>
----> 1 print(math.isqrt(3.14))
lcm() function
Least Common Multiple.
In [168]:
1 nlis = []
2 nlis.append(math.lcm(3, 5, 25))
3 nlis.append(math.lcm(9, 6, 27))
4 nlis.append(math.lcm(21, 27, 54))
5 print(nlis)
ldexp() function
Returns the inverse of math.frexp() which is x*(2^i) of the given numbers x and i
In [19]:
1 print(math.ldexp(20, 4))
2 print(20*(2**4))
320.0
320
lgamma() function
Returns the log gamma value of x
In [26]:
1 print(math.gamma(6))
2 print(math.lgamma(6))
3 print(math.log(120)) # print(math.gamma(6)) = 120
120.0
4.787491742782047
4.787491742782046
log() function
log(x, [base=math.e])
Return the logarithm of x to the given base.
In [174]:
1 nlis = []
2 nlis.append(math.log(90))
3 nlis.append(math.log(1))
4 nlis.append(math.log(math.e))
5 nlis.append(math.log(math.pi))
6 nlis.append(math.log(math.tau))
7 nlis.append(math.log(math.inf))
8 nlis.append(math.log(math.nan))
9 print(nlis)
log10() function
Return the base 10 logarithm of x.
In [177]:
1 nlis = []
2 nlis.append(math.log10(90))
3 nlis.append(math.log10(1))
4 nlis.append(math.log10(math.e))
5 nlis.append(math.log10(math.pi))
6 nlis.append(math.log10(math.tau))
7 nlis.append(math.log10(math.inf))
8 nlis.append(math.log10(math.nan))
9 print(nlis)
log1p() function
Return the natural logarithm of 1+x (base e).
In [179]:
1 nlis = []
2 nlis.append(math.log1p(90))
3 nlis.append(math.log1p(1))
4 nlis.append(math.log1p(math.e))
5 nlis.append(math.log1p(math.pi))
6 nlis.append(math.log1p(math.tau))
7 nlis.append(math.log1p(math.inf))
8 nlis.append(math.log1p(math.nan))
9 print(nlis)
log2() function
Return the base 2 logarithm of x.
In [183]:
1 nlis = []
2 nlis.append(math.log2(90))
3 nlis.append(math.log2(2))
4 nlis.append(math.log2(1))
5 nlis.append(math.log2(math.e))
6 nlis.append(math.log2(math.pi))
7 nlis.append(math.log2(math.tau))
8 nlis.append(math.log2(math.inf))
9 nlis.append(math.log2(math.nan))
10 print(nlis)
modf() function
It returns the frwactional and integer parts of the certain number. Both the outputs carry the sign of x and
are of type float.
In [29]:
1 print(math.modf(math.pi))
2 print(math.modf(math.e))
3 print(math.modf(1.618))
(0.14159265358979312, 3.0)
(0.7182818284590451, 2.0)
(0.6180000000000001, 1.0)
nextafter() function
Return the next floating-point value after x towards y.
if x is equal to y then y is returned.
In [191]:
1 nlis = []
2 nlis.append(math.nextafter(3.14, 90))
3 nlis.append(math.nextafter(6, 2.718))
4 nlis.append(math.nextafter(3, math.e))
5 nlis.append(math.nextafter(28, math.inf))
6 nlis.append(math.nextafter(1.618, math.nan))
7 nlis.append(math.nextafter(1, 1))
8 nlis.append(math.nextafter(0, 0))
9 print(nlis)
perm() function
Returns the number of ways to choose k items from n items with order and without repetition.
In [31]:
1 print(math.perm(6, 2))
2 print(math.perm(6, 6))
30
720
pow() function
Returns the value of x to the power of y.
In [34]:
1 print(math.pow(10, 2))
2 print(math.pow(math.pi, math.e))
100.0
22.45915771836104
prod() function
Returns the product of all the elements in an iterable
In [32]:
85632659.07026622
radians() function
Convert angle x from degrees to radians.
In [193]:
1 nlis = []
2 nlis.append(math.radians(0))
3 nlis.append(math.radians(30))
4 nlis.append(math.radians(45))
5 nlis.append(math.radians(60))
6 nlis.append(math.radians(90))
7 nlis.append(math.radians(120))
8 nlis.append(math.radians(180))
9 nlis.append(math.radians(270))
10 nlis.append(math.radians(360))
11 print(nlis)
remainder() function
Difference between x and the closest integer multiple of y.
Return x - ny where ny is the closest integer multiple of y.
ReturnIn the case where x is exactly halfway between two multiples of
y, the nearest even value of n is used. The result is always exact.
In [196]:
1 nlis = []
2 nlis.append(math.remainder(3.14, 2.718))
3 nlis.append(math.remainder(6, 28))
4 nlis.append(math.remainder(5, 3))
5 nlis.append(math.remainder(1729, 37))
6 print(nlis)
sin() function
Return the sine of x (measured in radians).
Note: To find the sine of degrees, it must first be converted into radians with the math.radians() method.
In [204]:
1 nlis = []
2 nlis.append(math.sin(math.pi))
3 nlis.append(math.sin(math.pi/2))
4 nlis.append(math.sin(math.e))
5 nlis.append(math.sin(math.nan))
6 nlis.append(math.sin(math.tau))
7 nlis.append(math.sin(30))
8 nlis.append(math.sin(-5))
9 nlis.append(math.sin(37))
10 print(nlis)
sinh() function
Return the hyperbolic sine of x.
In [213]:
1 nlis = []
2 nlis.append(math.sinh(1))
3 nlis.append(math.sinh(0))
4 nlis.append(math.sinh(-5))
5 nlis.append(math.sinh(math.pi))
6 nlis.append(math.sinh(math.e))
7 nlis.append(math.sinh(math.tau))
8 nlis.append(math.sinh(math.nan))
9 nlis.append(math.sinh(math.inf))
10 print(nlis)
sqrt() function
localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebook_files/18. Math Mod… 18/21
15.06.2022 13:55 18. Math Module Functions in Python - Jupyter Notebook
In [210]:
1 nlis = []
2 nlis.append(math.sqrt(1))
3 nlis.append(math.sqrt(0))
4 nlis.append(math.sqrt(37))
5 nlis.append(math.sqrt(math.pi))
6 nlis.append(math.sqrt(math.e))
7 nlis.append(math.sqrt(math.tau))
8 nlis.append(math.sqrt(math.nan))
9 nlis.append(math.sqrt(math.inf))
10 print(nlis)
tan() function
Return the tangent of x (measured in radians).
In [212]:
1 nlis = []
2 nlis.append(math.tan(0))
3 nlis.append(math.tan(30))
4 nlis.append(math.tan(45))
5 nlis.append(math.tan(60))
6 nlis.append(math.tan(90))
7 nlis.append(math.tan(120))
8 nlis.append(math.tan(180))
9 nlis.append(math.tan(270))
10 nlis.append(math.tan(360))
11 print(nlis)
tanh() function
Return the hyperbolic tangent of x.
In [214]:
1 nlis = []
2 nlis.append(math.tanh(1))
3 nlis.append(math.tanh(0))
4 nlis.append(math.tanh(-5))
5 nlis.append(math.tanh(math.pi))
6 nlis.append(math.tanh(math.e))
7 nlis.append(math.tanh(math.tau))
8 nlis.append(math.tanh(math.nan))
9 nlis.append(math.tanh(math.inf))
10 print(nlis)
trunc() function
Truncates the Real x to the nearest Integral toward 0.
Returns the truncated integer parts of different numbers
In [218]:
1 nlis = []
2 nlis.append(math.trunc(1))
3 nlis.append(math.trunc(0))
4 nlis.append(math.trunc(-5))
5 nlis.append(math.trunc(0.577))
6 nlis.append(math.trunc(1.618))
7 nlis.append(math.trunc(math.pi))
8 nlis.append(math.trunc(math.e))
9 nlis.append(math.trunc(math.tau))
10 print(nlis)
[1, 0, -5, 0, 1, 3, 2, 6]
ulp() function
Return the value of the least significant bit of the float x.
In [224]:
1 import sys
2 nlis = []
3 nlis.append(math.ulp(1))
4 nlis.append(math.ulp(0))
5 nlis.append(math.ulp(-5))
6 nlis.append(math.ulp(0.577))
7 nlis.append(math.ulp(1.618))
8 nlis.append(math.ulp(math.pi))
9 nlis.append(math.ulp(math.e))
10 nlis.append(math.ulp(math.tau))
11 nlis.append(math.ulp(math.nan))
12 nlis.append(math.ulp(math.inf))
13 nlis.append(math.ulp(-math.inf))
14 nlis.append(math.ulp(float('nan')))
15 nlis.append(math.ulp(float('inf')))
16 x = sys.float_info.max
17 nlis.append(math.ulp(x))
18 print(nlis)
Python Tutorial
Created by Mustafa Germec, PhD
Examples
In [3]:
1 import math
2 from math import *
In [24]:
In [90]:
Example: The number of insexts in a lab doubles in size every month. Take the initial number of insects as
input and output a list, showing the number of insects for each of the next 12 months, starting with 0, which is
the initial value. So the resulting list should contain 12 items, each showing the number of insects at the
beginning of that month.
In [31]:
[10, 20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240, 20480]
[10, 20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240, 20480]
In [20]:
In [19]:
['P', 'y', 't', 'h', 'o', 'n', ' ', 'i', 's', ' ', 'a', ' ', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g', ' ', 'l', 'a', 'n', 'g', 'u', 'a', 'g',
'e']
['P', 'y', 't', 'h', 'o', 'n', ' ', 'i', 's', ' ', 'a', ' ', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g', ' ', 'l', 'a', 'n', 'g', 'u', 'a', 'g',
'e']
In [33]:
In [39]:
['Python', 'JavaScript']
['Python', 'JavaScript']
In [46]:
In [48]:
In [51]:
In [53]:
In [56]:
In [59]:
In [85]:
For loop: ['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']
List comprehension: ['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']
Lambda: ['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']
In [79]:
In [82]:
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
In [89]:
1 # Transpose of 2D matrix
2 matrix = [[0.577, 1.618, 0],
3 [2.718, 3.14, 1],
4 [6, 28, 28]]
5 transpose_matrix = [[i[j] for i in matrix] for j in range(len(matrix))]
6 print(transpose_matrix)
Python Tutorial
Created by Mustafa Germec, PhD
In [ ]:
1 """
2 @hello_decorator
3 def hi_decorator():
4 print("Hello")
5 """
6
7 '''
8 Above code is equal to -
9
10 def hi_decorator():
11 print("Hello")
12
13 hi_decorator = hello_decorator(hi_decorator)
14 '''
In [5]:
1 # Import libraries
2 import decorator
3 from decorator import *
4 import functools
5 import math
In [26]:
1 help(decorator)
Functions
In [27]:
1 # Define a function
2 """
3 In the following function, when the code was executed, it yeilds the outputs for both functions.
4 The function new_text() alluded to the function mytext() and behave as function.
5 """
6 def mytext(text):
7 print(text)
8
9 mytext('Python is a programming language.')
10 new_text = mytext
11 new_text('Hell, Python!')
Hell, Python!
In [1]:
1 def multiplication(num):
2 return num * num
3
4 mult = multiplication
5 mult(3.14)
Out[1]:
9.8596
Nested/Inner Function
In [28]:
1 # Define a function
2 """
3 In the following function, it is nonsignificant how the child functions are announced.
4 The implementation of the child function does influence on the output.
5 These child functions are topically linked with the function mytext(), therefore they can not be called individually.
6 """
7 def mytext():
8 print('Python is a programming language.')
9 def new_text():
10 print('Hello, Python!')
11 def message():
12 print('Hi, World!')
13
14 new_text()
15 message()
16 mytext()
17
Hello, Python!
Hi, World!
In [3]:
1 # Define a function
2 """
3 In the following example, the function text() is nesred into the function message().
4 It will return each time when the function tex() is called.
5 """
6 def message():
7 def text():
8 print('Python is a programming language.')
9 return text
10
11 new_message = message()
12 new_message()
In [4]:
1 def function(num):
2 def mult(num):
3 return num*num
4
5 output = mult(num)
6 return output
7 mult(3.14)
Out[4]:
9.8596
In [13]:
1 def msg(text):
2 'Hello, World!'
3 def mail():
4 'Hi, Python!'
5 print(text)
6
7 mail()
8
9 msg('Python is the most popular programming language.')
Passing functions
In [29]:
1 # Define a function
2 """
3 In this function, the mult() and divide() functions as argument in operator() function are passed.
4 """
5 def mult(x):
6 return x * 3.14
7 def divide(x):
8 return x/3.14
9 def operator(function, x):
10 number = function(x)
11 return number
12
13 print(operator(mult, 2.718))
14 print(operator(divide, 1.618))
8.53452
0.5152866242038217
In [7]:
1 def addition(num):
2 return num + math.pi
3
4 def called_function(func):
5 added_number = math.e
6 return func(added_number)
7
8 called_function(addition)
Out[7]:
5.859874482048838
In [111]:
1 def decorator_one(function):
2 def inner():
3 num = function()
4 return num * (num**num)
5 return inner
6
7 def decorator_two(function):
8 def inner():
9 num = function()
10 return (num**num)/num
11 return inner
12
13 @decorator_one
14 @decorator_two
15 def number():
16 return 4
17
18 print(number())
19
20 # The above decorator returns the following code
21 x = pow(4, 4)/4
22 print(x*(x**x))
2.5217283965692467e+117
2.5217283965692467e+117
In [11]:
1 def msg_func():
2 def text():
3 return "Python is a programming language."
4 return text
5 msg = msg_func()
6 print(msg())
Decorating functions
localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebook_files/20. Decorators i… 5/14
20.06.2022 16:06 20. Decorators in Python - Jupyter Notebook
g
In [8]:
5.859874482048838
In [9]:
1 """
2 Rather than above function, Python ensures to employ decorator in easy way with the symbol @ called 'pie' syntax, as
3 """
4 def outer_addition(function):
5 def inner(a, b):
6 if a < b:
7 a, b = b, a
8 return function(a, b)
9 return inner
10
11 @outer_addition # Syntax of decorator
12 def addition(a, b):
13 print(a+b)
14 result = outer_addition(addition)
15 result(math.pi, math.e)
5.859874482048838
In [17]:
1 def decorator_text_uppercase(func):
2 def wrapper():
3 function = func()
4 text_uppercase = function.upper()
5 return text_uppercase
6
7 return wrapper
8
9 # Using a function
10 def text():
11 return 'Python is the most popular programming language.'
12
13 decorated_result = decorator_text_uppercase(text)
14 print(decorated_result())
15
16 # Using a decorator
17 @decorator_text_uppercase
18 def text():
19 return 'Python is the most popular programming language.'
20
21 print(text())
Reprocessing decorator
The decorator can be reused by recalling that decorator function.
In [37]:
1 def do_twice(function):
2 def wrapper_do_twice():
3 function()
4 function()
5 return wrapper_do_twice
6
7 @do_twice
8 def text():
9 print('Python is a programming language.')
10 text()
In [39]:
1 def do_twice(function):
2 """
3 The function wrapper_function() can admit any number of argument and pass them on the function.
4 """
5 def wrapper_function(*args, **kwargs):
6 function(*args, **kwargs)
7 function(*args, **kwargs)
8 return wrapper_function
9
10 @do_twice
11 def text(programming_language):
12 print(f'{programming_language} is a programming language.')
13 text('Python')
In [41]:
1 @do_twice
2 def returning(programming_language):
3 print('Python is a programming language.')
4 return f'Hello, {programming_language}'
5
6 hello_python = returning('Python')
Fancy decorators
@propertymethod
@staticmethod
@classmethod
In [45]:
1 class Microorganism:
2 def __init__(self, name, product):
3 self.name = name
4 self.product = product
5 @property
6 def show(self):
7 return self.name + ' produces ' + self.product + ' enzyme'
8
9 organism = Microorganism('Aspergillus niger', 'inulinase')
10 print(f'Microorganism name: {organism.name}')
11 print(f'Microorganism product: {organism.product}')
12 print(f'Message: {organism.show}.')
In [46]:
1 class Micoorganism:
2 @staticmethod
3 def name():
4 print('Aspergillus niger is a fungus that produces inulinase enzyme.')
5
6 organims = Micoorganism()
7 organims.name()
8 Micoorganism.name()
In [97]:
1 class Microorganism:
2 def __init__(self, name, product):
3 self.name = name
4 self.product = product
5
6 @classmethod
7 def display(cls):
8 return cls('Aspergillus niger', 'inulinase')
9
10 organism = Microorganism.display()
11 print(f'The fungus {organism.name} produces {organism.product} enzyme.')
12
In [49]:
1 """
2 In the following example, @iterate refers to a function object that can be called in another function.
3 The @iterate(numbers=4) will return a function which behaves as a decorator.
4 """
5 def iterate(numbers):
6 def decorator_iterate(function):
7 @functools.wraps(function)
8 def wrapper(*args, **kwargs):
9 for _ in range(numbers):
10 worth = function(*args, **kwargs)
11 return worth
12 return wrapper
13 return decorator_iterate
14
15 @iterate(numbers=4)
16 def function_one(name):
17 print(f'{name}')
18
19 x = function_one('Python')
Python
Python
Python
Python
In [21]:
1 def arguments(func):
2 def wrapper_arguments(argument_1, argument_2):
3 print(f'The arguments are {argument_1} and {argument_2}.')
4 func(argument_1, argument_2)
5 return wrapper_arguments
6
7
8 @arguments
9 def programing_language(lang_1, lang_2):
10 print(f'My favorite programming languages are {lang_1} and {lang_2}.')
11
12 programing_language("Python", "R")
Multiple decorators
In [18]:
1 def splitted_text(text):
2 def wrapper():
3 function = text()
4 text_splitting = function.split()
5 return text_splitting
6
7 return wrapper
8
9 @splitted_text
10 @decorator_text_uppercase # Calling other decorator above
11 def text():
12 return 'Python is the most popular programming language.'
13 text()
Out[18]:
Arbitrary arguments
In [43]:
1 def arbitrary_argument(func):
2 def wrapper(*args,**kwargs):
3 print(f'These are positional arguments {args}.')
4 print(f'These are keyword arguments {kwargs}.')
5 func(*args)
6 return wrapper
7
8 """1. Without arguments decorator"""
9 print(__doc__)
10 @arbitrary_argument
11 def without_argument():
12 print("There is no argument in this decorator.")
13
14 without_argument()
15
16 """2. With positional arguments decorator"""
17 print(__doc__)
18 @arbitrary_argument
19 def with_positional_argument(x1, x2, x3, x4, x5, x6):
20 print(x1, x2, x3, x4, x5, x6)
21
22 with_positional_argument(math.inf, math.tau, math.pi, math.e, math.nan, -math.inf)
23
24 """3. With keyword arguments decorator"""
25 print(__doc__)
26 @arbitrary_argument
27 def with_keyword_argument():
28 print("Python and R are my favorite programming languages and keyword arguments.")
29
30 with_keyword_argument(language_1="Python", language_2="R")
Debugging decorators
In [69]:
1 def capitalize_dec(function):
2 @functools.wraps(function)
3 def wrapper():
4 return function().capitalize()
5 return wrapper
6
7 @capitalize_dec
8 def message():
9 "Python is the most popular programming language."
10 return 'PYTHON IS THE MOST POPULAR PROGRAMMING LANGUAGE. '
11
12 print(message())
13 print()
14 print(message.__name__)
15 print(message.__doc__)
message
Preserving decorators
In [85]:
1 def preserved_decorator(function):
2 def wrapper():
3 print('Before calling the function, this is printed.')
4 function()
5 print('After calling the function, this is printed.')
6 return wrapper
7
8 @preserved_decorator
9 def message():
10 """This function prints the message when it is called."""
11 print('Python is the most popular programming language.')
12
13 message()
14 print(message.__name__)
15 print(message.__doc__)
16 print(message.__class__)
17 print(message.__module__)
18 print(message.__code__)
19 print(message.__closure__)
20 print(message.__annotations__)
21 print(message.__dir__)
22 print(message.__format__)
wrapper
None
<class 'function'>
__main__
{}
Python Tutorial
Created by Mustafa Germec, PhD
In [22]:
1 def function():
2 for i in range(10):
3 if i%2==0:
4 yield i
5
6 nlis = []
7 for i in function():
8 nlis.append(i)
9 print(nlis)
[0, 2, 4, 6, 8]
In [26]:
1 def func():
2 for i in range(25):
3 if i%4==0:
4 yield i
5
6 num_lis = []
7 for i in func():
8 num_lis.append(i)
9 print(num_lis)
In [2]:
1 def message():
2 msg_one = 'Hello, World!'
3 yield msg_one
4
5 msg_two = 'Hi, Python!'
6 yield msg_two
7
8 msg_three = 'Python is the most popular programming language.'
9 yield msg_three
10
11 result = message()
12 print(next(result))
13 print(next(result))
14 print(next(result))
Hello, World!
Hi, Python!
In [4]:
1 """
2 In the following example, the list comprehension will return the list of cube of elements.
3 Whereas the generator expression will return the reference of the calculated value.
4 Rather than this application, the ^function 'next()' can be used on the generator object.
5 """
6 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 37, 1729]
7
8 list_comp = [i*3 for i in special_nums] # This is a list comprehension.
9 generator_exp = (i*3 for i in special_nums) # This is a generator expression.
10
11 print(list_comp)
12 print(generator_exp)
In [8]:
In [12]:
1 def mult_table(n):
2 for i in range(0, 11):
3 yield n*i
4 i+=1
5
6 mult_table_list = []
7 for i in mult_table(20):
8 mult_table_list.append(i)
9 print(mult_table_list)
[0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200]
In [17]:
1 import sys
2
3 # List comprehension
4 cubic_nums_lc = [i**3 for i in range(1500)]
5 print(f'Memory in bytes with list comprehension is {sys.getsizeof(cubic_nums_lc)}.')
6
7 # Generator expression of the same conditions
8 cubic_nums_gc = (i**3 for i in range(1500))
9 print(f'Memory in bytes with generator expression is {sys.getsizeof(cubic_nums_gc)}.')
In [ ]:
1 def infinite():
2 count = 0
3 while True:
4 yield count
5 count = count + 1
6
7 for i in infinite():
8 print(i)
In [29]:
1 def generator(a):
2 for i in range(a):
3 yield i
4
5 gen = generator(6)
6 print(next(gen))
7 print(next(gen))
8 print(next(gen))
9 print(next(gen))
10 print(next(gen))
11 print(next(gen))
12 print(next(gen))
---------------------------------------------------------------------------
~\AppData\Local\Temp/ipykernel_20708/3124683773.py in <module>
10 print(next(gen))
11 print(next(gen))
---> 12 print(next(gen))
StopIteration:
In [41]:
1 def square_number(num):
2 for i in range(num):
3 yield i**i
4
5 generator = square_number(6)
6
7 # Using 'while' loop
8 while True:
9 try:
10 print(f'The number using while loop is {next(generator)}.')
11 except StopIteration:
12 break
13
14 # Using 'for' loop
15 nlis = []
16 for square in square_number(6):
17 nlis.append(square)
18 print(f'The numbers using for loop are {nlis}.')
19
20 # Using generator comprehension
21 square = (i**i for i in range(6))
22 square_list = []
23 square_list.append(next(square))
24 square_list.append(next(square))
25 square_list.append(next(square))
26 square_list.append(next(square))
27 square_list.append(next(square))
28 square_list.append(next(square))
29 print(f'The numbers using generator comprehension are {square_list}.')
The numbers using for loop are [1, 1, 4, 27, 256, 3125].
The numbers using generator comprehension are [1, 1, 4, 27, 256, 3125].
In [42]:
1 import math
2 sum(i**i for i in range(6))
Out[42]:
3414
In [46]:
1 def fibonacci(numbers):
2 a, b = 0, 1
3 for _ in range(numbers):
4 a, b = b, a+b
5 yield a
6
7 def square(numbers):
8 for i in numbers:
9 yield i**2
10
11 print(sum(square(fibonacci(25))))
9107509825