Python Tutorial
Python Tutorial
(Codes)
Mustafa GERMEC, PhD
TABLE OF CONTENTS
PYTHON TUTORIAL
1 Introduction to Python 4
2 Strings in Python 15
3 Lists in Python 24
4 Tuples in Python 37
5 Sets in Python 46
6 Dictionaries in Python 55
7 Conditions in Python 64
8 Loops in Python 73
9 Functions in Python 84
10 Exception Handling in Python 98
11 Built-in Functions in Python 108
12 Classes and Objects in Python 143
13 Reading Files in Python 158
14 Writing Files in Python 166
15 String Operators and Functions in Python 176
16 Arrays in Python 190
17 Lambda Functions in Python 200
18 Math Module Functions in Python 206
19 List Comprehension in Python 227
20 Decorators in Python 235
21 Generators in Python 249
To my family…
5.06.2022 15:57 01. ntroduct on_python - Jupyter Notebook
Python Tutor al
Created by Mustafa Germec, PhD
1. Introduct on to Python
F rst code
In [4]:
1 import [Link]
In [2]:
Hello World!
Hi, Python!
Vers on control
In [10]:
help() funct on
In [11]:
1 # The Python help func on is used to display the documenta on of modules, func ons, classes, keywords, etc.
2 help(sys) # here the module name is 'sys'
NAME
sys
MODULE REFERENCE
h ps://[Link]/3.10/library/[Link] (h ps://[Link]/3.10/library/[Link])
DESCRIPTION
This module provides access to some objects used or maintained by the
interpreter and to func ons that interact strongly with the interpreter.
Dynamic objects:
Comment
In [12]:
Hello World!
Hello
Errors
In [13]:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_13804/[Link] in <module>
1 # Print string as error message
----> 2 frint('Hello, World!')
In [14]:
In [15]:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_13804/[Link] in <module>
1 # Print both string and error to see the running order
2 print('This string is printed')
----> 3 frint('This gives an error message')
4 print('This string will not be printed')
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() funct on
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
6.0
<class 'int'>
<class 'str'>
<class 'float'>
Out[35]:
'6'
In [37]:
3.14
3
<class 'float'>
<class 'str'>
<class 'int'>
Out[37]:
'3.14'
In [42]:
1
0
1.0
0.0
True
False
True
False
In [46]:
3.0
2
<class 'float'>
<class 'int'>
In [47]:
1 # Addi on
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 # Substrac on
2
3 x = 85-52-21-8
4 print(x)
5 print(type(x))
4
<class 'int'>
In [49]:
1 # Mul plica on
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))
5
<class 'int'>
In [52]:
1 # Modulus
2
3 x = 125%24
4 print(x)
5 print(type(x))
5
<class 'int'>
In [54]:
1 # Exponen a on
2
3 x = 2**3
4 print(x)
5 print(type(x))
8
<class 'int'>
In [56]:
1200
<class 'int'>
5.8
<class 'float'>
In [57]:
1 # Mathema ca 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
Var ables
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]:
842
8
4
2
2.0
4.0
2.0
14
64
2
1.0
1
0
Python Tutor al
Created by Mustafa Germec, PhD
2. Str ngs
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 # prin ng a string
2 print('Hello World!')
Hello World!
In [6]:
Hello World!
Out[6]:
'Hello World!'
Index ng of a str ng
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 nega ve indexing starts with -1, in this case, the nega ve 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
Sl c ng of a str ng
In [15]:
Out[15]:
'Hello'
In [16]:
Out[16]:
'World!'
Str d ng n a str ng
In [17]:
Out[17]:
'HloWrd'
In [18]:
Out[18]:
'Hlo'
In [19]:
Out[19]:
In [20]:
Out[20]:
Escape sequences
In [21]:
Hello World!
How many people are living on the earth?
In [22]:
In [23]:
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 so est 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 me 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 so est 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 me 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 so est 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 me 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 [Link]()
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 so est 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 me 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 [Link](50, '-')
Out[35]:
'-------------------Hallo Leute!-------------------'
In [36]:
1 # count() method returns the number of elements with the specified value
2 [Link]('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([Link](word = 'World!'))
9
10 message1 = 'Hi, My name is {} and I am {} years old.'
11 print([Link]('Bob', 36))
12
13 message2 = 'Hi, My name is {name} and I am {number} years old.'
14 print([Link](name ='Bob', number = 36))
15
16 message3 = 'Hi, My name is {0} and I am {1} years old.'
17 print([Link]('Bob', 36))
Hello World!
Hi, My name is Bob and I am 36 years old.
Hi, My name is Bob and I am 36 years old.
Hi, My name is Bob and I am 36 years old.
Python Tutor al
Created by Mustafa Germec, PhD
3. L sts
L sts are ordered.
L sts can conta n any arb trary objects.
L st elements can be accessed by ndex.
L sts can be nested to arb trary depth.
L sts are mutable.
L sts are dynam c.
Index ng
In [1]:
Out[1]:
In [7]:
1 print('Posi ve and nega ve indexing of the first element: \n - Posi ve index:', nlis[0], '\n - Nega ve index:', nlis[-3])
2 print()
3 print('Posi ve and nega ve indexing of the second element: \n - Posi ve index:', nlis[1], '\n - Nega ve index:', nlis[-2])
4 print()
5 print('Posi ve and nega ve indexing of the third element: \n - Posi ve index:', nlis[2], '\n - Nega ve index:', nlis[-1])
In [8]:
1 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
2 nlis
Out[8]:
['python',
3.14,
2022,
[1, 1, 2, 3, 5, 8, 13, 21, 34],
('hello', 'python', 3, 14, 2022)]
L st operat ons
In [10]:
1 # take a list
2 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
3 nlis
Out[10]:
['python',
3.14,
2022,
[1, 1, 2, 3, 5, 8, 13, 21, 34],
('hello', 'python', 3, 14, 2022)]
In [11]:
Out[11]:
Sl c ng
In [20]:
1 # slicing of a list
2 print(nlis[0:2])
3 print(nlis[2:4])
4 print(nlis[4:6])
['python', 3.14]
[2022, [1, 1, 2, 3, 5, 8, 13, 21, 34]]
[('hello', 'python', 3, 14, 2022)]
Extend ng the l st
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 [Link](['hello world!', 1.618])
4 nlis
Out[25]:
['python',
3.14,
2022,
[1, 1, 2, 3, 5, 8, 13, 21, 34],
('hello', 'python', 3, 14, 2022),
'hello world!',
1.618]
append() method
As d fferent from the extend() method, w th the append() method, we add only one element to the l st
You can see the d fference by compar ng 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 [Link](['hello world!', 1.618])
3 nlis
Out[27]:
['python',
3.14,
2022,
[1, 1, 2, 3, 5, 8, 13, 21, 34],
('hello', 'python', 3, 14, 2022),
['hello world!', 1.618]]
len(), append(), count(), ndex(), nsert(), max(), m n(), sum() funct ons
In [99]:
1 lis = [1,2,3,4,5,6,7]
2 print(len(lis))
3 [Link](4)
4 print(lis)
5 print([Link](4)) # How many 4 are on the list 'lis'?
6 print([Link](2)) # What is the index of the number 2 in the list 'lis'?
7 [Link](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?
7
[1, 2, 3, 4, 5, 6, 7, 4]
2
1
[1, 2, 3, 4, 5, 6, 7, 4, 9]
9
1
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('A er changing:', nlis)
5 nlis[1] = 1.618
6 print('A er changing:', nlis)
7 nlis[2] = [3.14, 2022]
8 print('A er changing:', nlis)
Before changing: ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
A er changing: ['hello python!', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
A er changing: ['hello python!', 1.618, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
A er 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)]
A er changing: [[3.14, 2022], [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
A er changing: [[3.14, 2022], [1, 1, 2, 3, 5, 8, 13, 21, 34]]
In [81]:
1 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
2 print('Before dele ng:', nlis)
3 del nlis
4 print('A er dele ng:', nlis)
Before dele ng: ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_13488/[Link] in <module>
2 print('Before dele ng:', nlis)
3 del nlis
----> 4 print('A er dele ng:', nlis)
In [36]:
Out[36]:
In [57]:
1 text = 'p,y,t,h,o,n'
2 [Link]("," )
Out[57]:
In [90]:
4
6
['a', 'b', 'hello', 'Python', 1, 2, 3, 4, 5, 6]
['a', 'b', 'hello', 'Python', 'a', 'b', 'hello', 'Python', 'a', 'b', 'hello', 'Python']
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
a
b
hello
Python
1
2
3
4
5
6
False
True
Copy the l st
In [62]:
1 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
2 copy_list = nlis
3 print('nlis:', nlis)
4 print('copy_list:', copy_list)
nlis: ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
copy_list: ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
In [70]:
1 # The element in the copied list also changes when the element in the original list was changed.
2 # See the following example
3
4 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
5 print(nlis)
6 copy_list = nlis
7 print(copy_list)
8 print('copy_list[0]:', copy_list[0])
9 nlis[0] = 'hello python!'
10 print('copy_list[0]:', copy_list[0])
['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
copy_list[0]: python
copy_list[0]: hello python!
Clone the l st
In [72]:
Out[72]:
['python',
3.14,
2022,
[1, 1, 2, 3, 5, 8, 13, 21, 34],
('hello', '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
nlis[0]: hello, python!
Concatenate the l st
In [78]:
As d fferent from the l st, I also f nd s gn f cant the follow ng nformat on.
nput() funct on
nput() funct on n Python prov des a user of a program supply nputs to the program at runt me.
In [6]:
In [12]:
1 # Although the func on 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]:
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))
format() funct on
Th s funct on helps to format the output pr nted on the secreen w th good look and attract ve.
In [22]:
In [25]:
The operators such as <, >, <=, >=, ==, and != compare the certa n 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)
The operators nclud ng and, or, not are ut l zed to br ng two cond t ons 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
The operators nclud ng =, +=, -=, =, /=, %=, //=, *=, &=, |=, ^=, >>=, and <<= are employed to evaluate a
value to a var able.
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
Ident ty operators
The operators s or s not are employed to control f the operands or objects to the left and r ght of these
operators are referr ng to a value stored n the same momory locat on 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
Membersh p operators
These operators nclus ng n and not n are employed to check f the certa n value s ava lable n 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 Tutor al
Created by Mustafa Germec, PhD
4. Tuples n Python
Tuples are mmutable l sts and cannot be changed n any way once t s 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},
{'A': 3, 'B': 8},
(0, 1))
In [10]:
1 print(type(tuple_1))
2 print(len(tuple_1))
<class 'tuple'>
11
Index ng
In [12]:
1 # Prin ng the each value in a tuple using both posi ve and nega ve 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'>
Concatenat on of tuples
In [13]:
Out[13]:
('Hello',
'Python',
3.14,
1.618,
True,
False,
32,
[1, 2, 3],
{1, 2, 3},
{'A': 3, 'B': 8},
(0, 1),
'Hello World!',
2022)
Repet t on 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)
Membersh p
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
Iterat on
In [50]:
1 rep_tup = (1,2,3,4)
2 for i in rep_tup:
3 print(i)
1
2
3
4
cmp() funct on
In [55]:
-1
1
0
m n() funct on
In [56]:
1 rep_tup = (1,2,3,4)
2 min(rep_tup)
Out[56]:
max() funct on
In [58]:
1 rep_tup = (1,2,3,4)
2 max(rep_tup)
Out[58]:
tup(seq) funct on
In [60]:
1 seq = 'ATGCGTATTGCCAT'
2 tuple(seq)
Out[60]:
('A', 'T', 'G', 'C', 'G', 'T', 'A', 'T', 'T', 'G', 'C', 'C', 'A', 'T')
Sl c ng
To obta n a new tuple from the current tuple, the sl c ng method s used.
In [14]:
Out[14]:
In [18]:
Out[18]:
len() funct on
To obta n how many elements there are n the tuple, use len() funct on.
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
Sort ng tuple
In [22]:
Out[22]:
[0, 1, 2, 3, 4, 6, 7, 8, 9, 9]
Nested tuple
In [25]:
Out[25]:
('biotechnology',
(0, 5),
('fermenta on', 'ethanol'),
(3.14, 'pi', (1.618, 'golden ra o')))
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
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_17624/[Link] in <module>
1 # Take a tuple
2 tuple_4 = (1,3,5,7,8)
----> 3 tuple_4[0] = 9
4 print(tuple_4)
5
Delete a tuple
In [36]:
1 tuple_4 = (1,3,5,7,8)
2 print('Before dele ng:', tuple_4)
3 del tuple_4
4 print('A er dele ng:', tuple_4)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_17624/[Link] in <module>
2 print('Before dele ng:', tuple_4)
3 del tuple_4
----> 4 print('A er dele ng:', 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]:
ndex() method
It returns the ndex of the f rst occurrence of the spec f ed value n 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))
4
0
12
f a tuple ncludes only one element, you should put a comma after the element. Otherw se, t s not cons dered
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
0
<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 Tutor al
Created by Mustafa Germec, PhD
5. Sets n Python
Set s one of 4 bu lt- n data types n Python used to store collect ons of data nclud ng L st, Tuple, and
D ct onary
Sets are unordered, but you can remove tems and add new tems.
Set elements are un que. Dupl cate elements are not allowed.
A set tself may be mod f ed, but the elements conta ned n the set must be of an mmutable type.
Sets are used to store mult ple tems n a s ngle var able.
You can denote a set w th a pa r of curly brackets {}.
In [47]:
1 # The empty set of curly braces denotes the empty dic onary, not empty set
2 x = {}
3 print(type(x))
<class 'dict'>
In [46]:
1 # To take a set without elements, use set() func on 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]:
Convert ng l st to set
In [4]:
Out[4]:
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() funct on
To add an element nto a set, we use the funct on add(). If the same element s added to the set, noth ng w ll
happen because the set accepts no dupl cates.
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() funct on
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() funct on
In [16]:
1 [Link]('Hello Python!')
2 set3
3
Out[16]:
d scard() funct on
It leaves the set unchanged f the element to be deleted s not ava lable n the set.
In [50]:
1 [Link](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}
d fference() funct on
In [61]:
1 print([Link]fference(set5))
2 print([Link]fference(set4))
3
4 # The same process can make using subtrac on operator as follows:
5 print(set4-set5)
6 print(set5-set4)
In [62]:
1 print(set4>set5)
2 print(set5>set4)
3 print(set4==set5)
False
False
False
un on() funct on
In [24]:
1 [Link](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([Link]([3.14, 1.618]))
4 print([Link]([3.14, 1.618]))
True
True
True
True
In [36]:
A set can not have mutable elements such as l st or d ct onary n t. If any, t returns error as follows:
In [39]:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_10540/[Link] in <module>
----> 1 set6 = {'Python', 1,2,3, [1,2,3]}
2 set6
ndex() funct on
Th s funct on does not work n set s nce the set s unordered collect on
In [48]:
1 set7 = {1,2,3,4}
2 set7[1]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_10540/[Link] 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 [Link](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() funct on
In [56]:
1 set8 = {1,3,5,7,9}
2 print(set8)
3 set9 = [Link]()
4 print(set9)
5 [Link](11)
6 print(set8)
7 print(set9)
8
9 """
10 When this func on is used, the original set stays unmodified.
11 A new copy stored in another set of memory loca ons 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 func on is used, the original set stays unmodified.\nA new copy stored in another set of
memory loca ons is created.\nThe change made in one copy won't reflect in another.\n"
celar() funct on
t removes all elements n the set and then do the set empty.
In [57]:
pop() funct on
In [60]:
1 x = {0, 1,1,2,3,5,8,13,21,34}
2 print(x)
3 [Link]()
4 print(x)
Python Tutor al
Created by Mustafa Germec, PhD
6. D ct onar es n Python
D ct onar es are used to store data values n key:value pa rs.
A d ct onary s a collect on wh ch s ordered, changeable or mutable and do not allow dupl cates.
D ct onary tems are ordered, changeable, and does not allow dupl cates.
D ct onary tems are presented n key:value pa rs, and can be referred to by us ng the key name.
D ct onar es are changeable, mean ng that we can change, add or remove tems after the d ct onary has
been created.
D ct onar es cannot have two tems w th the same key.
A d ct onary can nested and can conta n another d ct onary.
In [1]:
Out[1]:
{'key_1': 3.14,
'key_2': 1.618,
'key_3': True,
'key_4': [3.14, 1.618],
'key_5': (3.14, 1.618),
'key_6': 2022,
(3.14, 1.618): 'pi and golden ra o'}
Note: As you see that the whole d ct onary s enclosed n curly braces, each key s separated from ts value by
a column ":", and commas are used to separate the tems n the d ct onary.
In [4]:
3.14
1.618
True
[3.14, 1.618]
(3.14, 1.618)
2022
pi and golden ra o
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 dic onary was deleted.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_2904/[Link] in <module>
----> 1 del product
2 print(product)
3
4 # The dic onary was deleted.
In [17]:
True
False
d ct() funct on
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 dic onary values. It gives a KeyError
2 dict_sample[1]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_3576/[Link] in <module>
1 # Numerical index is not used to take the dic onary values. It gives a KeyError
----> 2 dict_sample[1]
KeyError: 1
It removes all the tems n the d ct onary and returns an empty d ct onary
In [34]:
Out[34]:
{}
copy() funct on
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() funct on
In [38]:
pop
{'family': 'music', 'year': '2022', 'name': 'happy new year'}
It s used to remove the ab trary tems from the d ct onary and returns as a tuple.
In [39]:
get() funct on
Th s method returns the value for the spec f ed key f t s ava lable n the d ct onary. If the key s not ava lable, t
returns None.
In [41]:
music
None
fromkeys() funct on
It returns a new d ct onary w th the certa n sequence of the tems as the keys of the d ct onary and the values
are ass gned w th None.
In [44]:
update() funct on
In [45]:
tems() funct on
In [46]:
Out[46]:
Iterat ng d ct onary
In [11]:
Aspergillus niger
Saccharomyces cerevisiae
Scheffersomyces s pi s
Aspergillus sojae_1
Streptococcus zooepidemicus
Lactobacillus casei
Aspergillus sojae_2
In [15]:
1 # 'for' loop to print the values of the dic onary by using values() and other method
2
3 product = {'Aspergillus niger': 'inulinase', 'Saccharomyces cerevisiae': 'ethanol',
4 'Scheffersomyces s pi s': 'ethanol', 'Aspergillus sojae_1': 'mannanase',
5 'Streptococcus zooepidemicus': 'hyaluronic acid', 'Lactobacillus casei': 'lac c acid',
6 'Aspergillus sojae_2': 'polygalacturonase'}
7 for x in [Link]():
8 print(x)
9
10 print()
11 # 'for' loop to print the values of the dic onary by using values() and other method
12 for x in product:
13 print(product[x])
inulinase
ethanol
ethanol
mannanase
hyaluronic acid
lac c acid
polygalacturonase
inulinase
ethanol
ethanol
mannanase
hyaluronic acid
lac c acid
polygalacturonase
In [16]:
1 # 'for' loop to print the items of the dic onary by using items() method
2 product = {'Aspergillus niger': 'inulinase', 'Saccharomyces cerevisiae': 'ethanol',
3 'Scheffersomyces s pi s': 'ethanol', 'Aspergillus sojae_1': 'mannanase',
4 'Streptococcus zooepidemicus': 'hyaluronic acid', 'Lactobacillus casei': 'lac c acid',
5 'Aspergillus sojae_2': 'polygalacturonase'}
6
7 for x in [Link]():
8 print(x)
In [17]:
Python Tutor al
Created by Mustafa Germec, PhD
In [1]:
1 # Take a variable
2 golden_ra o = 1.618
3
4 # Condi on less than
5 print(golden_ra o<2) # The golden ra o is lower than 2, thus the output is True
6 print(golden_ra o<1) # The golden ra o is greater than 1, thus the output is False
True
False
In [4]:
1 # Take a variable
2 golden_ra o = 1.618
3
4 # Condi on less than or equal to
5 print(golden_ra o<=2) # The golden ra o is lower than 2, thus the condi on is True.
6 print(golden_ra o<=1) # The golden ra o is greater than 1, thus the condi on is False.
7 print(golden_ra o<=1.618) # The golden ra o is equal to 1.618, thus the condi on is True.
True
False
True
In [5]:
1 # Take a variable
2 golden_ra o = 1.618
3
4 # Condi on greater than
5 print(golden_ra o>2) # The golden ra o is lower than 2, thus the condi on is False.
6 print(golden_ra o>1) # The golden ra o is greater than 1, thus the condi on is True.
False
True
In [7]:
1 # Take a variable
2 golden_ra o = 1.618
3
4 # Condi on greater than or equal to
5 print(golden_ra o>=2) # The golden ra o is not greater than 2, thus the condi on is False.
6 print(golden_ra o>=1) # The golden ra o is greater than 1, thus the condi on is True.
7 print(golden_ra o>=1.618) # The golden ra o is equal to 1.618, thus the condi on is True.
False
True
True
In [8]:
1 # Take a variable
2 golden_ra o = 1.618
3
4 # Condi on equal to
5 print(golden_ra o==2) # The golden ra o is not equal to 1.618, thus the condi on is False.
6 print(golden_ra o==1.618) # The golden ra o is equal to 1.618, thus the condi on is True.
False
True
In [11]:
1 # Take a variable
2 golden_ra o = 1.618
3
4 # Condi on not equal to
5 print(golden_ra o!=2) # The golden ra o is not equal to 1.618, thus the condi on is True.
6 print(golden_ra o!=1.618) # The golden ra o is equal to 1.618, thus the condi on is False.
True
False
The compar son operators are also employed to compare the letters/words/symbols accord ng to the ASCII
([Link] [Link]/) 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, respec vely.
9 print('a'>'b') # According to ASCII table, the values of a and b are equal 97 and 98, respec vely.
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 le ers are different since python is case sensi ve.
False
True
True
False
True
False
True
False
False
Branch ng ( f, el f, else)
Dec s on mak ng s requ red when we want to execute a code only f a certa n cond t on s sat sf ed.
The f/el f/else statement s used n Python for dec s on mak ng.
An else statement can be comb ned w th an f statement.
An else statement conta ns the block of code that executes f the cond t onal express on n the f statement
resolves to 0 or a False value
The else statement s an opt onal statement and there could be at most only one else statement follow ng
f.
The el f statement allows you to check mult ple express ons for True and execute a block of code as soon
as one of the cond t ons evaluates to True.
S m lar to the else, the el f statement s opt onal.
However, unl ke else, for wh ch there can be at most one statement, there can be an arb trary number of
el f statements follow ng an f.
If statement
In [6]:
1 pi = 3.14
2 golden_ra o = 1.618
3
4 # This statement can be True or False.
5 if pi > golden_ra o:
6
7 # If the condi ons is True, the following statement will be printed.
8 print(f'The number pi {pi} is greater than the golden ra o {golden_ra o}.')
9
10 # The following statement will be printed in each situta on.
11 print('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_ra o = 1.618
3
4 if pi < golden_ra o:
5 print(f'The number pi {pi} is greater than the golden ra o {golden_ra o}.')
6 else:
7 print(f'The golden ra o {golden_ra o} is lower than the number pi {pi}.')
8 print('Done!')
el f 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!')
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!')
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]:
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!')
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}, respec vely.')
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, respec vely.
The number x with 36 is the greatest number.
or
In [28]:
1 birth_year = 1990
2 if birth_year < 1980 or birth_year > 1989:
3 print('You were not born in 1980s.')
4 else:
5 print('You were born in 1990s.')
6 print('Done!')
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 Tutor al
Created by Mustafa Germec, PhD
8. Loops n Python
A for loop s used for terat ng over a sequence (that s e ther a l st, a tuple, a d ct onary, a set, or a str ng).
Th s s less l ke the for keyword n other programm ng languages, and works more l ke an terator method
as found n other object-or entated programm ng languages.
W th the for loop we can execute a set of statements, once for each tem n a l st, tuple, set etc.
The for loop does not requ re an ndex ng var able to set beforehand.
W th the wh le loop we can execute a set of statements as long as a cond t on s true.
Note: remember to ncrement , or else the loop w ll cont nue forever.
The wh le loop requ res relevant var ables to be ready, n th s example we need to def ne an ndex ng
var able, , wh ch we set to 1.
range() funct on
It s helpful to th nk of the range object as an ordered l st.
To loop through a set of code a spec f ed number of t mes, we can use the range() funct on,
The range() funct on returns a sequence of numbers, start ng from 0 by default, and ncrements by 1 (by
default), and ends at a spec f ed number.
In [3]:
range(0, 5)
range(0, 10)
for loop
The for loop enables you to execute a code block mult ple t mes.
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]:
2
3
4
5
6
7
8
9
10
11
In [16]:
2
5
8
11
In [12]:
In [14]:
0 Python
1 Java
2 JavaScript
3C
4 C++
5 PHP
In [30]:
-3
-2
-1
0
1
2
3
4
5
6
In [31]:
0 Python
1 Java
2 JavaScript
3C
4 C++
5 PHP
In [120]:
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 addi on
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() func on
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_f les_for_shar ng/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 con nue
6 print(i)
7
8 """
9 You see that the output includes the numbers without 5.
10 The con nue func on jumps when it meets with the reference.
11 """
1
2
4
6
7
8
9
10
11
12
13
14
Out[116]:
'\nYou see that the output includes the numbers without 5. \nThe con nue func on 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 func on terminate the loop when it meets with the reference.
11 """
1
2
4
Out[118]:
'\nYou see that the output includes the numbers before 5. \nThe break func on terminate the loop whe
n it meets with the reference.\n'
wh le loop
The wh le loop ex sts as a tool for repeated execut on based on a cond t on. The code block w ll keep be ng
executed unt l the g ven log cal cond t on 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, 'repe tons to get out of loop')
13
2005
2006
2007
It gives us only 3 repe tons to get out of loop
In [37]:
8.0
7.5
There is only 2 movie ra ng, 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
There is only 5 films gretater than movie ra ng 6
In [91]:
['banana']
In [119]:
wh le-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 con nue
0
1
2
3
4
5
break n wh le loop
In [121]:
1 i=0
2
3 while i<=5:
4 print(i)
5 i+=1
6 if i == 3:
7 break
0
1
2
Python Tutor al
Created by Mustafa Germec, PhD
In [9]:
If you make the above opera ons 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 opera ons 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
Var ables
The nput to a funct on s called a formal parameter.
A var able that s declared ns de a funct on s called a local var able.
The parameter only ex sts w th n the funct on ( .e. the po nt where the funct on starts and stops).
A var able that s declared outs de a funct on def n t on s a global var able, and ts value s access ble and
mod f able throughout the program.
In [5]:
1 # Define a func on
2 def func on(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 opera ons with {x}, the results will be {z}.')
8 return z
9
10 with_golden_ra o = func on(1.618)
11 print(with_golden_ra o)
If you make the above opera ons with 1.618, the results will be 9.934520000000001.
9.934520000000001
In [8]:
If you make the above opera ons with 3.14, the results will be 14.500520000000002.
14.500520000000002
In [9]:
If you make the above opera ons with 2.718, the results will be 13.23452.
Out[9]:
13.23452
In [10]:
Hello, Python!
Hello, World!
In [15]:
1 # Prin ng the func on a er a call indicates a None is the default return statement.
2 # See the following pron ngs what func ons returns are.
3
4 print(msg1())
5 print(msg2())
Hello, Python!
None
Hello, World!
None
In [18]:
1 # Define a func on
2 def strings(x, y):
3 return x + y
4
5 # Tes ng the func on 'strings(x, y)'
6 strings('Hello', ' ' 'Python')
Out[18]:
'Hello Python'
In [26]:
Out[26]:
37
In [27]:
Out[27]:
In [28]:
Out[28]:
37
In [29]:
Out[29]:
Predef ned funct ons l ke pr nt(), sum(), len(), m n(), max(), nput()
In [31]:
In [32]:
Out[32]:
1808.053
In [33]:
Out[33]:
In [44]:
In [50]:
S rred-tank bioreactor
30°C temperature
200 rpm agita on speed
1 vvm aera on
1% (v/v) inoculum ra o
pH control at 5.0
In [53]:
You should not watch this film with the ra ng value of 5.5
You should watch this film with the ra ng value of 8.6
Var ables that are created outs de of a funct on (as n all of the examples above) are known as global
var ables.
Global var ables can be used by everyone, both ns de of funct ons and outs de.
In [56]:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_21468/[Link] in <module>
7
8 lang(language)
----> 9 lang(global_var)
In [58]:
The scope of a var able s the part of the program to wh ch that var able s access ble.
Var ables declared outs de of all funct on def n t ons can be accessed from anywhere n the program.
Consequently, such var ables are sa d to have global scope and are known as global var ables.
In [76]:
In [77]:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_21468/[Link] in <module>
13 print('The produc ovity in batch fermenta on is', fermenta on('Batch fermenta on'))
14 print('Con nuous fermenta on has many advantages over batch fermenta on.')
---> 15 print(f'My favourite process is {process}.')
In [81]:
1 # When the global variable and local variable have the same name:
2
3 process = 'Con nuous fermenta on'
4
5 def fermenta on(process_name):
6 process = 'Batch fermenta on'
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 produc ovity in con nuous fermenta on is', fermenta on('Con nuous fermenta on'))
13 print('The produc ovity in batch fermenta on is', fermenta on('Batch fermenta on'))
14 print(f'My favourite process is {process}.')
When the number of arguments are unkknown for a funct on, then the arguments can be packet nto a tuple or
a d ct onary
In [84]:
Number of elements is 4
Aspergillus niger
inulinase
batch
1800 U/mL ac vity
Number of elements is 5
Saccharomyces cerevisia
ethanol
con nuous
45% yield
carob
In [98]:
In [88]:
In [96]:
In [97]:
1 # Define a func on
2 def addi on(x, y):
3 """The following func on returns the sum of two parameters."""
4 z = x+y
5 return z
6
7 print(addi on.__doc__)
8 print(addi on(3.14, 2.718))
In [103]:
In [107]:
1 # Define a func on 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))
In [111]:
25 ------->> 26
nonlocal funct on
In [112]:
In [117]:
Hi Mustafa
Python Tutor al
Created by Mustafa Germec, PhD
ZeroD v s onError
In [1]:
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/[Link] in <module>
5 print('This code gives a ZeroDivisionError.')
6
----> 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))
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/[Link] in <module>
7 print('This code gives a ZeroDivisionError')
8
----> 9 print(count/len(nlis))
In [3]:
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/[Link] in <module>
5 print('The code gives a ZeroDivisionError.')
6
----> 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)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/[Link] in <module>
8
9 # Since the variable 'mean' is not defined, it gives us a 'NameError
---> 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)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/[Link] in <module>
4 print('This code gives a NameError.')
5
----> 6 print(y)
In [6]:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/[Link] in <module>
5
6 print('This func on gives a NameError.')
----> 7 total = add(3.14, 1.618)
8 print(total)
In [7]:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/[Link] in <module>
6 print('This code gives a NameError.')
7
----> 8 name = (Mustafa)
9 print(name, 'today is your wedding day.')
IndexError
In [8]:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/[Link] in <module>
5 print('This code gives us a IndexError.')
6
----> 7 print(nlis[10])
In [9]:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/[Link] in <module>
6 print('This code gives us a IndexError.')
7
----> 8 print(tuple_sample[10])
KeyError
In [10]:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/[Link] in <module>
5 print('This code gives us a KeyError.')
6
----> 7 dictonary = dic onary['euler_number']
8 print(dictonary)
KeyError: 'euler_number'
Except on Handl ng
try/except
In [11]:
1 try:
2 print(name)
3 except NameError:
4 print('Since the variable name is not defined, the func on gives a NameError.')
Since the variable name is not defined, the func on gives a NameError.
In [1]:
try/except/except etc.
In [2]:
try/except/else
In [3]:
try/except/else/f nally
In [5]:
In [6]:
Ra s ng n except on
Us ng the 'ra se' keyword, the programmer can throw an except on when a certa n cond t on s reached.
In [7]:
Python Tutor al
Created by Mustafa Germec, PhD
abs()
Returns the absolute value of a number
In [3]:
all()
Retturns True f all elements n passes terable are true. When the terable object s empty, t returns True. Here,
0 and False return False n th s funct on.
In [10]:
True
[0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729, 0]
False
[0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729, 0, False]
False
[]
True
b n()
Returns the b nary representat on of a spec f c ed nteger
In [14]:
bool()
Converts a value to boolean, namely True and False
In [25]:
bytes()
Returns a btyes object
In [26]:
b'Hello, Python!'
callable()
Checks and returns True f 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 func on(): # since the object appears callable, it returns True
5 print('Hi, Python!')
6 msg = func on
7 print(callable(msg))
False
True
chr()
It returns a character from the spec f ed Un code 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.
B
Y
ל
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_16192/[Link] in <module>
4 print(chr(1500))
5 print(chr(3))
----> 6 print(chr(-500)) # The argument must be inside of the range.
In [135]:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_16192/[Link] in <module>
----> 1 print(chr('Python')) # The argument maut be integer.
comp le()
Returns a code object that can subsequently be executed by exec() funct on
In [35]:
<class 'code'>
Result = 19.87
exec()
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 4/35
7.06.2022 01:23 11. bu lt_ n_funct ons_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 spec f ed attr bute (property or method). If t s not found, t 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_ra o = 1.618
6 msg = 'These numbers are special.'
7
8 special_numbers = SpecialNumbers()
9 print('The euler number is', geta r(special_numbers, 'euler_number'))
10 print('The golden ra o is', special_numbers.golden_ra o)
delattr()
It deletes the spec f ed attr bute (property or method) from the spec f ed object.
In [143]:
1 class SpecialNumbers:
2 euler_constant = 0.577
3 euler_number = 2.718
4 pi = 3.14
5 golden_ra o = 1.618
6 msg = 'These numbers are special.'
7
8 def parameter(self):
9 print(self.euler_constant, self.euler_number, [Link], self.golden_ra o, [Link])
10
11 special_numbers = SpecialNumbers()
12 special_numbers.parameter()
13 dela r(SpecialNumbers, 'msg') # The code deleted the 'msg'.
14 special_numbers.parameter() # Since the code deleted the 'msg', it returns an A ributeError.
---------------------------------------------------------------------------
A ributeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_16192/[Link] in <module>
12 special_numbers.parameter()
13 dela r(SpecialNumbers, 'msg')
---> 14 special_numbers.parameter()
~\AppData\Local\Temp/ipykernel_16192/[Link] in parameter(self)
7
8 def parameter(self):
----> 9 print(self.euler_constant, self.euler_number, [Link], self.golden_ra o, [Link])
10
11 special_numbers = SpecialNumbers()
d ct()
It returns a d ct onary (Array).
In [158]:
1 name = dict()
2 print(name)
3
4 dic onary = dict(euler_constant = 0.577, euler_number=2.718, golden_ra o=1.618)
5 print(dic onary)
{}
{'euler_constant': 0.577, 'euler_number': 2.718, 'golden_ra o': 1.618}
enumerate()
It takes a collect on (e.g. a tuple) and returns t as an enumerate object.
In [156]:
0 Hello Python!
1 Hello, World!
In [155]:
f lter()
It excludes tems n an terable 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 d ct onary.
In [39]:
1 globals()
Out[39]:
{'__name__': '__main__',
'__doc__': 'Automa cally created module for IPython interac ve environment',
'__package__': None,
'__loader__': None,
'__spec__': None,
'__buil n__': <module 'buil ns' (built-in)>,
'__buil ns__': <module 'buil ns' (built-in)>,
'_ih': ['',
'nlis = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]\nprint(any(nlis))',
'nlis = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]\nprint(any(nlis))\[Link]()\nprint(nlis)\nprint
(any(nlis))',
'nlis = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]\nprint(nlis)\nprint(any(nlis))\[Link]()\nprint
(nlis)\nprint(any(nlis))',
"nlis = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]\nprint(nlis)\nprint(any(nlis))\[Link]()\nprint
(nlis)\nprint(any(nlis))\[Link](0, 'False')\nprint(nlis)",
'nlis = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]\nprint(nlis)\nprint(any(nlis))\[Link]()\nprint
(nlis)\nprint(any(nlis))\[Link](0, False)\nprint(nlis)',
'nlis = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]\nprint(nlis)\nprint(any(nlis))\[Link]()\nprint
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 f any terable s True.
In [10]:
asc ()
It returns a str ng nclud ng a pr ntable representat on of an object and escapes non-ASCII characters n the
str ng employ ng \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"')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_16192/[Link] in <module>
6 print(bytearray(nlis))
7 float_num = 3.14
----> 8 print(bytearray(float_num))
hasattr()
It returns True f the spec f ed object has the spec f ed attr bute (property/method).
In [47]:
1 class SpecialNumbers:
2 euler_constant = 0.577
3 euler_number = 2.718
4 pi = 3.14
5 golden_ra o = 1.618
6 msg = 'These numbers are special.'
7
8 special_numbers = SpecialNumbers()
9 print('The euler number is', hasa r(special_numbers, 'euler_number'))
10 print('The golden ra o is', hasa r(special_numbers, 'golden_ra o'))
11 print('The golden ra o is', hasa r(special_numbers, 'prime_number')) # Since there is no prime number, the output
hash()
It returns the hash value of a spec f ed 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 bu lt- n help system
In [167]:
1 help()
If this is your first me using Python, you should definitely check out
the tutorial on the internet at h ps://[Link]/3.10/tutorial/. (h ps://[Link]/3.10/tut
orial/.)
Enter the name of any module, keyword, or topic to get help on wri ng
Python programs and using Python modules. To quit this help u lity and
return to the interpreter, just type "quit".
You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a par cular object directly from the
interpreter, you can type "help(object)". Execu ng "help('string')"
has the same effect as typing a par cular string at the help> prompt.
In [169]:
1 import pandas as pd
2 help(pd) # You can find more informa on about pandas.
NAME
pandas
DESCRIPTION
pandas - a powerful data analysis and manipula on library for Python
=====================================================================
Main Features
-------------
H j t f f th thi th t d d ll
d()
Returns the d 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 ra o': 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()
Th s funct on evaluates and executes an express on.
In [26]:
map()
It returns the spec f ed terator w th the spec f ed funct on appl ed to each tem.
In [77]:
len()
It returns the length of an object
In [54]:
In [59]:
m n()
Returns the smallest tem n an terable
In [170]:
0.577
max()
Returns the largest tem n an terable
In [171]:
1729
sum()
To get the sum of numbers n a l st
In [172]:
1808.0529999999999
float()
It returns a float ng po nt 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
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_16192/[Link] in <module>
6 print(float(txt))
7 msg = 'Hello, Python!' # It resturns a ValueError
----> 8 print(float(msg))
locals()
It returns an updated d ct onary of the current local symbol table.
In [68]:
1 locals()
Out[68]:
{'__name__': '__main__',
'__doc__': 'Automa cally created module for IPython interac ve environment',
'__package__': None,
'__loader__': None,
'__spec__': None,
'__buil n__': <module 'buil ns' (built-in)>,
'__buil ns__': <module 'buil ns' (built-in)>,
'_ih': ['',
'nlis = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]\nprint(any(nlis))',
'nlis = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]\nprint(any(nlis))\[Link]()\nprint(nlis)\nprint
(any(nlis))',
'nlis = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]\nprint(nlis)\nprint(any(nlis))\[Link]()\nprint
(nlis)\nprint(any(nlis))',
"nlis = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]\nprint(nlis)\nprint(any(nlis))\[Link]()\nprint
(nlis)\nprint(any(nlis))\[Link](0, 'False')\nprint(nlis)",
'nlis = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]\nprint(nlis)\nprint(any(nlis))\[Link]()\nprint
(nlis)\nprint(any(nlis))\[Link](0, False)\nprint(nlis)',
'nlis = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]\nprint(nlis)\nprint(any(nlis))\[Link]()\nprint
In [70]:
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 dic onary', dict_1())
9 print('If there is locals(), it returns a dic onary', dict_2())
format()
Th s funct on formats a spec f ed 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 nto a hexadec mal value
In [184]:
1 print(hex(6))
2 print(hex(37))
3 print(hex(1729))
0x6
0x25
0x6c1
nput()
Allow ng user nput
In [219]:
nt()
Returns an nteger 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}.')
s nstance()
It checks f the object (f rst argument) s an nstance or subclass of class nfo 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_ra o = 1.618
6 msg = 'These numbers are very special'
7
8 def __init__(self, euler_constant, euler_number, pi, golden_ra o, msg):
9 self.euler_constant = euler_constant
10 self.euler_number = euler_number
11 [Link] = pi
12 self.golden_ra o = golden_ra o
13 [Link] = 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
ssubclass()
Checks f the class argument (f rst argument) s a subclass of class nfo 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
ter()
It returns an terator object.
In [52]:
object()
It returns a new object.
In [97]:
1 name= object()
2 print(type(name))
3 print(dir(name))
<class 'object'>
['__class__', '__dela r__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__geta ribute__', '__g
t__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__r
educe_ex__', '__repr__', '__seta r__', '__sizeof__', '__str__', '__subclasshook__']
oct()
It returns an octal str ng from the g ven nteger number. The oct() funct on takes an nteger number and returns
ts octal representat on.
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))
l st()
It creates a l st n 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 ra o': 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))
[]
['P', 'y', 't', 'h', 'o', 'n']
[0.577, 1.618, 2.718, 3.14, 1729, 37, 6, 28]
[0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]
['Euler constant', 'Golden ra o', 'Euler number', 'Pi number', 'Perfect number', 'Prime number', 'Ramanu
jan Hardy number']
memoryv ew()
It returns a memory v ew object.
In [91]:
<memory at 0x0000018BB24C5D80>
88
89
90
b'XY'
[88, 89, 90]
{88, 89, 90}
(88, 89, 90)
[88, 65, 90]
bytearray(b'XAZ')
In [ ]:
In [218]:
0.577
1.618
2.718
3.14
6
28
37
1729
open()
It opens a f le and returns a f le object.
In [120]:
1 path = "[Link]"
2 file = open(path, mode = 'r', encoding='u -8')
3 print(fi[Link])
4 print(fi[Link]())
[Link]
English,Charles Severance
English,Sue Blumenberg
English,Elloi Hauser
Spanish,Fernando Tardío Muñiz
In [122]:
English,Charles Severance
English,Sue Blumenberg
English,Elloi Hauser
Spanish,Fernando TardÃo Muñiz
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)
d r()
It returns a l st of the spec f ed object's propert es 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', '__', '___', '__buil n__', '__buil ns__', '__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', 'func on',
'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']
['__abs__', '__add__', '__bool__', '__ceil__', '__class__', '__dela r__', '__dir__', '__divmod__', '__doc_
_', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__geta ribute__', '__ge or
mat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt_
_', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod_
_', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__r
pow__', '__rsub__', '__rtruediv__', '__set_format__', '__seta r__', '__sizeof__', '__str__', '__sub__', '__
subclasshook__', '__truediv__', '__trunc__', 'as_integer_ra o', 'conjugate', 'fromhex', 'hex', 'imag', 'is_in
teger', 'real']
['__add__', '__class__', '__class_ge tem__', '__contains__', '__dela r__', '__delitem__', '__dir__', '__do
c__', '__eq__', '__format__', '__ge__', '__geta ribute__', '__ge tem__', '__gt__', '__hash__', '__iadd_
_', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__seta r__', '__se t
em__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'inse
rt', 'pop', 'remove', 'reverse', 'sort']
['__and__', '__class__', '__class_ge tem__', '__contains__', '__dela r__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__geta ribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass_
_', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__',
'__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__seta r__', '_
_sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'differen
ce_update', 'discard', 'intersec on', 'intersec on_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remo
ve', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
d vmod()
It returns the quot ent and the rema nder when argument1 s d v ded by argument2.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 25/35
7.06.2022 01:23 11. bu lt_ n_funct ons_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)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_16192/[Link] in <module>
2 print(divmod(9, 3))
3 print(divmod(12, 5))
----> 4 print(divmod('Hello', 'Python!'))
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 ra o': 1.618, 'Euler number': 2.718, 'Pi number': 3.14, 'Perfect n
8 print(set(special_nums_dict))
set()
{'5', '1', '.', '3'}
{' ', 'o', 't', 'e', 'n', 'y', 'P', 'h', '!', 'H', 'l'}
{0.577, 1.618, 2.718, 3.14, 1729, 37, 6, 28}
{2, 3, 4, 5, 6, 7, 8}
{'Pi number', 'Euler number', 'Euler constant', 'Golden ra o', 'Perfect number'}
setattr()
Sets an attr bute (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_ra o = 0.0
6 msg = ''
7
8 def __init__(self, euler_constant, euler_number, pi, golden_ra o, msg):
9 self.euler_constant = euler_constant
10 self.euler_number = euler_number
11 [Link] = pi
12 self.golden_ra o = golden_ra o
13 [Link] = 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_ra o)
20 print(special_numbers.msg)
21 seta r(special_numbers, 'Ramanujan_Hardy_number', 1729)
22 print(special_numbers.Ramanujan_Hardy_number)
0.577
2.718
3.14
1.618
These numbers are special.
1729
sl ce()
Returns a sl ce object that s used to sl ce any sequence (str ng, tuple, l st, 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])
sorted()
Returns a sorted l st
In [213]:
ord()
Convert an nteger represent ng the Un code of the spec f ed character
In [241]:
1 print(ord('9'))
2 print(ord('X'))
3 print(ord('W'))
4 print(ord('^'))
57
88
87
94
pow()
The pow() funct on 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
pr nt()
It pr nts the g ven object to the standard output dev ce (screen) or to the text stream f le.
In [248]:
Hello, Python!
range()
Returns a sequence of numbers between the g ven start nteger to the stop nteger.
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]
2
3
4
5
6
7
8
reversed()
Returns the reversed terator of the g ven sequence.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 29/35
7.06.2022 01:23 11. bu lt_ n_funct ons_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)))
round()
Returns a float ng-po nt number rounded to the spec f ed number of dec mals.
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))
3
3
1
2
1729
str()
Returns the str ng vers on of the g ven 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() bu lt n can be used to create tuples n Python. In Python, a tuple s an mmutable sequence type.
One of the ways of creat ng tuple s by us ng the tuple() construct.
In [271]:
type()
It e ther returns the type of the object or returns a new type object based on the arguments passed.
In [276]:
('H', 'e', 'l', 'l', 'o', ',', ' ', 'P', 'y', 't', 'h', 'o', 'n', '!')
<class 'str'>
<class '__main__.SpecialNumbers'>
vars()
The vars() funct on returns the d ct attr bute of the g ven object.
In [277]:
1 class SpecialNumbers:
2 euler_constant = 0.577
3 euler_number = 2.718
4 pi = 3.14
5 golden_ra o = 1.618
6 msg = 'These numbers are very special'
7
8 def __init__(self, euler_constant, euler_number, pi, golden_ra o, msg):
9 self.euler_constant = euler_constant
10 self.euler_number = euler_number
11 [Link] = pi
12 self.golden_ra o = golden_ra o
13 [Link] = 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_ra o': 1.618, 'msg': 'These numbers a
re very special.'}
z p()
It takes terables (can be zero or more), aggregates them n a tuple, and returns t.
In [283]:
[]
{('Pi number', 3.14), ('Perfect number', 28), ('Euler number', 2.718), ('Euler constant', 0.577), ('Ramanuja
n-Hardy number', 1729), ('Golden ra o', 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 mathema k.')
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()
mport()
It s a funct on that s called by the mport statement.
In [303]:
3.14
2.718
64.0
0.006737946999085467
0.999896315728952
720
In [304]:
1 import math
2 print([Link](3.14))
3 print([Link](-2.718))
4 print([Link](4, 3))
5 print([Link](-5))
6 print([Link](2.718))
7 print([Link](6))
3.14
2.718
64.0
0.006737946999085467
0.999896315728952
720
Python Tutor al
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_f les_for_shar ng/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([Link])
3.14
Funct on n t()
In [43]:
1 class Data:
2 def __init__(self, euler_number, pi_number, golden_ra o):
3 self.euler_number = euler_number
4 self.pi_number = pi_number
5 self.golden_ra o = golden_ra o
6
7 val = Data(2.718, 3.14, 1.618)
8
9 print(val.euler_number)
10 print(val.golden_ra o)
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_ra o):
3 self.euler_number = euler_number
4 self.pi_number = pi_number
5 self.golden_ra o = golden_ra o
6 def msg_func on(self):
7 print("The euler number is", self.euler_number)
8 print("The golden ra o is", self.golden_ra o)
9 print("The pi number is", self.pi_number)
10
11 val = Data(2.718, 3.14, 1.618)
12 val.msg_func on()
Self parameter
The self parameter s a reference to the current nstance of the class, and s used to access var ables that
belongs to the class.
It does not have to be named self, you can call t whatever you l ke, but t has to be the f rst parameter of
any funct on n the class.
Check the follow ng example:
In [46]:
1 """
2 The following codes are the same as the above codes under the tle '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_ra o):
7 classFirstParameter.euler_number = euler_number
8 classFirstParameter.pi_number = pi_number
9 classFirstParameter.golden_ra o = golden_ra o
10
11 def msg_func on(classFirstParameter):
12 print("The euler number is", classFirstParameter.euler_number)
13 print("The golden ra o is", classFirstParameter.golden_ra o)
14 print("The pi number is", classFirstParameter.pi_number)
15
16 val = Data(2.718, 3.14, 1.618)
17 val.msg_func on()
In [1]:
20
10
['__class__', '__dela r__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__geta ribu
te__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__n
ew__', '__reduce__', '__reduce_ex__', '__repr__', '__seta r__', '__sizeof__', '__str__', '__subclasshook_
_', '__weakref__', 'color', 'drawRectangle', 'height', 'width']
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
['__class__', '__dela r__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__geta ribu
te__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__n
ew__', '__reduce__', '__reduce_ex__', '__repr__', '__seta r__', '__sizeof__', '__str__', '__subclasshook_
_', '__weakref__', 'color', 'drawCircle', 'increase_radius', 'radius']
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_ra o = 1.618
6 msg = 'These numbers are special.'
7
8 special_numbers = SpecialNumbers()
9 print('The euler number is', geta r(special_numbers, 'euler_number'))
10 print('The golden ra o is', special_numbers.golden_ra o)
11 print('The pi number is', geta r(special_numbers, 'pi_number'))
12 print('The message is ', geta r(special_numbers, 'msg'))
In [37]:
1 class SpecialNumbers:
2 euler_constant = 0.577
3 euler_number = 2.718
4 pi = 3.14
5 golden_ra o = 1.618
6 msg = 'These numbers are special.'
7
8 def parameter(self):
9 print(self.euler_constant, self.euler_number, [Link], self.golden_ra o, [Link])
10
11 special_numbers = SpecialNumbers()
12 special_numbers.parameter()
13 dela r(SpecialNumbers, 'msg') # The code deleted the 'msg'.
14 special_numbers.parameter() # Since the code deleted the 'msg', it returns an A ributeError.
---------------------------------------------------------------------------
A ributeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_15364/[Link] in <module>
12 special_numbers.parameter()
13 dela r(SpecialNumbers, 'msg') # The code deleted the 'msg'.
---> 14 special_numbers.parameter() # Since the code deleted the 'msg', it returns an A ributeErr
or.
~\AppData\Local\Temp/ipykernel_15364/[Link] in parameter(self)
7
8 def parameter(self):
----> 9 print(self.euler_constant, self.euler_number, [Link], self.golden_ra o, [Link])
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 [Link]()
3.14-1.618j
In [54]:
1 class Data:
2 def __init__(self, genus, species):
3 [Link] = genus
4 [Link] = species
5
6 def microorganism(self):
7 print(f'The name of a microorganism is in the form of {[Link]} {[Link]}.')
8
9 #Use the Data class to create an object, and then execute the microorganism method
10 value = Data('Aspergillus', 'niger')
11 [Link]()
In [56]:
1 class Data:
2 def __init__(self, genus, species):
3 [Link] = genus
4 [Link] = species
5
6 def microorganism(self):
7 print(f'The name of a microorganism is in the form of {[Link]} {[Link]}.')
8
9 class Recombinant(Data):
10 pass
11
12 value = Recombinant('Aspergillus', 'sojae')
13 [Link]()
In [4]:
1 class Data:
2 def __init__(self, genus, species):
3 [Link] = genus
4 [Link] = species
5
6 def microorganism(self):
7 print(f'The name of a microorganism is in the form of {[Link]} {[Link]}.')
8
9 class Recombinant(Data):
10 def __init__(self, genus, species):
11 Data.__init__(self, genus, species)
12
13 value = Recombinant('Aspergillus', 'sojae')
14 [Link]()
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 mathema k.')
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 [Link] = genus
4 [Link] = species
5
6 def microorganism(self):
7 print(f'The name of a microorganism is in the form of {[Link]} {[Link]}.')
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 [Link]()
In [65]:
1 class Data:
2 def __init__(self, genus, species):
3 [Link] = genus
4 [Link] = species
5
6 def microorganism(self):
7 print(f'The name of a microorganism is in the form of {[Link]} {[Link]}.')
8
9 class Recombinant(Data):
10 def __init__(self, genus, species):
11 super().__init__(genus, species)
12 [Link] vity = 2500 # This informa on was adedd as a Property
13
14 value = Recombinant('Aspergillus', 'sojae')
15 print(f'The enzyme ac vity increased to {[Link] vity} U/mL.')
In [66]:
1 class Data:
2 def __init__(self, genus, species):
3 [Link] = genus
4 [Link] = species
5
6 def microorganism(self):
7 print(f'The name of a microorganism is in the form of {[Link]} {[Link]}.')
8
9 class Recombinant(Data):
10 def __init__(self, genus, species, ac vity):
11 super().__init__(genus, species)
12 [Link] vity = ac vity # This informa on was adedd as a Property
13
14 value = Recombinant('Aspergillus', 'sojae', 2500)
15 print(f'The enzyme ac vity increased to {[Link] vity} U/mL.')
In [67]:
1 class Data:
2 def __init__(self, genus, species):
3 [Link] = genus
4 [Link] = species
5
6 def microorganism(self):
7 print(f'The name of a microorganism is in the form of {[Link]} {[Link]}.')
8
9 class Recombinant(Data):
10 def __init__(self, genus, species, ac vity):
11 super().__init__(genus, species)
12 [Link] vity = ac vity # This informa on was adedd as a Property
13
14 def increment(self):
15 print(f'With this new recombinant {[Link]} {[Link]} strain, the enzyme ac vity increased 2- mes with {se
16
17 value = Recombinant('Aspergillus', 'sojae', 2500)
18 [Link]()
With this new recombinant Aspergillus sojae strain, the enzyme ac vity increased 2- mes with 2500 U/
mL.
Python Tutor al
Created by Mustafa Germec, PhD
Read ng f le
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 so est 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 me 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 li
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_fi[Link]
r
I dedicate this book to Nancy Lier Cosgrove Mullis.
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 so est 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 me 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 li 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 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_fi[Link]'
2 with open(fname, 'r') as f:
3 content = [Link]()
4 print(content)
In [7]:
Out[7]:
True
In [8]:
In [9]:
In [10]:
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 so est 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 me 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 li 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 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) funct on
Reads atmost n bytes from the f le f n s spec f ed, else reads the ent re f le.
Returns the retr eved bytes n the form of a str ng.
In [14]:
In [15]:
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 so est 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 me 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 li 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 depth; it is due to a year of Nancy, and the prospect of neve
r again being without her.
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 so est
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 me 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 li 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 la
ck of depth; it is due to a year of Nancy, and the prospect of never again being without her.\n', '\n']
Removes the lead ng and tra l ng spaces from the g ven str ng.
In [18]:
S ze of the text f le
In [19]:
In [20]:
Python Tutor al
Created by Mustafa Germec, PhD
F rst, open the text f le for wr t ng (or append ng) us ng the open() funct on.
Second, wr te to the text f le us ng the wr te() or wr tel nes() method.
Th rd, close the f le us ng the close() method.
Wr t ng f les
In [17]:
In [18]:
In [20]:
Entertaini ng … [Mullis is] usefully cranky and comba ve, raising provoca ve ques ons about received tr
uths from the scien fic establishment.
One of the most unusual scien sts of our mes, 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, informa ve, and fun.
Append ng f les
In [24]:
Overright
In [25]:
Overright
I dedicate this book to Nancy Lier Cosgrove Mullis.
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 so est 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 me 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 li 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 depth; it is due to a year of Nancy, and the prospect of neve
r again being without her.
A feedback from Elle on the book
This bona-fide wild card of the scien fic 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_fi[Link]'
2 with open(fname, 'a+') as f:
3 [Link]("From F. Lee Bailey\n")
4 [Link]("A very good book by a fascina ng man.… [Mullis] enjoys an almost frighteningly brilliant mind and yet some
5 print([Link]())
In [9]:
Overright
I dedicate this book to Nancy Lier Cosgrove Mullis.
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 so est 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 me 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 li 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 depth; it is due to a year of Nancy, and the prospect of neve
r again being without her.
A feedback from Elle on the book
This bona-fide wild card of the scien fic community writes with eccentric gusto.… Mullis has created a fr
ee-wheeling adventure yarn that just happens to be the story of his life.
From F. Lee Bailey
A very good book by a fascina ng 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]:
r+
In [13]:
Copy the f le
In [14]:
In [15]:
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!
Hi, See!Hi, Sun!
Hello, Summer!
Hi, See!
Python Tutor al
Created by Mustafa Germec
In [1]:
1 string_hello = 'Hello'
2 string_python = 'Python!'
3 print(string_hello)
4 print(string_python)
Hello
Python!
Delet ng the tems n a str ng s not supported s nce str ngs are mmutable
It returns a TypeError. However, the whole str ng can be deleted. When t s, t returns a NameError.
In [6]:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_18660/[Link] in <module>
1 text = 'Python is a programming language.'
2 print(text)
----> 3 del text[1]
4 print(text)
In [7]:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_18660/[Link] in <module>
2 print(text)
3 del text
----> 4 print(text)
In [9]:
Hello Python!
Append ng (+=) adds a new str ng the the end of the current str ng
In [10]:
Hello Python!
In [12]:
In [21]:
Hello
o
Python!
Python
Str d ng n sl c ng
The th rd parameter spec f es the str de, wh ch refers to how many characters to move forward after the f rst
character s retr eved from the str ng.
In [29]:
14
Hello, Python!
Hlo yhn
Hl tn
Reverse str ng
The str de value s equal to -1 f a reverse str ng s wanted to obta n
In [30]:
!nohtyP ,olleH
n and not n
n returns True when the character or word s n the g ven str ng, otherw se False.
not n returns False when the character or word s n the g ven str ng, otherw se True.
In [130]:
True
False
True
False
In [31]:
casefold() funct on
It converts the characters n the certa n str ng nto lowercase.
In [32]:
center() funct on
It w ll center al gn the str ng, us ng a spec f ed character (space s default) as the f ll character.
In [43]:
count() funct on
It returns the number of a certa n characters n a str ng.
In [45]:
In [49]:
True
False
f nd() funct on
It nvest gates the str ng for a certa n value and returns the pos t on of where t was found.
In [62]:
7
-1
format() funct on
It formats the spec f ed value(s) and nsert them ns de the str ng's placeholder.
The placeholder s def ned us ng curly brackets: {}.
In [66]:
ndex() funct on
It exam nes the str ng for a certa n value and returns the pos t on of where t was found.
In [71]:
7
0
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_18660/[Link] in <module>
2 print([Link]('Python!'))
3 print([Link]('Hello'))
----> 4 print([Link]('Hi')) # If the value is not found, it returns a 'ValueError'
salnum() funct on
It returns True f all characters n the str ng are alphanumer c.
In [76]:
False
True
salpha() funct on
It returns True f all characters n the str ng are alphabets.
Wh te spaces are not cons dered as alphabets and thus t returns False.
In [80]:
1 text = 'Hello'
2 print([Link]())
3 text = 'Hello1358' # The text contains numbers.
4 print([Link]())
5 text = 'Hello Python!' # The text contains a white space.
6 print([Link]())
True
False
False
In [82]:
1 text = 'Hello'
2 print([Link]())
3 numbered_text = '011235813'
4 print(numbered_text.isdecimal())
False
True
sd g t() funct on
Th s funct on returns True f all the characters n the str ng and the Un code characters are d g ts.
In [83]:
1 numbered_text = '011235813'
2 print(numbered_text.isdigit())
True
In [85]:
1 numbered_text = '011235813'
2 print(numbered_text.isiden fier())
3 variable = 'numbered_text'
4 print([Link] fier())
False
True
In [89]:
True
False
True
sspace() funct on
localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/15. Str ngs Ope… 9/14
20.06.2022 16:06 15. Str ngs Operators and Funct ons n Python - Jupyter Notebook
p ()
It returns True f all the characters n the str ng are wh tespaces.
In [90]:
False
True
In [94]:
False
True
In [95]:
False
True
jo n() funct on
It takes all tems n an terable and jo ns them nto one str ng.
A str ng must be spec f ed as the separator.
In [100]:
Hello#World#Hi#Python
Hello+World+Hi+Python
Hello--Python--Hi--World
val1--val2--val3--val4
ljust() funct on
It returns the left just f ed vers on of the certa n str ng.
In [119]:
1 text = 'Python'
2 text = [Link](30, '-')
3 print(text, 'is my favorite programming language.')
rjust() funct on
It returns the r ght just f ed vers on of the certa n str ng.
In [120]:
1 text = 'Python'
2 text = [Link](30, '-')
3 print(text, 'is my favorite programming language.')
In [103]:
Hello Python!
It removes characters from the r ght based on the argument (a str ng spec fy ng the set of characters to be
removed).
In [104]:
Hello Python!
In [105]:
Hello Python!
replace() funct on
Replaces a spec f ed phrase w th another spec f ed phrase.
In [106]:
In [107]:
In [114]:
rf nd() funct on
The rf nd() method f nds the last occurrence of the spec f ed value.
The rf nd() method returns -1 f the value s not found.
The rf nd() method s almost the same as the r ndex() method.
In [125]:
r ndex() funct on
The r ndex() method f nds the last occurrence of the spec f ed value.
The r ndex() method ra ses a ValueError except on f the value s not found.
The r ndex() method s almost the same as the rf nd() method.
In [126]:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_18660/[Link] in <module>
2 print(f"'Python' is in the posi on {[Link]('Python')}.")
3 print(f"'my' is in the posi on {[Link]('my')}.")
----> 4 print(f"'close' is in the posi on {[Link]('close')}.")
swapcase() funct on
Th s funct on converts the uppercase characters nto lowercase and v ce versa.
localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/15. Str ngs Op… 13/14
20.06.2022 16:06 15. Str ngs Operators and Funct ons n Python - Jupyter Notebook
In [116]:
hELLO pYTHON!
Hello Python!
t tle() funct on
Th s funct on converts the f rst character n the g ven str ng nto uppercase.
In [117]:
Python Tutor al
Created by Mustafa Germec, PhD
Creat ng an array
You should mport the module name 'array' as follows:
In [4]:
In [5]:
1 # To access more informa on regarding array, you can execute the following commands
2 help(arr)
NAME
array
DESCRIPTION
This module defines an object type which can efficiently represent
an array of basic values: characters, integers, floa ng point
numbers. Arrays are sequence types and behave very much like lists,
except that the type of objects stored in them is constrained.
CLASSES
buil [Link]
array
Type code
Arrays represent bas c values and behave very much l ke l sts, except the type of objects stored n them s
constra ned.
The type s spec f ed at object creat on t me by us ng a type code, wh ch s a s ngle character.
The follow ng type codes are def ned:
In [6]:
0.577
1.618
2.718
3.14
6.0
37.0
1729.0
Access ng
In [7]:
Chang ng or Updat ng
In [8]:
Delet ng
In [9]:
In [10]:
Concatenat on
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]).
Creat ng 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]:
In [15]:
In [16]:
In [17]:
Sl c ng
In [18]:
In [19]:
In [20]:
In [21]:
In [22]:
Search ng
In [23]:
Copy ng
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
0.577 1.618 2.718 3.14 6.0 37.0 1729.0
The ID number of the array special_nums is 2668250199472.
0.577 1.618 2.718 3.14 6.0 37.0 1729.0
The ID number of the array copied_special_nums is 2668250199472.
Copy ng us ng v ew()
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
0.577 1.618 2.718 3.14 6.0 37.0 1729.0
0.577 1.618 2.718 3.14 6.0 37.0 1729.0
Copy ng us ng copy()
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
0.577 1.618 2.718 3.14 6.0 37.0 1729.0
0.577 1.618 2.718 3.14 6.0 37.0 1729.0
Python Tutor al
Created by Mustafa Germec, PhD
In [1]:
9.14
Out[1]:
9.14
In [2]:
In [3]:
1 # Calculate the volume of a cube using def and lambda func ons
2 # def func on
3 def cube_volume_def(a):
4 return a*a*a
5
6 print(f'The volume of a cube using def func on is {cube_volume_def(3.14)}.')
7
8 # lambda func on
9 print(f'The volume of a cube using lambda func on is {(lambda a: a*a*a)(3.14)}.')
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
The entered number is 6.
6x0=0
6x1=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
f lter()
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 mul plicate 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]
L st comprehens ons
In [7]:
In [8]:
Enter an age: 18
The entered age is 18.
Therefore, you can use a vote.
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 mul plica on of euler number and pi number is equal to {mult_pi_number(2.718)}.')
8 print(f'The mul plica on of euler number and euler constant is equal to {mult_euler_constant(2.718)}.')
In [11]:
In [12]:
In [13]:
1 lambda_list = []
2 # Mul plica on of pi number and 12 in one line using lambda func on
3 lambda_list.append((lambda x:x*3.14) (12))
4 # Division of pi number and 12 in one line using lambda func on
5 lambda_list.append((lambda x: x/3.14) (12))
6 # Addi on of pi number and 12 in one line using lambda func on
7 lambda_list.append((lambda x: x+3.14) (12))
8 # Subtrac on of pi number and 12 in one line using lambda func on
9 lambda_list.append((lambda x: x-3.14) (12))
10 # Remainder of pi number and 12 in one line using lambda func on
11 lambda_list.append((lambda x: x%3.14) (12))
12 # Floor division of pi number and 12 in one line using lambda func on
13 lambda_list.append((lambda x: x//3.14) (12))
14 # Exponen al of pi number and 12 in one line using lambda func on
15 lambda_list.append((lambda x: x**3.14) (12))
16
17 # Prin ng the list
18 print(lambda_list)
In [14]:
1 # Using the func on 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
pec vely.
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 - [Link] - Tools for working with func ons and callable objects
MODULE REFERENCE
h ps://[Link]/3.9/library/functools (h ps://[Link]/3.9/library/functools)
CLASSES
buil [Link]
cached_property
par al
par almethod
singledispatchmethod
In [1]:
In [2]:
1 # Many func ons regarding math modules in python can be find using helf(math) method.
2 help(math)
NAME
math
DESCRIPTION
This module provides access to the mathema cal func ons
defined by the C standard.
FUNCTIONS
acos(x, /)
Return the arc cosine (measured in radians) of x.
acosh(x, /)
Return the inverse hyperbolic cosine of x.
asin(x, /)
Return the arc sine (measured in radians) of x
acos() funct on
Return the arc cos ne (measured n rad ans) of x.
The result s between 0 and p .
The parameter must be a double value between -1 and 1.
In [54]:
1 nlis = []
2 [Link]([Link](1))
3 [Link]([Link](-1))
4 print(nlis)
[0.0, 3.141592653589793]
acosh() funct on
It s a bu lt- n method def ned under the math module to calculate the hyperbol c arc cos ne of the g ven
parameter n rad ans.
For example, f x s passed as an acosh funct on (acosh(x)) parameter, t returns the hyperbol c arc cos ne
value.
In [56]:
1 print([Link](1729))
8.148445582615551
as n() funct on
Return the arc s ne (measured n rad ans) of x.
The result s between -p /2 and p /2.
In [52]:
1 nlis = []
2 [Link]([Link](1))
3 [Link]([Link](-1))
4 print(nlis)
5
[1.5707963267948966, -1.5707963267948966]
as nh() funct on
Return the nverse hyperbol c s ne of x.
In [55]:
1 print([Link](1729))
8.1484457498709
atan() funct on
Return the arc tangent (measured n rad ans) of x.
The result s between -p /2 and p /2.
localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Modul… 2/21
15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook
e esu t s bet ee p/ a dp/
In [66]:
1 nlis = []
2 [Link]([Link]([Link])) # pozi ve infinite
3 [Link]([Link](-[Link])) # nega ve infinite
4 print(nlis)
[1.5707963267948966, -1.5707963267948966]
atan2() funct on
Return the arc tangent (measured n rad ans) of y/x.
Unl ke atan(y/x), the s gns of both x and y are cons dered.
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([Link], [Link]))
6 print(math.atan2([Link], math.e))
7 print(math.atan2([Link], [Link]))
1.5493999395414435
1.5921927140483498
-1.5921927140483498
-1.5493999395414435
0.0
1.5707963267948966
1.1071487177940904
atanh() funct on
Return the nverse hyperbol c tangent of x.
In [91]:
1 nlis=[]
2 [Link]([Link](-0.9999))
3 [Link]([Link](0))
4 [Link]([Link](0.9999))
5 print(nlis)
6
ce l() funct on
Rounds a number up to the nearest nteger
Returns the smalles nteger greater than or equal to var able.
In [22]:
comb() funct on
Number of ways to choose k tems from n tems w thout repet t on and w thout order.
Evaluates to n!/(k!*(n - k)!) when k <= n and evaluates to zero when k>n.
Also called the b nom al coeff c ent because t s equ valent to the coeff c ent of k-th term n polynom al
expans on of the express on (1 + x)**n.
Ra ses TypeError f e ther of the arguments are not ntegers.
Ra ses ValueError f e ther of the arguments are negat ve.
In [19]:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9084/[Link] in <module>
1 print(f'The combina on of 6 with 2 is {[Link](6, 2)}.')
----> 2 print([Link](10, 3.14)) # It returns a TypeError
In [18]:
1 print(f'The copysign of thes two numbers -3.14 and 2.718 is {[Link](-3.14, 2.718)}.')
2 print(f'The copysign of thes two numbers 1729 and -0.577 is {[Link](1729, -0.577)}.')
cos() funct on
Return the cos ne of x (measured n rad ans).
In [105]:
1 print([Link](0))
2 print([Link]([Link]/6))
3 print([Link](-1))
4 print([Link](1))
5 print([Link](1729))
6 print([Link](90))
1.0
0.8660254037844387
0.5403023058681398
0.5403023058681398
0.43204202084333315
-0.4480736161291701
cosh() funct on
Return the hyperbol c cos ne of x.
In [114]:
1 nlis = []
2 [Link]([Link](1))
3 [Link]([Link](0))
4 [Link]([Link](-5))
5 print(nlis)
degrees() funct on
Convert angle x from rad ans to degrees.
In [122]:
1 nlis = []
2 [Link]([Link]([Link]/2))
3 [Link]([Link]([Link]))
4 [Link]([Link]([Link]/4))
5 [Link]([Link](-[Link]))
6 print(nlis)
d st() funct on
Return the Eucl dean d stance between two po nts p and q.
The po nts should be spec f ed as sequences (or terables) of coord nates.
Both nputs must have the same d mens on.
Roughly equ valent to: sqrt(sum((px - qx) ** 2.0 for px, qx n z p(p, q)))
In [127]:
1 print([Link]([30], [60]))
2 print([Link]([0.577, 1.618], [3.14, 2.718]))
3 x = [0.577, 1.618, 2.718]
4 y = [6, 28, 37]
5 print([Link](x, y))
30.0
2.7890803143688783
43.59672438383416
erf() funct on
Error funct on at x.
Th s method accepts a value between - nf and + nf, and returns a value between - 1 to + 1.
In [136]:
1 nlis = []
2 [Link]([Link]([Link]))
3 [Link]([Link]([Link]))
4 [Link]([Link](math.e))
5 [Link]([Link]([Link]))
6 [Link]([Link](0))
7 [Link]([Link](6))
8 [Link]([Link](1.618))
9 [Link]([Link](0.577))
10 [Link]([Link](-[Link]))
11 print(nlis)
erfc() funct on
Complementary error funct on at x.
Th s method accepts a value between - nf and + nf, and returns a value between 0 and 2.
In [137]:
1 nlis = []
2 [Link]([Link]([Link]))
3 [Link]([Link]([Link]))
4 [Link]([Link](math.e))
5 [Link]([Link]([Link]))
6 [Link]([Link](0))
7 [Link]([Link](6))
8 [Link]([Link](1.618))
9 [Link]([Link](0.577))
10 [Link]([Link](-[Link]))
11 print(nlis)
exp() funct on
The [Link]() method returns E ra sed to the power of x (Ex).
E s the base of the natural system of logar thms (approx mately 2.718282) and x s the number passed to
t.
In [139]:
1 nlis = []
2 [Link]([Link]([Link]))
3 [Link]([Link]([Link]))
4 [Link]([Link](math.e))
5 [Link]([Link]([Link]))
6 [Link]([Link](0))
7 [Link]([Link](6))
8 [Link]([Link](1.618))
9 [Link]([Link](0.577))
10 [Link]([Link](-[Link]))
11 print(nlis)
expm1() funct on
Return exp(x)-1.
Th s funct on avo ds the loss of prec s on nvolved n the d rect evaluat on of exp(x)-1 for small x.
In [141]:
1 nlis = []
2 [Link](math.expm1([Link]))
3 [Link](math.expm1([Link]))
4 [Link](math.expm1(math.e))
5 [Link](math.expm1([Link]))
6 [Link](math.expm1(0))
7 [Link](math.expm1(6))
8 [Link](math.expm1(1.618))
9 [Link](math.expm1(0.577))
10 [Link](math.expm1(-[Link]))
11 print(nlis)
fabs() funct on
Returns the absolute value of a number
In [14]:
In [28]:
In [29]:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9084/[Link] in <module>
1 # Factorial of nega ve numbers returns a ValueError.
----> 2 print([Link](-6))
In [30]:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9084/[Link] in <module>
1 # Factorial of non-unteger numbers returns a TypeError.
----> 2 print([Link](3.14))
In [34]:
1 print(math.floor(3.14))
fmod() funct on
Returns the rema nder of x/y
In [37]:
1 print([Link](37, 6))
2 print([Link](1728, 37))
1.0
26.0
frexp() funct on
Returns the mant ssa and the exponent, of a spec f ed number
In [31]:
1 print([Link](2.718))
(0.6795, 2)
fsum() funct on
Returns the sum of all tems n any terable (tuples, arrays, l sts, etc.)
In [142]:
1808.053
gamma() funct on
Returns the gamma funct on at x.
You can f nd more nformat on about gamma funct on from th s L nk.
([Link] k ped [Link]/w k /Gamma_funct on)
In [143]:
1 print([Link](3.14))
2 print([Link](6))
3 print([Link](2.718))
2.2844806338178008
120.0
1.5671127417668826
gcd() funct on
Returns the greatest common d v sor of two ntegers
In [144]:
1 print([Link](3, 10))
2 print([Link](4, 8))
3 print([Link](0, 0))
1
4
0
hypot() funct on
Returns the Eucl dean norm.
Mult d mens onal Eucl dean d stance from the or g n to a po nt.
Roughly equ valent to: sqrt(sum(x**2 for x n coord nates))
For a two d mens onal po nt (x, y), g ves the hypotenuse us ng the Pythagorean theorem: sqrt(xx + yy).
In [148]:
1 print([Link](3, 4))
2 print([Link](5, 12))
3 print([Link](8, 15))
5.0
13.0
17.0
sclose() funct on
It checks whether two values are close to each other, or not.
Returns True f the values are close, otherw se False.
Th s method uses a relat ve or absolute tolerance, to see f the values are close.
T p: It uses the follow ng 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
sf n te() funct on
Return True f x s ne ther an nf n ty nor a NaN, and False otherw se.
In [155]:
1 nlis = []
2 [Link]([Link]finite([Link]))
3 [Link]([Link]finite([Link]))
4 [Link]([Link]finite(math.e))
5 [Link]([Link]finite([Link]))
6 [Link]([Link]finite(0))
7 [Link]([Link]finite(6))
8 [Link]([Link]finite(1.618))
9 [Link]([Link]finite(0.577))
10 [Link]([Link]finite(-[Link]))
11 [Link]([Link]finite(float('NaN')))
12 [Link]([Link]finite(float('inf')))
13 print(nlis)
[False, True, True, True, True, True, True, True, False, False, False]
s nf() funct on
Return True f x s a pos t ve or negat ve nf n ty, and False otherw se.
In [161]:
1 nlis = []
2 [Link]([Link]([Link]))
3 [Link]([Link]([Link]))
4 [Link]([Link](math.e))
5 [Link]([Link]([Link]))
6 [Link]([Link](0))
7 [Link]([Link](6))
8 [Link]([Link](1.618))
9 [Link]([Link](0.577))
10 [Link]([Link](-[Link]))
11 print(nlis)
snan() funct on
Return True f x s a NaN (not a number), and False otherw se.
In [162]:
1 nlis = []
2 [Link]([Link](float('NaN')))
3 [Link]([Link]([Link]))
4 [Link]([Link]([Link]))
5 [Link]([Link](math.e))
6 [Link]([Link]([Link]))
7 [Link]([Link](0))
8 [Link]([Link](6))
9 [Link]([Link](1.618))
10 [Link]([Link](0.577))
11 [Link]([Link](-[Link]))
12 [Link]([Link]([Link]))
13 print(nlis)
[True, False, False, False, False, False, False, False, False, False, True]
sqrt() funct on
Rounds a square root number downwards to the nearest nteger.
The returned square root value s the floor value of square root of a non-negat ve nteger number.
It g ves a ValueError and TypeError when a negat ve nteger number and a float number are used,
respect vely.
In [15]:
1 print([Link](4))
2 print([Link](5))
3 print([Link](-5))
2
2
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_20068/[Link] in <module>
1 print([Link](4))
2 print([Link](5))
----> 3 print([Link](-5))
In [16]:
1 print([Link](3.14))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_20068/[Link] in <module>
----> 1 print([Link](3.14))
lcm() funct on
Least Common Mult ple.
In [168]:
1 nlis = []
2 [Link]([Link](3, 5, 25))
3 [Link]([Link](9, 6, 27))
4 [Link]([Link](21, 27, 54))
5 print(nlis)
ldexp() funct on
Returns the nverse of [Link]() wh ch s x*(2^ ) of the g ven numbers x and
In [19]:
1 print([Link](20, 4))
2 print(20*(2**4))
320.0
320
lgamma() funct on
Returns the log gamma value of x
In [26]:
1 print([Link](6))
2 print([Link](6))
3 print([Link](120)) # print([Link](6)) = 120
120.0
4.787491742782047
4.787491742782046
log() funct on
log(x, [base=math.e])
Return the logar thm of x to the g ven base.
In [174]:
1 nlis = []
2 [Link]([Link](90))
3 [Link]([Link](1))
4 [Link]([Link](math.e))
5 [Link]([Link]([Link]))
6 [Link]([Link]([Link]))
7 [Link]([Link]([Link]))
8 [Link]([Link]([Link]))
9 print(nlis)
log10() funct on
Return the base 10 logar thm of x.
In [177]:
1 nlis = []
2 [Link](math.log10(90))
3 [Link](math.log10(1))
4 [Link](math.log10(math.e))
5 [Link](math.log10([Link]))
6 [Link](math.log10([Link]))
7 [Link](math.log10([Link]))
8 [Link](math.log10([Link]))
9 print(nlis)
log1p() funct on
Return the natural logar thm of 1+x (base e).
In [179]:
1 nlis = []
2 [Link](math.log1p(90))
3 [Link](math.log1p(1))
4 [Link](math.log1p(math.e))
5 [Link](math.log1p([Link]))
6 [Link](math.log1p([Link]))
7 [Link](math.log1p([Link]))
8 [Link](math.log1p([Link]))
9 print(nlis)
log2() funct on
Return the base 2 logar thm of x.
In [183]:
1 nlis = []
2 [Link](math.log2(90))
3 [Link](math.log2(2))
4 [Link](math.log2(1))
5 [Link](math.log2(math.e))
6 [Link](math.log2([Link]))
7 [Link](math.log2([Link]))
8 [Link](math.log2([Link]))
9 [Link](math.log2([Link]))
10 print(nlis)
modf() funct on
It returns the frwact onal and nteger parts of the certa n number. Both the outputs carry the s gn of x and
are of type float.
In [29]:
1 print([Link]([Link]))
2 print([Link](math.e))
3 print([Link](1.618))
(0.14159265358979312, 3.0)
(0.7182818284590451, 2.0)
(0.6180000000000001, 1.0)
nextafter() funct on
Return the next float ng-po nt value after x towards y.
f x s equal to y then y s returned.
In [191]:
1 nlis = []
2 [Link]([Link] er(3.14, 90))
3 [Link]([Link] er(6, 2.718))
4 [Link]([Link] er(3, math.e))
5 [Link]([Link] er(28, [Link]))
6 [Link]([Link] er(1.618, [Link]))
7 [Link]([Link] er(1, 1))
8 [Link]([Link] er(0, 0))
9 print(nlis)
perm() funct on
Returns the number of ways to choose k tems from n tems w th order and w thout repet t on.
In [31]:
1 print([Link](6, 2))
2 print([Link](6, 6))
30
720
pow() funct on
Returns the value of x to the power of y.
In [34]:
1 print([Link](10, 2))
2 print([Link]([Link], math.e))
100.0
22.45915771836104
prod() funct on
Returns the product of all the elements n an terable
In [32]:
85632659.07026622
In [193]:
1 nlis = []
2 [Link]([Link](0))
3 [Link]([Link](30))
4 [Link]([Link](45))
5 [Link]([Link](60))
6 [Link]([Link](90))
7 [Link]([Link](120))
8 [Link]([Link](180))
9 [Link]([Link](270))
10 [Link]([Link](360))
11 print(nlis)
In [196]:
1 nlis = []
2 [Link]([Link](3.14, 2.718))
3 [Link]([Link](6, 28))
4 [Link]([Link](5, 3))
5 [Link]([Link](1729, 37))
6 print(nlis)
s n() funct on
Return the s ne of x (measured n rad ans).
Note: To f nd the s ne of degrees, t must f rst be converted nto rad ans w th the [Link] ans() method.
In [204]:
1 nlis = []
2 [Link]([Link]([Link]))
3 [Link]([Link]([Link]/2))
4 [Link]([Link](math.e))
5 [Link]([Link]([Link]))
6 [Link]([Link]([Link]))
7 [Link]([Link](30))
8 [Link]([Link](-5))
9 [Link]([Link](37))
10 print(nlis)
s nh() funct on
Return the hyperbol c s ne of x.
In [213]:
1 nlis = []
2 [Link]([Link](1))
3 [Link]([Link](0))
4 [Link]([Link](-5))
5 [Link]([Link]([Link]))
6 [Link]([Link](math.e))
7 [Link]([Link]([Link]))
8 [Link]([Link]([Link]))
9 [Link]([Link]([Link]))
10 print(nlis)
sqrt() funct on
localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Mod… 18/21
15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook
In [210]:
1 nlis = []
2 [Link]([Link](1))
3 [Link]([Link](0))
4 [Link]([Link](37))
5 [Link]([Link]([Link]))
6 [Link]([Link](math.e))
7 [Link]([Link]([Link]))
8 [Link]([Link]([Link]))
9 [Link]([Link]([Link]))
10 print(nlis)
tan() funct on
Return the tangent of x (measured n rad ans).
In [212]:
1 nlis = []
2 [Link]([Link](0))
3 [Link]([Link](30))
4 [Link]([Link](45))
5 [Link]([Link](60))
6 [Link]([Link](90))
7 [Link]([Link](120))
8 [Link]([Link](180))
9 [Link]([Link](270))
10 [Link]([Link](360))
11 print(nlis)
tanh() funct on
Return the hyperbol c tangent of x.
In [214]:
1 nlis = []
2 [Link]([Link](1))
3 [Link]([Link](0))
4 [Link]([Link](-5))
5 [Link]([Link]([Link]))
6 [Link]([Link](math.e))
7 [Link]([Link]([Link]))
8 [Link]([Link]([Link]))
9 [Link]([Link]([Link]))
10 print(nlis)
trunc() funct on
Truncates the Real x to the nearest Integral toward 0.
Returns the truncated nteger parts of d fferent numbers
In [218]:
1 nlis = []
2 [Link]([Link](1))
3 [Link]([Link](0))
4 [Link]([Link](-5))
5 [Link]([Link](0.577))
6 [Link]([Link](1.618))
7 [Link]([Link]([Link]))
8 [Link]([Link](math.e))
9 [Link]([Link]([Link]))
10 print(nlis)
[1, 0, -5, 0, 1, 3, 2, 6]
ulp() funct on
Return the value of the least s gn f cant b t of the float x.
In [224]:
1 import sys
2 nlis = []
3 [Link]([Link](1))
4 [Link]([Link](0))
5 [Link]([Link](-5))
6 [Link]([Link](0.577))
7 [Link]([Link](1.618))
8 [Link]([Link]([Link]))
9 [Link]([Link](math.e))
10 [Link]([Link]([Link]))
11 [Link]([Link]([Link]))
12 [Link]([Link]([Link]))
13 [Link]([Link](-[Link]))
14 [Link]([Link](float('nan')))
15 [Link]([Link](float('inf')))
16 x = sys.float_info.max
17 [Link]([Link](x))
18 print(nlis)
Python Tutor al
Created by Mustafa Germec, PhD
Examples
In [3]:
1 import math
2 from math import *
In [24]:
In [90]:
Example: The number of nsexts n a lab doubles n s ze every month. Take the n t al number of nsects as
nput and output a l st, show ng the number of nsects for each of the next 12 months, start ng w th 0, wh ch s
the n t al value. So the result ng l st should conta n 12 tems, each show ng the number of nsects at the
beg nn ng of that month.
In [31]:
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 Tutor al
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)
Funct ons
In [27]:
1 # Define a func on
2 """
3 In the following func on, when the code was executed, it yeilds the outputs for both func ons.
4 The func on new_text() alluded to the func on mytext() and behave as func on.
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!')
In [1]:
Out[1]:
9.8596
Nested/Inner Funct on
In [28]:
1 # Define a func on
2 """
3 In the following func on, it is nonsignificant how the child func ons are announced.
4 The implementa on of the child func on does influence on the output.
5 These child func ons are topically linked with the func on 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
In [3]:
1 # Define a func on
2 """
3 In the following example, the func on text() is nesred into the func on message().
4 It will return each me when the func on 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]:
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.')
In [29]:
1 # Define a func on
2 """
3 In this func on, the mult() and divide() func ons as argument in operator() func on are passed.
4 """
5 def mult(x):
6 return x * 3.14
7 def divide(x):
8 return x/3.14
9 def operator(func on, x):
10 number = func on(x)
11 return number
12
13 print(operator(mult, 2.718))
14 print(operator(divide, 1.618))
8.53452
0.5152866242038217
In [7]:
Out[7]:
5.859874482048838
In [111]:
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())
In [8]:
5.859874482048838
In [9]:
1 """
2 Rather than above func on, Python ensures to employ decorator in easy way with the symbol @ called 'pie' syntax, as
3 """
4 def outer_addi on(func on):
5 def inner(a, b):
6 if a < b:
7 a, b = b, a
8 return func on(a, b)
9 return inner
10
11 @outer_addi on # Syntax of decorator
12 def addi on(a, b):
13 print(a+b)
14 result = outer_addi on(addi on)
15 result([Link], math.e)
5.859874482048838
In [17]:
1 def decorator_text_uppercase(func):
2 def wrapper():
3 func on = func()
4 text_uppercase = func [Link]()
5 return text_uppercase
6
7 return wrapper
8
9 # Using a func on
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())
Reprocess ng decorator
The decorator can be reused by recall ng that decorator funct on.
In [37]:
Decorators w th Arguments
In [39]:
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
@stat cmethod
@classmethod
In [45]:
1 class Microorganism:
2 def __init__(self, name, product):
3 [Link] = name
4 [Link] = product
5 @property
6 def show(self):
7 return [Link] + ' produces ' + [Link] + ' enzyme'
8
9 organism = Microorganism('Aspergillus niger', 'inulinase')
10 print(f'Microorganism name: {[Link]}')
11 print(f'Microorganism product: {[Link]}')
12 print(f'Message: {[Link]}.')
In [46]:
1 class Micoorganism:
2 @sta cmethod
3 def name():
4 print('Aspergillus niger is a fungus that produces inulinase enzyme.')
5
6 organims = Micoorganism()
7 [Link]()
8 [Link]()
In [97]:
1 class Microorganism:
2 def __init__(self, name, product):
3 [Link] = name
4 [Link] = product
5
6 @classmethod
7 def display(cls):
8 return cls('Aspergillus niger', 'inulinase')
9
10 organism = [Link]()
11 print(f'The fungus {[Link]} produces {[Link]} enzyme.')
12
Decorator w th arguments
In [49]:
1 """
2 In the following example, @iterate refers to a func on object that can be called in another func on.
3 The @iterate(numbers=4) will return a func on which behaves as a decorator.
4 """
5 def iterate(numbers):
6 def decorator_iterate(func on):
7 @[Link](func on)
8 def wrapper(*args, **kwargs):
9 for _ in range(numbers):
10 worth = func on(*args, **kwargs)
11 return worth
12 return wrapper
13 return decorator_iterate
14
15 @iterate(numbers=4)
16 def func on_one(name):
17 print(f'{name}')
18
19 x = func on_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")
In [18]:
Out[18]:
In [43]:
1 def arbitrary_argument(func):
2 def wrapper(*args,**kwargs):
3 print(f'These are posi onal 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 posi onal arguments decorator"""
17 print(__doc__)
18 @arbitrary_argument
19 def with_posi onal_argument(x1, x2, x3, x4, x5, x6):
20 print(x1, x2, x3, x4, x5, x6)
21
22 with_posi onal_argument([Link], [Link], [Link], math.e, [Link], -[Link])
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")
Debugg ng decorators
In [69]:
message
Python is the most popular programming language.
Preserv ng decorators
In [85]:
Python Tutor al
Created by Mustafa Germec, PhD
In [22]:
[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!
Python is the most popular programming language.
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 applica on, the ^func on '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 {[Link](cubic_nums_lc)}.')
6
7 # Generator expression of the same condi ons
8 cubic_nums_gc = (i**3 for i in range(1500))
9 print(f'Memory in bytes with generator expression is {[Link](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))
0
1
2
3
4
5
---------------------------------------------------------------------------
StopItera on Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_20708/[Link] in <module>
10 print(next(gen))
11 print(next(gen))
---> 12 print(next(gen))
StopItera on:
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 StopItera on:
12 break
13
14 # Using 'for' loop
15 nlis = []
16 for square in square_number(6):
17 [Link](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}.')
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