0% found this document useful (0 votes)
2 views255 pages

Python Tutorial

The document is a Python tutorial created by Mustafa Germec, PhD, covering various fundamental concepts and features of Python programming. It includes sections on data types, functions, error handling, and mathematical operations, along with code examples and explanations. The tutorial serves as a comprehensive guide for beginners to learn Python programming effectively.

Uploaded by

Mohamed Osman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views255 pages

Python Tutorial

The document is a Python tutorial created by Mustafa Germec, PhD, covering various fundamental concepts and features of Python programming. It includes sections on data types, functions, error handling, and mathematical operations, along with code examples and explanations. The tutorial serves as a comprehensive guide for beginners to learn Python programming effectively.

Uploaded by

Mohamed Osman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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]:

1 # First python output with 'Print' func ons


2 print('Hello World!')
3 print('Hi, Python!')

Hello World!
Hi, Python!

Vers on control

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 1/11


5.06.2022 15:57 01. ntroduct on_python - Jupyter Notebook

In [10]:

1 # Python version check


2 import sys
3 print([Link]) # version control
4 print([Link]) # [Windows only] version number of the Python DLL
5 print([Link] race) # get the global debug tracing func on
6 print([Link]) # keeps the parameters used while running the program we wrote in a list.
7

3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)]


3.10
<built-in func on ge race>
['c:\\Users\\test\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\ipykernel_laun
[Link]', '--ip=[Link]', '--stdin=9008', '--control=9006', '--hb=9005', '--Session.signature_scheme="hm
ac-sha256"', '--[Link]=b"ca6e4e4e-b431-4942-98fd-61b49a098170"', '--shell=9007', '--transport="t
cp"', '--iopub=9009', '--f=c:\\Users\\test\\AppData\\Roaming\\jupyter\\run me\\kernel-17668h2JS6UX
[Link]']

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'

Help on built-in module sys:

NAME
sys

MODULE REFERENCE
h ps://[Link]/3.10/library/[Link] (h ps://[Link]/3.10/library/[Link])

The following documenta on is automa cally generated from the Python


source files. It may be incomplete, incorrect or include features that
are considered implementa on detail and may vary between Python
implementa ons. When in doubt, consult the module reference at the
loca on listed above.

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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 2/11


5.06.2022 15:57 01. ntroduct on_python - Jupyter Notebook

In [12]:

1 # This is a comment, and to write a comment, '#' symbol is used.


2 print('Hello World!') # This line prints a string.
3
4 # Print 'Hello'
5 print('Hello')

Hello World!
Hello

Errors

In [13]:

1 # Print string as error message


2 frint('Hello, World!')

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_13804/[Link] in <module>
1 # Print string as error message
----> 2 frint('Hello, World!')

NameError: name 'frint' is not defined

In [14]:

1 # Built-in error message


2 print('Hello, World!)

File "C:\Users\test\AppData\Local\Temp/ipykernel_13804/[Link]", line 2


print('Hello, World!)
^
SyntaxError: unterminated string literal (detected at line 2)

In [15]:

1 # Print both string and error to see the running order


2 print('This string is printed')
3 frint('This gives an error message')
4 print('This string will not be printed')

This string is printed

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_13804/[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')

NameError: name 'frint' is not defined

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 3/11


5.06.2022 15:57 01. ntroduct on_python - Jupyter Notebook

Bas c data types n Python

In [27]:

1 # String
2 print("Hello, World!")
3 # Integer
4 print(12)
5 # Float
6 print(3.14)
7 # Boolean
8 print(True)
9 print(False)
10 print(bool(1)) # Output = True
11 print(bool(0)) # Output = False
12

Hello, World!
12
3.14
True
False
True
False

type() funct on

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 4/11


5.06.2022 15:57 01. ntroduct on_python - Jupyter Notebook

In [29]:

1 # String
2 print(type('Hello, World!'))
3
4 # Integer
5 print(type(15))
6 print(type(-24))
7 print(type(0))
8 print(type(1))
9
10 # Float
11 print(type(3.14))
12 print(type(0.5))
13 print(type(1.0))
14 print(type(-5.0))
15
16 # Boolean
17 print(type(True))
18 print(type(False))

<class 'str'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'float'>
<class 'float'>
<class 'float'>
<class 'float'>
<class 'bool'>
<class 'bool'>

In [25]:

1 # to obtain the informa on about 'interger' and 'float'


2 print(sys.int_info)
3 print() # to add a space between two outputs, use 'print()' func on
4 print(sys.float_info)

sys.int_info(bits_per_digit=30, sizeof_digit=4)

sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585


072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-
16, radix=2, rounds=1)

Convert ng an abject type to another object type

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 5/11


5.06.2022 15:57 01. ntroduct on_python - Jupyter Notebook

In [35]:

1 # Let's convert the integer number 6 to a string and a float


2
3 number = 6
4
5 print(str(number))
6 print(float(number))
7 print(type(number))
8 print(type(str(number)))
9 print(type(float(number)))
10 str(number)

6
6.0
<class 'int'>
<class 'str'>
<class 'float'>

Out[35]:

'6'

In [37]:

1 # Let's conver the float number 3.14 to a string and an integer


2
3 number = 3.14
4
5 print(str(number))
6 print(int(number))
7 print(type(number))
8 print(type(str(number)))
9 print(type(int(number)))
10 str(number)

3.14
3
<class 'float'>
<class 'str'>
<class 'int'>

Out[37]:

'3.14'

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 6/11


5.06.2022 15:57 01. ntroduct on_python - Jupyter Notebook

In [42]:

1 # Let's convert the booleans to an integer, a float, and a string


2
3 bool_1 = True
4 bool_2 = False
5
6 print(int(bool_1))
7 print(int(bool_2))
8 print(float(bool_1))
9 print(float(bool_2))
10 print(str(bool_1))
11 print(str(bool_2))
12 print(bool(1))
13 print(bool(0))

1
0
1.0
0.0
True
False
True
False

In [46]:

1 # Let's find the data types of 9/3 and 9//4


2
3 print(9/3)
4 print(9//4)
5 print(type(9/3))
6 print(type(9//4))

3.0
2
<class 'float'>
<class 'int'>

Experes on and var ables

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'>

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 7/11


5.06.2022 15:57 01. ntroduct on_python - Jupyter Notebook

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'>

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 8/11


5.06.2022 15:57 01. ntroduct on_python - Jupyter Notebook

In [54]:

1 # Exponen a on
2
3 x = 2**3
4 print(x)
5 print(type(x))

8
<class 'int'>

In [56]:

1 # An example: Let's calculate how many minutes there are in 20 hours?


2
3 one_hour = 60 # 60 minutes
4 hour = 20
5 minutes = one_hour *hour
6 print(minutes)
7 print(type(minutes))
8
9 # An example: Let's calculate how many hours there are in 348 minutes?
10
11 minutes = 348
12 one_hour = 60
13 hours = 348/60
14 print(hours)
15 print(type(hours))

1200
<class 'int'>
5.8
<class 'float'>

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 9/11


5.06.2022 15:57 01. ntroduct on_python - Jupyter Notebook

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]:

1 # Store the value 89 into the variabe 'number'


2
3 number = 90
4 print(number)
5 print(type(number))

90
<class 'int'>

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 10/11


5.06.2022 15:57 01. ntroduct on_python - Jupyter Notebook

In [62]:

1 x = 25
2 y = 87
3 z = 5*x - 2*y
4 print(z)
5
6 t = z/7
7 print(t)
8
9 z = z/14
10 print(z)

-49
-7.0
-3.5

In [68]:

1 x, y, z = 8, 4, 2 # the values of x, y, and z can be wri en in one line.


2 print(x, y, z)
3 print(x)
4 print(y)
5 print(z)
6 print(x/y)
7 print(x/z)
8 print(y/z)
9 print(x+y+z)
10 print(x*y*z)
11 print(x-y-z)
12 print(x/y/z)
13 print(x//y//z)
14 print(x%y%z)
15

842
8
4
2
2.0
4.0
2.0
14
64
2
1.0
1
0

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 11/11


5.06.2022 15:55 02. str ngs_python - Jupyter Notebook

Python Tutor al
Created by Mustafa Germec, PhD

2. Str ngs

In [1]:

1 # Employ double quota on marks for describing a string


2 "Hello World!"

Out[1]:

'Hello World!'

In [2]:

1 # Employ single quota on marks for describing a string


2 'Hello World!'

Out[2]:

'Hello World!'

In [3]:

1 # Digitals and spaces in a string


2 '3 6 9 2 6 8'

Out[3]:

'3 6 9 2 6 8'

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 1/9


5.06.2022 15:55 02. str ngs_python - Jupyter Notebook

In [4]:

1 # Specific characters in a string


2 '@#5_]*$%^&'

Out[4]:

'@#5_]*$%^&'

In [5]:

1 # prin ng a string
2 print('Hello World!')

Hello World!

In [6]:

1 # Assigning a string to a variable 'message'


2 message = 'Hello World!'
3 print(message)
4 message

Hello World!

Out[6]:

'Hello World!'

Index ng of a str ng

In [7]:

1 # prin ng the first element in a string


2
3 message = 'Hello World!'
4 print(message[0])

In [8]:

1 # Prin ng the element on index 8 in a string


2 print(message[8])

In [9]:

1 # lenght of a string includign spaces


2
3 len(message)

Out[9]:

12

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 2/9


5.06.2022 15:55 02. str ngs_python - Jupyter Notebook

In [10]:

1 # Prin ng the last element in a string


2 print(message[11])
3
4 # Another comment wri ng type is as follows using triple quotes.
5
6 """
7 Although the length of the string is 12, since the indexing in Python starts with 0,
8 the number of the last element is therefore 11.
9 """

Out[10]:

'\nAlthough the length of the string is 12, since the indexing in Python starts with 0, \nthe number of th
e last element is therefore 11.\n'

Negat ve ndex ng of a str ng

In [11]:

1 # prin ng the last element of a string


2
3 message[-1]

Out[11]:

'!'

In [12]:

1 # prin ng the first element of a string


2
3 message[-12]
4
5 """
6 Since the nega ve indexing starts with -1, in this case, the nega ve index number
7 of the first element is equal to -12.
8 """

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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 3/9


5.06.2022 15:55 02. str ngs_python - Jupyter Notebook

In [14]:

1 len('Hello World!')

Out[14]:

12

Sl c ng of a str ng

In [15]:

1 # Slicing on the variable 'message' with only index 0 to index 5


2 message[0:5]

Out[15]:

'Hello'

In [16]:

1 # Slicing on the variable 'message' with only index 6 to index 12


2 message[6:12]

Out[16]:

'World!'

Str d ng n a str ng

In [17]:

1 # to select every second element in the variable 'message'


2
3 message[::2]

Out[17]:

'HloWrd'

In [18]:

1 # corpora on of slicing and striding


2 # get every second element in range from index 0 to index 6
3
4 message[0:6:2]

Out[18]:

'Hlo'

Concatenate of str ngs

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 4/9


5.06.2022 15:55 02. str ngs_python - Jupyter Notebook

In [19]:

1 message = 'Hello World!'


2 ques on = ' How many people are living on the earth?'
3 statement = message+ques on
4 statement

Out[19]:

'Hello World! How many people are living on the earth?'

In [20]:

1 # prin ng a string for 4 mes


2 4*" Hello World!"

Out[20]:

' Hello World! Hello World! Hello World! Hello World!'

Escape sequences

In [21]:

1 # New line escape sequence


2 print('Hello World! \nHow many people are living on the earth?')

Hello World!
How many people are living on the earth?

In [22]:

1 # Tab escape sequence


2 print('Hello World! \tHow many people are living on the earth?')

Hello World! How many people are living on the earth?

In [23]:

1 # back slash in a string


2 print('Hello World! \\ How many people are living on the earth?')
3
4 # r will say python that a string will be show as a raw string
5 print(r'Hello World! \ How many people are living on the earth?')

Hello World! \ How many people are living on the earth?


Hello World! \ How many people are living on the earth?

Str ng operat ons

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 5/9


5.06.2022 15:55 02. str ngs_python - Jupyter Notebook

In [24]:

1 message = 'hello python!'


2 print('Before uppercase: ', message )
3
4 # convert uppercase the elements in a string
5 message_upper = [Link]()
6 print('A er uppercase: ', message_upper)
7
8 # convert lowercase the elements in a string
9 message_lower = [Link]()
10 print('Again lowercase: ', message_lower)
11
12 # convert first le er of string to uppercase
13 message_ tle = message. tle()
14 print('The first element of the string is uppercase: ', message_ tle)

Before uppercase: hello python!


A er uppercase: HELLO PYTHON!
Again lowercase: hello python!
The first element of the string is uppercase: Hello Python!

In [25]:

1 # replace() method in a string


2 message = 'Hello Python!'
3 message_hi = [Link]('Hello', 'Hi')
4 message_python = [Link]('Python', 'World')
5 print(message_hi)
6 print(message_python)

Hi Python!
Hello World!

In [26]:

1 # find() method applica on in a string


2 message = 'Hello World!'
3 print(message.find('Wo'))
4
5 # the output is the index number of the first element of the substring

In [27]:

1 # find() method applica on to obtain a substring in a string


2 message.find('World!')

Out[27]:

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 6/9


5.06.2022 15:55 02. str ngs_python - Jupyter Notebook

In [28]:

1 # if cannot find the substring in a string, the output is -1.


2 message.find('cndsjnd')

Out[28]:

-1

In [30]:

1 text = 'Jean-Paul Sartre somewhere observed that we each of us make our own hell out of the people around us. Had
2
3 # find the first index of the substring 'Nancy'
4 text.find('Nancy')

Out[30]:

122

In [31]:

1 # replace the substring 'Nancy' with 'Nancy Lier Cosgrove Mullis'


2 [Link]('Nancy', 'Nancy Lier Cosgrove Mullis')

Out[31]:

'Jean-Paul Sartre somewhere observed that we each of us make our own hell out of the people around
us. Had Jean-Paul known Nancy Lier Cosgrove Mullis, he may have noted that at least one man, someda
y, might get very lucky, and make his own heaven out of one of the people around him. She will be his m
orning and his evening star, shining with the brightest and the 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]:

1 # convet the text to lower case


2 [Link]()

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.'

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 7/9


5.06.2022 15:55 02. str ngs_python - Jupyter Notebook

In [33]:

1 # convert the first le er of the text to capital le er


2 [Link]()

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]:

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 8/9


5.06.2022 15:55 02. str ngs_python - Jupyter Notebook

In [37]:

1 # format() method
2 """
3 The format() method formats the specified value(s) and insert them inside the string's placeholder.
4 The placeholder is defined using curly brackets: {}.
5 """
6
7 txt = "Hello {word}"
8 print([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.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 9/9


5.06.2022 15:52 03. l sts_python - Jupyter Notebook

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]:

1 # crea nng a list


2 nlis = ['python', 25, 2022]
3 nlis

Out[1]:

['python', 25, 2022]

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 1/13


5.06.2022 15:52 03. l sts_python - Jupyter Notebook

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])

Posi ve and nega ve indexing of the first element:


- Posi ve index: python
- Nega ve index: python

Posi ve and nega ve indexing of the second element:


- Posi ve index: 25
- Nega ve index: 25

Posi ve and nega ve indexing of the third element:


- Posi ve index: 2022
- Nega ve index: 2022

What can content a l st?


Str ngs
Floats
Integer
Boolean
Nested L st
Nested Tuple
Other data structures

In [8]:

1 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
2 nlis

Out[8]:

['python',
3.14,
2022,
[1, 1, 2, 3, 5, 8, 13, 21, 34],
('hello', 'python', 3, 14, 2022)]

L st operat ons

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 2/13


5.06.2022 15:52 03. l sts_python - Jupyter Notebook

In [10]:

1 # take a list
2 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
3 nlis

Out[10]:

['python',
3.14,
2022,
[1, 1, 2, 3, 5, 8, 13, 21, 34],
('hello', 'python', 3, 14, 2022)]

In [11]:

1 # length of the list


2 len(nlis)

Out[11]:

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

we use the extend() funct on to add a new element to the l st.


W th th s funct on, we add more than one element to 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]

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 3/13


5.06.2022 15:52 03. l sts_python - Jupyter Notebook

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

Chang ng the element of a l st s nce t s mutable

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 4/13


5.06.2022 15:52 03. l sts_python - Jupyter Notebook

In [31]:

1 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
2 print('Before changing:', nlis)
3 nlis[0] = 'hello python!'
4 print('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)]

Delet ng the element from the l st us ng del() funct on

In [34]:

1 print('Before changing:', nlis)


2 del(nlis[0])
3 print('A er changing:', nlis)
4 del(nlis[-1])
5 print('A er changing:', nlis)

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)

NameError: name 'nlis' is not defined

Convers on of a str ng nto a l st us ng spl t() funct on

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 5/13


5.06.2022 15:52 03. l sts_python - Jupyter Notebook

In [36]:

1 message = 'Python is a programming language.'


2 [Link]()

Out[36]:

['Python', 'is', 'a', 'programming', 'language.']

Use of spl t() funct on w th a del m ter

In [57]:

1 text = 'p,y,t,h,o,n'
2 [Link]("," )

Out[57]:

['p', 'y', 't', 'h', 'o', 'n']

Bas c operat ons

In [90]:

1 nlis_1 = ['a', 'b', 'hello', 'Python']


2 nlis_2 = [1,2,3,4, 5, 6]
3 print(len(nlis_1))
4 print(len(nlis_2))
5 print(nlis_1+nlis_2)
6 print(nlis_1*3)
7 print(nlis_2*3)
8 for i in nlis_1:
9 print(i)
10 for i in nlis_2:
11 print(i)
12 print(4 in nlis_1)
13 print(4 in nlis_2)

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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 6/13


5.06.2022 15:52 03. l sts_python - Jupyter Notebook

In [62]:

1 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
2 copy_list = nlis
3 print('nlis:', nlis)
4 print('copy_list:', copy_list)

nlis: ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
copy_list: ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]

In [70]:

1 # The element in the copied list also changes when the element in the original list was changed.
2 # See the following example
3
4 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
5 print(nlis)
6 copy_list = nlis
7 print(copy_list)
8 print('copy_list[0]:', copy_list[0])
9 nlis[0] = 'hello python!'
10 print('copy_list[0]:', copy_list[0])

['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
copy_list[0]: python
copy_list[0]: hello python!

Clone the l st

In [72]:

1 # The cloned list is a new copy or clone of the original list.


2 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
3 clone_lis = nlis[:]
4 clone_lis

Out[72]:

['python',
3.14,
2022,
[1, 1, 2, 3, 5, 8, 13, 21, 34],
('hello', 'python', 3, 14, 2022)]

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 7/13


5.06.2022 15:52 03. l sts_python - Jupyter Notebook

In [74]:

1 # When an element in the original list is changed, the element in the cloned list does not change.
2 nlis = ['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3,14, 2022)]
3 print(nlis)
4 clone_list = nlis[:]
5 print(clone_list)
6 print('clone_list[0]:', clone_list[0])
7 nlis[0] = 'hello, python!'
8 print('nlis[0]:', nlis[0])

['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
['python', 3.14, 2022, [1, 1, 2, 3, 5, 8, 13, 21, 34], ('hello', 'python', 3, 14, 2022)]
clone_list[0]: python
nlis[0]: hello, python!

Concatenate the l st

In [78]:

1 a_list = ['a', 'b', ['c', 'd'], 'e']


2 b_list = [1,2,3,4,5,(6,7), True, False]
3 new_list = a_list + b_list
4 print(new_list)

['a', 'b', ['c', 'd'], 'e', 1, 2, 3, 4, 5, (6, 7), True, False]

As 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]:

1 text = input('Enter a string:')


2 print('The text is', text)
3 print(type(text))

The text is Hello, Python!


<class 'str'>

In [12]:

1 # Although the 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'>

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 8/13


5.06.2022 15:52 03. l sts_python - Jupyter Notebook

In [15]:

1 number = int(input('Enter an integer:'))


2 print('The number is', number)
3 print(type(number))

The number is 15
<class 'int'>

In [16]:

1 number = float(input('Enter an integer:'))


2 print('The number is', number)
3 print(type(number))

The number is 15.0


<class 'float'>

eval() funct ons

Th s funct on serves the a m of convert ng a str ng to an nteger or a float

In [17]:

1 expression = '8+7'
2 total = eval(expression)
3 print('Sum of the expression is', total)
4 print(type(expression))
5 print(type(total))

Sum of the expression is 15


<class 'str'>
<class 'int'>

format() 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]:

1 a = float(input('Enter the pi number:'))


2 b = float(input('Enter the golden ra o:'))
3 total = a + b
4 print('Sum of {} and {} is {}.'.format(a, b, total))

Sum of 3.14 and 1.618 is 4.758.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 9/13


5.06.2022 15:52 03. l sts_python - Jupyter Notebook

In [25]:

1 a = input('Enter your favorite fruit:')


2 b = input('Enter your favorite food:')
3 print('I like {} and {}.'.format(a, b))
4 print('I like {0} and {1}.'.format(a, b))
5 print('I like {1} and {0}.'.format(a, b))

I like apple and kebab.


I like apple and kebab.
I like kebab and apple.

Compar son operators

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)

a>b is: True


a<b is: False
a<=b is: False
a>=b is: True
a==b is: False
a!=b is: True

Log cal operators

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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 10/13


5.06.2022 15:52 03. l sts_python - Jupyter Notebook

Ass gnment operators

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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 11/13


5.06.2022 15:52 03. l sts_python - Jupyter Notebook

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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 12/13


5.06.2022 15:52 03. l sts_python - Jupyter Notebook

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 13/13


5.06.2022 15:50 04. tuples_python - Jupyter Notebook

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.

Tuples are def ned n the same way as l sts.


They are enclosed w th n parenthes s and not w th n square braces.
Tuples are ordered, ndexed collect ons of data.
S m lar to str ng nd ces, the f rst value n the tuple w ll have the ndex [0], the second value [1]
Negat ve nd ces are counted from the end of the tuple, just l ke l sts.
Tuple also has the same structure where commas separate the values.
Tuples can store dupl cate values.
Tuples allow you to store several data tems nclud ng str ng, nteger, float n one var able.

In [9]:

1 # Take a tuple
2 tuple_1 = ('Hello', 'Python', 3.14, 1.618, True, False, 32, [1,2,3], {1,2,3}, {'A': 3, 'B': 8}, (0, 1))
3 tuple_1

Out[9]:

('Hello',
'Python',
3.14,
1.618,
True,
False,
32,
[1, 2, 3],
{1, 2, 3},
{'A': 3, 'B': 8},
(0, 1))

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 1/9


5.06.2022 15:50 04. tuples_python - Jupyter Notebook

In [10]:

1 print(type(tuple_1))
2 print(len(tuple_1))

<class 'tuple'>
11

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]:

1 # Prin ng the type of each value in the tuple


2 tuple_1 = ('Hello', 'Python', 3.14, 1.618, True, False, 32, [1,2,3], {1,2,3}, {'A': 3, 'B': 8}, (0, 1))
3 print(type(tuple_1[0]))
4 print(type(tuple_1[2]))
5 print(type(tuple_1[4]))
6 print(type(tuple_1[6]))
7 print(type(tuple_1[7]))
8 print(type(tuple_1[8]))
9 print(type(tuple_1[9]))
10 print(type(tuple_1[10]))

<class 'str'>
<class 'float'>
<class 'bool'>
<class 'int'>
<class 'list'>
<class 'set'>
<class 'dict'>
<class 'tuple'>

Concatenat on of tuples

To concatenate tuples, + s gn s used

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 2/9


5.06.2022 15:50 04. tuples_python - Jupyter Notebook

In [13]:

1 tuple_2 = tuple_1 + ('Hello World!', 2022)


2 tuple_2

Out[13]:

('Hello',
'Python',
3.14,
1.618,
True,
False,
32,
[1, 2, 3],
{1, 2, 3},
{'A': 3, 'B': 8},
(0, 1),
'Hello World!',
2022)

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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 3/9


5.06.2022 15:50 04. tuples_python - Jupyter Notebook

In [50]:

1 rep_tup = (1,2,3,4)
2 for i in rep_tup:
3 print(i)

1
2
3
4

cmp() funct on

It s to compare two tuples and returs True or False

In [55]:

1 def cmp(t1, t2):


2 return bool(t1 > t2) - bool(t1 < t2)
3 def cmp(t31, t4):
4 return bool(t3 > t4) - bool(t3 < t4)
5 def cmp(t5, t6):
6 return bool(t5 > t6) - bool(t5 < t6)
7 t1 = (1,3,5) # Here t1 is lower than t2, since the output is -1
8 t2 = (2,4,6)
9
10 t3 = (5,) # Here t3 is higher than t4 since the output is 1
11 t4 = (4,)
12
13 t5 = (3.14,) # Here t5 is equal to t6 since the output is 0
14 t6 = (3.14,)
15
16 print(cmp(t1, t2))
17 print(cmp(t3, t4))
18 print(cmp(t5, t6))

-1
1
0

m n() funct on

In [56]:

1 rep_tup = (1,2,3,4)
2 min(rep_tup)

Out[56]:

max() funct on

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 4/9


5.06.2022 15:50 04. tuples_python - Jupyter Notebook

In [58]:

1 rep_tup = (1,2,3,4)
2 max(rep_tup)

Out[58]:

tup(seq) funct on

It converts a spec f c sequence to a tuple

In [60]:

1 seq = 'ATGCGTATTGCCAT'
2 tuple(seq)

Out[60]:

('A', 'T', 'G', 'C', 'G', 'T', 'A', 'T', 'T', 'G', 'C', 'C', 'A', 'T')

Sl c ng

To obta n a new tuple from the current tuple, the sl c ng method s used.

In [14]:

1 # Obtaining a new tuple from the index 2 to index 6


2
3 tuple_1 = ('Hello', 'Python', 3.14, 1.618, True, False, 32, [1,2,3], {1,2,3}, {'A': 3, 'B': 8}, (0, 1))
4 tuple_1[2:7]

Out[14]:

(3.14, 1.618, True, False, 32)

In [18]:

1 # Obtaining tuple using 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 tuple_1[-4:-1]

Out[18]:

([1, 2, 3], {1, 2, 3}, {'A': 3, 'B': 8})

len() funct on

To obta n how many elements there are n the tuple, use len() funct on.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 5/9


5.06.2022 15:50 04. tuples_python - Jupyter Notebook

In [19]:

1 tuple_1 = ('Hello', 'Python', 3.14, 1.618, True, False, 32, [1,2,3], {1,2,3}, {'A': 3, 'B': 8}, (0, 1))
2 len(tuple_1)

Out[19]:

11

Sort ng tuple

In [22]:

1 # Tuples can be sorted and save as a new tuple.


2
3 tuple_3 = (0,9,7,4,6,2,9,8,3,1)
4 sorted_tuple_3 = sorted(tuple_3)
5 sorted_tuple_3

Out[22]:

[0, 1, 2, 3, 4, 6, 7, 8, 9, 9]

Nested tuple

In Python, a tuple wr tten ns de another tuple s known as a nested tuple.

In [25]:

1 # Take a nested tuple


2 nested_tuple =('biotechnology', (0, 5), ('fermenta on', 'ethanol'), (3.14, 'pi', (1.618, 'golden ra o')) )
3 nested_tuple

Out[25]:

('biotechnology',
(0, 5),
('fermenta on', 'ethanol'),
(3.14, 'pi', (1.618, 'golden ra o')))

In [26]:

1 # Now prin ng the each element of the nested tuple


2 print('Item 0 of nested tuple is', nested_tuple[0])
3 print('Item 1 of nested tuple is', nested_tuple[1])
4 print('Item 2 of nested tuple is', nested_tuple[2])
5 print('Item 3 of nested tuple is', nested_tuple[3])

Element 0 of nested tuple is biotechnology


Element 1 of nested tuple is (0, 5)
Element 2 of nested tuple is ('fermenta on', 'ethanol')
Element 3 of nested tuple is (3.14, 'pi', (1.618, 'golden ra o'))

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 6/9


5.06.2022 15:50 04. tuples_python - Jupyter Notebook

In [33]:

1 # Using second index to access other tuples in the nested tuple


2 print('Item 1, 0 of the nested tuple is', nested_tuple[1][0])
3 print('Item 1, 1 of the nested tuple is', nested_tuple[1][1])
4 print('Item 2, 0 of the nested tuple is', nested_tuple[2][0])
5 print('Item 2, 1 of the nested tuple is', nested_tuple[2][1])
6 print('Item 3, 0 of the nested tuple is', nested_tuple[3][0])
7 print('Item 3, 1 of the nested tuple is', nested_tuple[3][1])
8 print('Item 3, 2 of the nested tuple is', nested_tuple[3][2])
9
10 # Accesing to the items in the second nested tuples using a third index
11 print('Item 3, 2, 0 of the nested tuple is', nested_tuple[3][2][0])
12 print('Item 3, 2, 1 of the nested tuple is', nested_tuple[3][2][1])

Item 1, 0 of the nested tuple is 0


Item 1, 1 of the nested tuple is 5
Item 2, 0 of the nested tuple is fermenta on
Item 2, 1 of the nested tuple is ethanol
Item 3, 0 of the nested tuple is 3.14
Item 3, 1 of the nested tuple is pi
Item 3, 2 of the nested tuple is (1.618, 'golden ra o')
Item 3, 2, 0 of the nested tuple is 1.618
Item 3, 2, 1 of the nested tuple is golden ra o

Tuples are mmutable

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

TypeError: 'tuple' object does not support item assignment

Delete a tuple

An element n a tuple can not be deleted s nce t s mmutable.


But a whole tuple can be deleted

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 7/9


5.06.2022 15:50 04. tuples_python - Jupyter Notebook

In [36]:

1 tuple_4 = (1,3,5,7,8)
2 print('Before dele ng:', tuple_4)
3 del tuple_4
4 print('A er dele ng:', tuple_4)

Before dele ng: (1, 3, 5, 7, 8)

---------------------------------------------------------------------------
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)

NameError: name 'tuple_4' is not defined

count() method

Th s method returns the number of t me an tem occurs n a tuple.

In [39]:

1 tuple_5 = (1,1,3,3,5,5,5,5,6,6,7,8,9)
2 tuple_5.count(5)

Out[39]:

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

One element tuple

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.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 8/9


5.06.2022 15:50 04. tuples_python - Jupyter Notebook

In [45]:

1 tuple_6 = (0)
2 print(tuple_6)
3 print(type(tuple_6))
4
5 # Here, you see that the output is an integer

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'>

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 9/9


5.06.2022 15:49 05. sets_python - Jupyter Notebook

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'>

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 1/9


5.06.2022 15:49 05. sets_python - Jupyter Notebook

In [2]:

1 # Take a set
2 set1 = {'Hello Python!', 3.14, 1.618, 'Hello World!', 3.14, 1.618, True, False, 2022}
3 set1

Out[2]:

{1.618, 2022, 3.14, False, 'Hello Python!', 'Hello World!', True}

Convert ng l st to set

In [4]:

1 # A list can convert to a set


2 # Take a list
3 nlis = ['Hello Python!', 3.14, 1.618, 'Hello World!', 3.14, 1.618, True, False, 2022]
4
5 # Convert the list to a set
6 set2 = set(nlis)
7 set2

Out[4]:

{1.618, 2022, 3.14, False, 'Hello Python!', 'Hello World!', True}

Set operat ons

In [5]:

1 # Take a set
2 set3 = set(['Hello Python!', 3.14, 1.618, 'Hello World!', 3.14, 1.618, True, False, 2022])
3 set3

Out[5]:

{1.618, 2022, 3.14, False, 'Hello Python!', 'Hello World!', True}

add() 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.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 2/9


5.06.2022 15:49 05. sets_python - Jupyter Notebook

In [6]:

1 # Addi on of an element to a set


2 set3 = set(['Hello Python!', 3.14, 1.618, 'Hello World!', 3.14, 1.618, True, False, 2022])
3 [Link]('Hi, Python!')
4 set3

Out[6]:

{1.618,
2022,
3.14,
False,
'Hello Python!',
'Hello World!',
'Hi, Python!',
True}

In [7]:

1 # Addi on of the same element


2 [Link]('Hi, Python!')
3 set3
4
5 # As you see that there is only one from the added element 'Hi, Python!'

Out[7]:

{1.618,
2022,
3.14,
False,
'Hello Python!',
'Hello World!',
'Hi, Python!',
True}

update() funct on

To add mult ple elements nto the set

In [49]:

1 x_set = {6,7,8,9}
2 print(x_set)
3 x_set.update({3,4,5})
4 print(x_set)

{8, 9, 6, 7}
{3, 4, 5, 6, 7, 8, 9}

remove() funct on

To remove an element from the set

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 3/9


5.06.2022 15:49 05. sets_python - Jupyter Notebook

In [16]:

1 [Link]('Hello Python!')
2 set3
3

Out[16]:

{1.618, 2022, 3.14, False, 'Hello World!', True}

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]:

{1.618, 2022, False, 'Hello World!', True}

In [17]:

1 # To verify if the element is in the set


2 1.618 in set3

Out[17]:

True

Log c operat ons n Sets

In [18]:

1 # Take two sets


2 set4 = set(['Hello Python!', 3.14, 1.618, 'Hello World!'])
3 set5 = set([3.14, 1.618, True, False, 2022])
4
5 # Prin ng two sets
6 set4, set5

Out[18]:

({1.618, 3.14, 'Hello Python!', 'Hello World!'},


{False, True, 1.618, 3.14, 2022})

To f nd the ntersect of two sets us ng &

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 4/9


5.06.2022 15:49 05. sets_python - Jupyter Notebook

In [19]:

1 intersec on = set4 & set5


2 intersec on

Out[19]:

{1.618, 3.14}

To f nd the ntersect of two sets, use ntersect on() funct on

In [21]:

1 [Link] on(set5) # The output is the same as that of above

Out[21]:

{1.618, 3.14}

d fference() funct on

To f nd the d fference between two sets

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)

{'Hello Python!', 'Hello World!'}


{False, True, 2022}
{'Hello Python!', 'Hello World!'}
{False, True, 2022}

Set compar son

In [62]:

1 print(set4>set5)
2 print(set5>set4)
3 print(set4==set5)

False
False
False

un on() funct on

t corresponds to all the elements n both sets

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 5/9


5.06.2022 15:49 05. sets_python - Jupyter Notebook

In [24]:

1 [Link](set5)

Out[24]:

{1.618, 2022, 3.14, False, 'Hello Python!', 'Hello World!', True}

ssuperset() and ssubset() funct ons

To control f a set s a superset or a subset of another set

In [25]:

1 set(set4).issuperset(set5)

Out[25]:

False

In [27]:

1 set(set4).issubset(set5)

Out[27]:

False

In [34]:

1 print(set([3.14, 1.618]).issubset(set5))
2 print(set([3.14, 1.618]).issubset(set4))
3 print([Link]([3.14, 1.618]))
4 print([Link]([3.14, 1.618]))

True
True
True
True

m n(), max() and sum() funct ons

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 6/9


5.06.2022 15:49 05. sets_python - Jupyter Notebook

In [36]:

1 A = [1,1,2,2,3,3,4,4,5,5] # Take a list


2 B = {1,1,2,2,3,3,4,4,5,5} # Take a set
3
4 print('The minimum number of A is', min(A))
5 print('The minimum number of B is', min(B))
6 print('The maximum number of A is', max(A))
7 print('The maximum number of B is', max(B))
8 print('The sum of A is', sum(A))
9 print('The sum of B is', sum(B))
10
11 # As you see that the sum of A and B is different. Because the set takes no duplicate.

The minimum number of A is 1


The minimum number of B is 1
The maximum number of A is 5
The maximum number of B is 5
The sum of A is 30
The sum of B is 15

No mutable sequence n a set

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]:

1 set6 = {'Python', 1,2,3, [1,2,3]}


2 set6

---------------------------------------------------------------------------
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

TypeError: unhashable type: 'list'

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]

TypeError: 'set' object is not subscriptable

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 7/9


5.06.2022 15:49 05. sets_python - Jupyter Notebook

Copy the set

In [54]:

1 set8 = {1,3,5,7,9}
2 print(set8)
3 set9 = set8
4 print(set9)
5 [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

t returns a shallow copy of the or g nal set.

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.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 8/9


5.06.2022 15:49 05. sets_python - Jupyter Notebook

In [57]:

1 x = {0, 1,1,2,3,5,8,13, 21,34}


2 print( x)
3 [Link]()
4 print(x)

{0, 1, 2, 3, 34, 5, 8, 13, 21}


set()

pop() funct on

It removes and returns an arb trary set element.

In [60]:

1 x = {0, 1,1,2,3,5,8,13,21,34}
2 print(x)
3 [Link]()
4 print(x)

{0, 1, 2, 3, 34, 5, 8, 13, 21}


{1, 2, 3, 34, 5, 8, 13, 21}

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 9/9


5.06.2022 15:48 06. d ct onar es_python - Jupyter Notebook

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]:

1 # Take a sample dic onary


2
3 sample_dict = {'key_1': 3.14, 'key_2': 1.618,
4 'key_3': True, 'key_4': [3.14, 1.618],
5 'key_5': (3.14, 1.618), 'key_6': 2022, (3.14, 1.618): 'pi and golden ra o'}
6 sample_dict

Out[1]:

{'key_1': 3.14,
'key_2': 1.618,
'key_3': True,
'key_4': [3.14, 1.618],
'key_5': (3.14, 1.618),
'key_6': 2022,
(3.14, 1.618): 'pi and golden ra o'}

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 1/9


5.06.2022 15:48 06. d ct onar es_python - Jupyter Notebook

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]:

1 # Accessing to the value using the key


2 print(sample_dict['key_1'])
3 print(sample_dict['key_2'])
4 print(sample_dict['key_3'])
5 print(sample_dict['key_4'])
6 print(sample_dict['key_5'])
7 print(sample_dict['key_6'])
8 print(sample_dict[(3.14, 1.618)]) # Keys can be any immutable object like tuple

3.14
1.618
True
[3.14, 1.618]
(3.14, 1.618)
2022
pi and golden ra o

Keys

In [26]:

1 # Take a sample dic onary


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 product
7

Out[26]:

{'Aspergillus niger': 'inulinase',


'Saccharomyces cerevisiae': 'ethanol',
'Scheffersomyces s pi s': 'ethanol',
'Aspergillus sojae_1': 'mannanase',
'Streptococcus zooepidemicus': 'hyaluronic acid',
'Lactobacillus casei': 'lac c acid',
'Aspergillus sojae_2': 'polygalacturonase'}

In [27]:

1 # Retrieving the value by keys


2 print(product['Aspergillus niger'])
3 print(product['Saccharomyces cerevisiae'])
4 print(product['Scheffersomyces s pi s'])

inulinase
ethanol
ethanol

keys() funct on to get the keys n the d ct onary

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 2/9


5.06.2022 15:48 06. d ct onar es_python - Jupyter Notebook

In [28]:

1 # What are the keys in the dic onary?


2 [Link]()

Out[28]:

dict_keys(['Aspergillus niger', 'Saccharomyces cerevisiae', 'Scheffersomyces s pi s', 'Aspergillus sojae_


1', 'Streptococcus zooepidemicus', 'Lactobacillus casei', 'Aspergillus sojae_2'])

values() funct on to get the values n the d ct onary

In [29]:

1 # What are the values in the dic onary?


2 [Link]()

Out[29]:

dict_values(['inulinase', 'ethanol', 'ethanol', 'mannanase', 'hyaluronic acid', 'lac c acid', 'polygalacturona


se'])

Add t on of a new key:value pa r n the d ct onary

In [31]:

1 product['Yarrovia lipoly ca'] = 'microbial oil'


2 product

Out[31]:

{'Aspergillus niger': 'inulinase',


'Saccharomyces cerevisiae': 'ethanol',
'Scheffersomyces s pi s': 'ethanol',
'Aspergillus sojae_1': 'mannanase',
'Streptococcus zooepidemicus': 'hyaluronic acid',
'Lactobacillus casei': 'lac c acid',
'Aspergillus sojae_2': 'polygalacturonase',
'Yarrovia lipoly ca': 'microbial oil'}

Delete an tem us ng del() funct on n the d ct onary by key

In [32]:

1 del(product['Aspergillus niger'])
2 del(product['Aspergillus sojae_1'])
3 product

Out[32]:

{'Saccharomyces cerevisiae': 'ethanol',


'Scheffersomyces s pi s': 'ethanol',
'Streptococcus zooepidemicus': 'hyaluronic acid',
'Lactobacillus casei': 'lac c acid',
'Aspergillus sojae_2': 'polygalacturonase',
'Yarrovia lipoly ca': 'microbial oil'}

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 3/9


5.06.2022 15:48 06. d ct onar es_python - Jupyter Notebook

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.

NameError: name 'product' is not defined

Ver f cat on us ng n or not n

In [17]:

1 print('Saccharomyces cerevisiae' in product)


2 print('Saccharomyces cerevisiae' not in product)

True
False

d ct() funct on

Th s funct on s used to create a d ct onary

In [19]:

1 dict_sample = dict(family = 'music', type='pop', year='2022' , name='happy new year')


2 dict_sample

Out[19]:

{'family': 'music', 'type': 'pop', 'year': '2022', 'name': 'happy new year'}

In [21]:

1 # Numerical index is not used to take the 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

clear() funct ons

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 4/9


5.06.2022 15:48 06. d ct onar es_python - Jupyter Notebook

It removes all the tems n the d ct onary and returns an empty d ct onary

In [34]:

1 dict_sample = dict(family = 'music', type='pop', year='2022' , name='happy new year')


2 dict_sample.clear()
3 dict_sample

Out[34]:

{}

copy() funct on

It returns a shallow copy of the ma n d ct onary

In [35]:

1 sample_original = dict(family = 'music', type='pop', year='2022' , name='happy new year')


2 sample_copy = sample_original.copy()
3 print(sample_original)
4 print(sample_copy)

{'family': 'music', 'type': 'pop', 'year': '2022', 'name': 'happy new year'}
{'family': 'music', 'type': 'pop', 'year': '2022', 'name': 'happy new year'}

In [36]:

1 # This method can be made usign '=' sign


2 sample_copy = sample_original
3 print(sample_copy)
4 print(sample_original)

{'family': 'music', 'type': 'pop', 'year': '2022', 'name': 'happy new year'}
{'family': 'music', 'type': 'pop', 'year': '2022', 'name': 'happy new year'}

pop() funct on

Th s funct on s used to remove a spec f c tem from the d ct onary

In [38]:

1 sample_original = dict(family = 'music', type='pop', year='2022' , name='happy new year')


2 print(sample_original.pop('type'))
3 print(sample_original)
4

pop
{'family': 'music', 'year': '2022', 'name': 'happy new year'}

pop tem() funct on

It s used to remove the ab trary tems from the d ct onary and returns as a tuple.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 5/9


5.06.2022 15:48 06. d ct onar es_python - Jupyter Notebook

In [39]:

1 sample_original = dict(family = 'music', type='pop', year='2022' , name='happy new year')


2 print(sample_original.popitem())
3 print(sample_original)

('name', 'happy new year')


{'family': 'music', 'type': 'pop', 'year': '2022'}

get() 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]:

1 sample_original = dict(family = 'music', type='pop', year='2022' , name='happy new year')


2 print(sample_original.get('family'))
3 print(sample_original.get(3))

music
None

fromkeys() 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]:

1 keys = {'A', 'T', 'C', 'G'}


2 sequence = [Link](keys)
3 print(sequence)

{'C': None, 'T': None, 'A': None, 'G': None}

update() funct on

It ntegrates a d ct onary w th another d ct onary or w th an terable of key:value pa rs.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 6/9


5.06.2022 15:48 06. d ct onar es_python - Jupyter Notebook

In [45]:

1 product = {'Aspergillus niger': 'inulinase', 'Saccharomyces cerevisiae': 'ethanol',


2 'Scheffersomyces s pi s': 'ethanol', 'Aspergillus sojae_1': 'mannanase',
3 'Streptococcus zooepidemicus': 'hyaluronic acid', 'Lactobacillus casei': 'lac c acid',
4 'Aspergillus sojae_2': 'polygalacturonase'}
5
6 sample_original = dict(family = 'music', type='pop', year='2022' , name='happy new year')
7
8 [Link](sample_original)
9 print(product)

{'Aspergillus niger': 'inulinase', 'Saccharomyces cerevisiae': 'ethanol', 'Scheffersomyces s pi s': 'ethanol',


'Aspergillus sojae_1': 'mannanase', 'Streptococcus zooepidemicus': 'hyaluronic acid', 'Lactobacillus case
i': 'lac c acid', 'Aspergillus sojae_2': 'polygalacturonase', 'family': 'music', 'type': 'pop', 'year': '2022', 'na
me': 'happy new year'}

tems() funct on

It returns a l st of key:value pa rs n a d ct onary. The elements n the l sts are tuples.

In [46]:

1 product = {'Aspergillus niger': 'inulinase', 'Saccharomyces cerevisiae': 'ethanol',


2 'Scheffersomyces s pi s': 'ethanol', 'Aspergillus sojae_1': 'mannanase',
3 'Streptococcus zooepidemicus': 'hyaluronic acid', 'Lactobacillus casei': 'lac c acid',
4 'Aspergillus sojae_2': 'polygalacturonase'}
5
6 [Link]()

Out[46]:

dict_items([('Aspergillus niger', 'inulinase'), ('Saccharomyces cerevisiae', 'ethanol'), ('Scheffersomyces s


pi s', 'ethanol'), ('Aspergillus sojae_1', 'mannanase'), ('Streptococcus zooepidemicus', 'hyaluronic acid'),
('Lactobacillus casei', 'lac c acid'), ('Aspergillus sojae_2', 'polygalacturonase')])

Iterat ng d ct onary

A d ct onary can be terated us ng the for loop

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 7/9


5.06.2022 15:48 06. d ct onar es_python - Jupyter Notebook

In [11]:

1 # 'for' loop print all the keys in the dic onary


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
8 for k in product:
9 print(k)

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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 8/9


5.06.2022 15:48 06. d ct onar es_python - Jupyter Notebook

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)

('Aspergillus niger', 'inulinase')


('Saccharomyces cerevisiae', 'ethanol')
('Scheffersomyces s pi s', 'ethanol')
('Aspergillus sojae_1', 'mannanase')
('Streptococcus zooepidemicus', 'hyaluronic acid')
('Lactobacillus casei', 'lac c acid')
('Aspergillus sojae_2', 'polygalacturonase')

In [17]:

1 product = {'Aspergillus niger': 'inulinase', 'Saccharomyces cerevisiae': 'ethanol',


2 'Scheffersomyces s pi s': 'ethanol', 'Aspergillus sojae_1': 'mannanase',
3 'Streptococcus zooepidemicus': 'hyaluronic acid', 'Lactobacillus casei': 'lac c acid',
4 'Aspergillus sojae_2': 'polygalacturonase'}
5
6 for x, y in [Link]():
7 print(x, y)

Aspergillus niger inulinase


Saccharomyces cerevisiae ethanol
Scheffersomyces s pi s ethanol
Aspergillus sojae_1 mannanase
Streptococcus zooepidemicus hyaluronic acid
Lactobacillus casei lac c acid
Aspergillus sojae_2 polygalacturonase

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 9/9


5.06.2022 15:59 07. cond t ons_python - Jupyter Notebook

Python Tutor al
Created by Mustafa Germec, PhD

7. Cond t ons n Python

Compar son operators


Compar son operat ons compare some value or operand and based on a cond t on, produce a Boolean. Python
has s x compar son operators as below:

Less than (<)


Less than or equal to (<=)
Greater than (>)
Greater than or equal to (>=)
Equal to (==)
Not equal to (!=)

In [1]:

1 # Take a variable
2 golden_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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 1/9


5.06.2022 15:59 07. cond t ons_python - Jupyter Notebook

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.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 2/9


5.06.2022 15:59 07. cond t ons_python - Jupyter Notebook

In [17]:

1 # Compare strings
2 print('Hello' == 'Python')
3 print('Hello' != 'Python')
4 print('Hello' <= 'Python')
5 print('Hello' >= 'Python')
6 print('Hello' < 'Python')
7 print('Hello' > 'Python')
8 print('B'>'A') # According to ASCII table, the values of A and B are equal 65 and 66, 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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 3/9


5.06.2022 15:59 07. cond t ons_python - Jupyter Notebook

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!')

The number pi 3.14 is greater than the golden ra o 1.618.


Done!

In [2]:

1 if 2:
2 print('Hello, python!')

Hello, python!

In [5]:

1 if True:
2 print('This is true.')

This is true.

else statement

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 4/9


5.06.2022 15:59 07. cond t ons_python - Jupyter Notebook

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!')

The golden ra o 1.618 is lower than the number pi 3.14.


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!')

You should go to kindergarten.


Done!

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 5/9


5.06.2022 15:59 07. cond t ons_python - Jupyter Notebook

In [25]:

1 album_year = 2000
2 album_year = 1990
3
4 if album_year >= 1995:
5 print('Album year is higher than 1995.')
6
7 print('Done!')

Done!

In [26]:

1 album_year = 2000
2 # album_year = 1990
3
4 if album_year >= 1995:
5 print('Album year is higher than 1995.')
6 else:
7 print('Album year is lower than 1995.')
8
9 print('Done!')

Album year is higher than 1995.


Done!

In [43]:

1 imdb_point = 9.0
2 if imdb_point > 8.5:
3 print('The movie could win Oscar.')

The movie could win Oscar.

In [13]:

1 movie_ra ng = float(input('Enter a ra ng number:'))


2
3 print(f'The entered movie ra ng is: {movie_ra ng}')
4
5 if movie_ra ng > 8.5:
6 print('The movie is awesome with {} ra ng and you should watch it.'.format(movie_ra ng))
7 else:
8 print('The movie has merit to be watched with {} ra ng.'.format(movie_ra ng))

The entered movie ra ng is: 8.2


The movie has merit to be watched with 8.2 ra ng.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 6/9


5.06.2022 15:59 07. cond t ons_python - Jupyter Notebook

In [18]:

1 note = float(input('Enter a note:'))


2
3 print(f'The entered note value is: {note}')
4
5 if note >= 90 and note <= 100:
6 print('The le er grade is AA.')
7 elif note >= 85 and note <= 89:
8 print('The le er grade is BA.')
9 elif note >= 80 and note <= 84:
10 print('The le er grade is BB.')
11 elif note >= 75 and note <= 79:
12 print('The le er grade is CB.')
13 elif note >= 70 and note <= 74:
14 print('The le er grade is CC.')
15 elif note >= 65 and note <= 69:
16 print('The le er grade is DC.')
17 elif note >= 60 and note <= 64:
18 print('The le er grade is DD.')
19 elif note >=55 and note <= 59:
20 print('The le er grade is ED.')
21 elif note >=50 and note <= 54:
22 print('The le er grade is EE.')
23 elif note >=45 and note <=49:
24 print('The le er grade is FE.')
25 else:
26 print('The le er grade is FF.')

The entered note value is: 74.0


The le er grade is CC.

In [17]:

1 number = int(input('Enter a number:'))


2
3 print(f'The entered number is: {number}')
4
5 if number %2 == 0:
6 print(f'The entered number {number} is even')
7 else:
8 print(f'The entered number {number} is odd')

The entered number is 12


The entered number 12 is even

Log cal operators


Log cal operators are used to comb ne cond t onal statements.

and: Returns True f both statements are true


or: Returns True f one of the statements s true
not: Reverse the result, returns False f the result s true

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 7/9


5.06.2022 15:59 07. cond t ons_python - Jupyter Notebook

and

In [27]:

1 birth_year = 1990
2 if birth_year > 1989 and birth_year < 1995:
3 print('You were born between 1990 and 1994')
4 print('Done!')

You were born between 1990 and 1994


Done!

In [23]:

1 x = int(input('Enter a number:'))
2 y = int(input('Enter a number: '))
3 z = int(input('Enter a number:'))
4
5 print(f'The entered numbers for x, y, and z are {x}, {y}, and {z}, 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!')

You were not born in 1980s.


Done!

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 8/9


5.06.2022 15:59 07. cond t ons_python - Jupyter Notebook

not

In [29]:

1 birth_year = 1990
2 if not birth_year == 1991:
3 print('The year of birth is not 1991.')

The year of birth is not 1991.

In [15]:

1 birth_year = int(input('Enter a year of birth: '))


2
3 print(f'The entered year of birth is: {birth_year}')
4
5 if birth_year < 1985 or birth_year == 1991 or birth_year == 1995:
6 print(f'You were born in {birth_year}')
7 else:
8 # For instance, if your year of birth is 1993
9 print(f'Your year of birth with {birth_year} is wrong.')

The entered year of birth is: 1993


Your year of birth with 1993 is wrong.

In [16]:

1 birth_year = int(input('Enter a year of birth: '))


2
3 print(f'The entered year of birth is: {birth_year}')
4
5 if birth_year < 1985 or birth_year == 1991 or birth_year == 1995:
6 # For instance, if your year of birth is 1995
7 print(f'You were born in {birth_year}')
8 else:
9 print(f'Your year of birth with {birth_year} is wrong.')

The entered year of birth is: 1995


You were born in 1995

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 9/9


5.06.2022 16:00 08. loops_python - Jupyter Notebook

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]:

1 # Take a range() func on


2 print(range(5))
3 print(range(10))

range(0, 5)
range(0, 10)

for loop
The for loop enables you to execute a code block mult ple t mes.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 1/11


5.06.2022 16:00 08. loops_python - Jupyter Notebook

In [4]:

1 # Take an example
2 # Diectly accessing to the elements in the list
3
4 years = [2005, 2006, 2007, 2008, 2009, 2010]
5
6 for i in years:
7 print(i)

2005
2006
2007
2008
2009
2010

In [10]:

1 # Again, directly accessing to the elements in the list


2 years = [2005, 2006, 2007, 2008, 2009, 2010]
3
4 for year in years:
5 print(year)

2005
2006
2007
2008
2009
2010

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 2/11


5.06.2022 16:00 08. loops_python - Jupyter Notebook

In [6]:

1 # Take an example
2 years = [2005, 2006, 2007, 2008, 2009, 2010]
3
4 for i in range(len(years)):
5 print(years[i])

2005
2006
2007
2008
2009
2010

In [8]:

1 # Another for loop example


2 for i in range(2, 12):
3 print(i)

2
3
4
5
6
7
8
9
10
11

In [16]:

1 # Striding in for loop


2 for i in range(2, 12, 3):
3 print(i)

2
5
8
11

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 3/11


5.06.2022 16:00 08. loops_python - Jupyter Notebook

In [12]:

1 # Changing the elements in the list


2 languages = ['Java', 'JavaScript', 'C', 'C++', 'PHP']
3
4 for i in range(len(languages)):
5 print('Before language', i, 'is', languages[i])
6 languages[i] = 'Python'
7 print('A er language', i, 'is', languages[i])

Before language 0 is Java


A er language 0 is Python
Before language 1 is JavaScript
A er language 1 is Python
Before language 2 is C
A er language 2 is Python
Before language 3 is C++
A er language 3 is Python
Before language 4 is PHP
A er language 4 is Python

In [14]:

1 # Enumaera on of the elements in the list


2 languages = ['Python', 'Java', 'JavaScript', 'C', 'C++', 'PHP']
3
4 for index, language in enumerate(languages):
5 print(index, language)

0 Python
1 Java
2 JavaScript
3C
4 C++
5 PHP

In [30]:

1 # Take the numbers between -3 and 6 using for loop


2 # Use range() func on
3
4 for i in range(-3, 7):
5 print(i)

-3
-2
-1
0
1
2
3
4
5
6

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 4/11


5.06.2022 16:00 08. loops_python - Jupyter Notebook

In [31]:

1 # Take a list and print the elements using for loop


2 languages = ['Python', 'Java', 'JavaScript', 'C', 'C++', 'PHP']
3
4 for i in range(len(languages)):
5 print(i, languages[i])

0 Python
1 Java
2 JavaScript
3C
4 C++
5 PHP

In [120]:

1 number1 = int(input('Enter a number:'))


2 number2 = int(input('Enter a number:'))
3 print(f'The entered numbers are {number1} and {number2}.')
4 for i in range(0, 11):
5 print(('%d x %d = %d' %(number1, i, number1*i)), ',', ('%d x %d = %d' %(number2, i, number2*i )))

The entered numbers are 7 and 9.


7x0=0,9x0=0
7x1=7,9x1=9
7 x 2 = 14 , 9 x 2 = 18
7 x 3 = 21 , 9 x 3 = 27
7 x 4 = 28 , 9 x 4 = 36
7 x 5 = 35 , 9 x 5 = 45
7 x 6 = 42 , 9 x 6 = 54
7 x 7 = 49 , 9 x 7 = 63
7 x 8 = 56 , 9 x 8 = 72
7 x 9 = 63 , 9 x 9 = 81
7 x 10 = 70 , 9 x 10 = 90

Add t on and average calculat on n for loop

In [2]:

1 # Take a list
2 nlis = [0.577, 2.718, 3.14, 1.618, 1729, 6, 37]
3
4 # Write a for loop for 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))

The total value of the numbers in the list is 1780.053


The total value of the numbers in the list is 254.29328571428573

for-else statement
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_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.')

1, 2, 3, 4, 5, These are numbers from 1 to 5.

nested for loop

In [112]:

1 num = int(input('Enter a number:'))


2
3 print(f'The entered the number is {num}.')
4 i, j = 0, 0
5 for i in range(0, num):
6 print()
7 for j in range(0, i+1):
8 print('+', end='')

The entered the number is 10.

+
++
+++
++++
+++++
++++++
+++++++
++++++++
+++++++++
++++++++++

cont nue n for loop

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 6/11


5.06.2022 16:00 08. loops_python - Jupyter Notebook

In [116]:

1 # Take a list
2 nlis = [1,2,4,5,6,7,8,9,10,11,12,13,14]
3 for i in nlis:
4 if i == 5:
5 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'

break n for loop

In [118]:

1 # Take a list
2 nlis = [1,2,4,5,6,7,8,9,10,11,12,13,14]
3 for i in nlis:
4 if i == 5:
5 break
6 print(i)
7
8 """
9 You see that the output includes the numbers before 5.
10 The break 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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 7/11


5.06.2022 16:00 08. loops_python - Jupyter Notebook

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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 8/11


5.06.2022 16:00 08. loops_python - Jupyter Notebook

In [25]:

1 # Take an example
2 years = [2005, 2006, 2007, 2008, 2009, 2010]
3
4 index = 0
5
6 year = years[0]
7
8 while year !=2008:
9 print(year)
10 index+=1
11 year = years[index]
12 print('It gives us only', index, '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]:

1 # Print the movie ra ngs gretater than 6.


2 movie_ra ng = [8.0, 7.5, 5.4, 9.1, 6.3, 6.5, 2.1, 4.8, 3.3]
3
4 index = 0
5 ra ng = movie_ra ng[0]
6
7 while ra ng>=6:
8 print(ra ng)
9 index += 1
10 ra ng = movie_ra ng[index]
11 print('There is only', index, 'movie ra ng, because the loop stops when it meets with the number lower than 6.')

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 # Print the movie ra ngs gretater than 6.


2 movie_ra ng = [8.0, 7.5, 5.4, 9.1, 6.3, 6.5, 2.1, 4.8, 3.3]
3
4 index = 0
5 for i in range(len(movie_ra ng)):
6 if movie_ra ng[i] >= 6:
7 index += 1
8 print(index, movie_ra ng[i])
9 print('There is only', index, 'films gretater than movie ra ng 6')

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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 9/11


5.06.2022 16:00 08. loops_python - Jupyter Notebook

In [91]:

1 # Adding the element in a list to a new list


2 fruits = ['banana', 'apple', 'banana', 'orange', 'kiwi', 'banana', 'Cherry', 'Grapes']
3
4 new_fruits = []
5
6 index = 0
7 while fruits[index] == 'banana':
8 new_fruits.append(fruits[index])
9 index += 1
10 print(new_fruits)

['banana']

In [119]:

1 number1 = int(input('Enter a number:'))


2 number2 = int(input('Enter a number:'))
3 print(f'The entered numbers are {number1} and {number2}.')
4
5 i=0
6 while i<=10:
7 print(('%d x %d = %d' %(number1, i, number1*i)), ',', ('%d x %d = %d' %(number2, i, number2*i )))
8 i+=1
9

The entered numbers are 8 and 9.


8x0=0,9x0=0
8x1=8,9x1=9
8 x 2 = 16 , 9 x 2 = 18
8 x 3 = 24 , 9 x 3 = 27
8 x 4 = 32 , 9 x 4 = 36
8 x 5 = 40 , 9 x 5 = 45
8 x 6 = 48 , 9 x 6 = 54
8 x 7 = 56 , 9 x 7 = 63
8 x 8 = 64 , 9 x 8 = 72
8 x 9 = 72 , 9 x 9 = 81
8 x 10 = 80 , 9 x 10 = 90

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.')

0 1 2 3 4 5 It gives us the numbers between 0 and 5.

cont nue n wh le loop

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 10/11


5.06.2022 16:00 08. loops_python - Jupyter Notebook

In [122]:

1 i=0
2
3 while i<=5:
4 print(i)
5 i+=1
6 if i == 3:
7 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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 11/11


5.06.2022 16:01 09. funct ons_python - Jupyter Notebook

Python Tutor al
Created by Mustafa Germec, PhD

9. Funct ons n Python


In Python, a funct on s a group of related statements that performs a spec f c task.
Funct ons help break our program nto smaller and modular chunks. * As our program grows larger and
larger, funct ons make t more organ zed and manageable.
Furthermore, t avo ds repet t on and makes the code reusable.
There are two types of funct ons :
Pre-def ned funct ons
User def ned funct ons
In Python a funct on s def ned us ng the def keyword followed by the funct on name and parentheses ().
Keyword def that marks the start of the funct on header.
A funct on name to un quely dent fy the funct on.
Funct on nam ng follows the same rules of wr t ng dent f ers n Python.
Parameters (arguments) through wh ch we pass values to a funct on. They are opt onal.
A colon (:) to mark the end of the funct on header.
Opt onal documentat on str ng (docstr ng) to descr be what the funct on does.
One or more val d python statements that make up the funct on body.
Statements must have the same ndentat on level (usually 4 spaces).
An opt onal return statement to return a value from the funct on.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 1/14


5.06.2022 16:01 09. funct ons_python - Jupyter Notebook

In [9]:

1 # Take a func on sample


2 # Mathema cal opera ons in a func on
3
4 def process(x):
5 y1 = x-8
6 y2 = x+8
7 y3 = x*8
8 y4 = x/8
9 y5 = x%8
10 y6 = x//8
11 print(f'If you make the above opera ons with {x}, the results will be {y1}, {y2}, {y3}, {y4}, {y5}, {y6}.')
12 return y1, y2, y3, y4, y5, y6
13
14 process(5)

If you make the above opera ons with 5, the results will be -3, 13, 40, 0.625, 5, 0.

Out[9]:

(-3, 13, 40, 0.625, 5, 0)

You can request help us ng help() funct on

In [10]:

1 help(process)

Help on func on process in module __main__:

process(x)

Call the funct on aga n w th the number 3.14

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]:

(-4.859999999999999, 11.14, 25.12, 0.3925, 3.14, 0.0)

Funct ons w th mult ple parameters

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 2/14


5.06.2022 16:01 09. funct ons_python - Jupyter Notebook

In [2]:

1 # Define a func on with mul ple elements


2 def mult(x, y):
3 z = 2*x + 5*y + 45
4 return z
5
6 output = mult(3.14, 1.618) # You can yield the output by assigning to a variable
7 print(output)
8 print(mult(3.14, 1.618)) # You can obtain the result directly
9 mult(3.14, 1.618) # This is also another version

59.370000000000005
59.370000000000005

Out[2]:

59.370000000000005

In [20]:

1 # Call again the defined func on with different arguments


2 print(mult(25, 34))

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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 3/14


5.06.2022 16:01 09. funct ons_python - Jupyter Notebook

In [8]:

1 # It starts the gloabal variable


2 a = 3.14
3
4 # call func on and return func on
5 y = func on(a)
6 print(y)

If you make the above opera ons with 3.14, the results will be 14.500520000000002.
14.500520000000002

In [9]:

1 # Enter a number directly as a parameter


2 func on(2.718)

If you make the above opera ons with 2.718, the results will be 13.23452.

Out[9]:

13.23452

W thout return statement, the funct on returns None

In [10]:

1 # Define a func on with and without return statement


2 def msg1():
3 print('Hello, Python!')
4
5 def msg2():
6 print('Hello, World!')
7 return None
8
9 msg1()
10 msg2()

Hello, Python!
Hello, World!

In [15]:

1 # 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

Concatetant on of two str ngs

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 4/14


5.06.2022 16:01 09. funct ons_python - Jupyter Notebook

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'

S mpl c ty of funct ons

In [26]:

1 # The following codes are not used again.


2 x = 2.718
3 y = 0.577
4 equa on = x*y + x+y - 37
5 if equa on>0:
6 equa on = 6
7 else: equa on = 37
8
9 equa on

Out[26]:

37

In [27]:

1 # The following codes are not used again.


2 x=0
3 y=0
4 equa on = x*y + x+y - 37
5 if equa on<0:
6 equa on = 0
7 else: equa on = 37
8
9 equa on

Out[27]:

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 5/14


5.06.2022 16:01 09. funct ons_python - Jupyter Notebook

In [28]:

1 # The following codes can be write as a func on.


2 def func on(x, y):
3 equa on = x*y + x+y - 37
4 if equa on>0:
5 equa on = 6
6 else: equa on = 37
7 return equa on
8
9 x = 2.718
10 y = 0.577
11 func on(x, y)

Out[28]:

37

In [29]:

1 # The following codes can be write as a func on.


2 def func on(x, y):
3 equa on = x*y + x+y - 37
4 if equa on<0:
5 equa on = 6
6 else: equa on = 37
7 return equa on
8
9 x=0
10 y=0
11 func on(x, y)

Out[29]:

Predef ned funct ons l ke pr nt(), sum(), len(), m n(), max(), nput()

In [31]:

1 # print() is a built-in func on


2 special_numbers = [0.577, 2.718, 3.14, 1.618, 1729, 6, 28, 37]
3 print(special_numbers)

[0.577, 2.718, 3.14, 1.618, 1729, 6, 28, 37]

In [32]:

1 # The func on sum() add all elements in a list or a tuple


2 sum(special_numbers)

Out[32]:

1808.053

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 6/14


5.06.2022 16:01 09. funct ons_python - Jupyter Notebook

In [33]:

1 # The func on len() gives us the length of the list or tuple


2 len(special_numbers)

Out[33]:

Us ng cond t ons and loops n funct ons

In [44]:

1 # Define a func on including condi ons if/else


2
3 def fermenta on(microorganism, substrate, product, ac vity):
4 print(microorganism, substrate, product, ac vity)
5 if ac vity < 1000:
6 return f'The fermenta on process was unsuccessful with the {product} ac vity of {ac vity} U/mL from {substrate}
7 else:
8 return f'The fermenta on process was successful with the {product} ac vity of {ac vity} U/mL from {substrate} us
9
10 result1 = fermenta on('Aspergillus niger', 'molasses', 'inulinase', 1800)
11 print(result1)
12 print()
13 result2 = fermenta on('Aspergillus niger', 'molasses', 'inulinase', 785)
14 print(result2)
15

Aspergillus niger molasses inulinase 1800


The fermenta on process was successful with the inulinase ac vity of 1800 U/mL from molasses using A
spergillus niger.

Aspergillus niger molasses inulinase 785


The fermenta on process was unsuccessful with the inulinase ac vity of 785 U/mL from molasses using
Aspergillus niger. You should repeat the fermenta on process.

In [50]:

1 # Define a func on using the loop 'for'


2
3 def fermenta on(content):
4 for parameters in content:
5 print(parameters)
6
7 content = ['S rred-tank bioreactor' ,'30°C temperature', '200 rpm agita on speed', '1 vvm aera on', '1% (v/v) inoculum
8 fermenta on(content)

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

Adjust ng default values of ndependent var ables n funct ons

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 7/14


5.06.2022 16:01 09. funct ons_python - Jupyter Notebook

In [53]:

1 # Define a func on adjus ng the default value of the variable


2
3 def ra ng_value(ra ng = 5.5):
4 if ra ng < 8:
5 return f'You should not watch this film with the ra ng value of {ra ng}'
6 else:
7 return f'You should watch this film with the ra ng value of {ra ng}'
8
9 print(ra ng_value())
10 print(ra ng_value(8.6))

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

Global var ables

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]:

1 # Define a func on for a global variable


2 language = 'Python'
3
4 def lang(language):
5 global_var = language
6 print(f'{language} is a program language.')
7
8 lang(language)
9 lang(global_var)
10
11 """
12 The output gives a NameError, since all variables in the func on are local variables,
13 so variable assignment is not persistent outside the func on.
14 """

Python is a program language.

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_21468/[Link] in <module>
7
8 lang(language)
----> 9 lang(global_var)

NameError: name 'global_var' is not defined

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 8/14


5.06.2022 16:01 09. funct ons_python - Jupyter Notebook

In [58]:

1 # Define a func on for a global variable


2 language = 'JavaScript'
3
4 def lang(language):
5 global global_var
6 global_var = 'Python'
7 print(f'{language} is a programing language.')
8
9 lang(language)
10 lang(global_var)

JavaScript is a programing language.


Python is a programing language.

Var ables n funct ons

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]:

1 process = 'Con nuous fermenta on'


2
3 def fermenta on(process_name):
4 if process_name == process:
5 return '0.5 g/L/h.'
6 else:
7 return '0.25 g/L/h.'
8
9 print('The produc ovity in con nuous fermenta on is', fermenta on('Con nuous fermenta on'))
10 print('The produc ovity in batch fermenta on is', fermenta on('Batch fermenta on'))
11 print('Con nuous fermenta on has many advantages over batch fermenta on.')
12 print(f'My favourite process is {process}.')

The produc ovity in con nuous fermenta on is 0.5 g/L/h.


The produc ovity in batch fermenta on is 0.25 g/L/h.
Con nuous fermenta on has many advantages over batch fermenta on.
My favourite process is Con nuous fermenta on.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 9/14


5.06.2022 16:01 09. funct ons_python - Jupyter Notebook

In [77]:

1 # If the variable 'process' is deleted, it returns a NameError as follows


2 del process
3
4 # Since the variable 'process' is deleted, the following func on is an example of local variable
5 def fermenta on(process_name):
6 process = 'Con nuous 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('Con nuous fermenta on has many advantages over batch fermenta on.')
15 print(f'My favourite process is {process}.')

The produc ovity in con nuous fermenta on is 0.5 g/L/h.


The produc ovity in batch fermenta on is 0.25 g/L/h.
Con nuous fermenta on has many advantages over batch fermenta on.

---------------------------------------------------------------------------
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}.')

NameError: name 'process' is not defined

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}.')

The produc ovity in con nuous fermenta on is 0.25 g/L/h.


The produc ovity in batch fermenta on is 0.5 g/L/h.
My favourite process is Con nuous fermenta on.

(args) and/or (*args) and Funct ons

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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 10/14


5.06.2022 16:01 09. funct ons_python - Jupyter Notebook

In [84]:

1 # Define a func on regarding a tuple example


2 def func on(*args):
3 print('Number of elements is', len(args))
4 for element in args:
5 print(element)
6
7 func on('Aspergillus niger', 'inulinase', 'batch', '1800 U/mL ac vity')
8 print()
9 func on('Saccharomyces cerevisia', 'ethanol', 'con nuous', '45% yield', 'carob')
10

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]:

1 # Another example regarding 'args'


2 def total(*args):
3 total = 0
4 for i in args:
5 total += i
6 return total
7
8 print('The total of the numbers is', total(0.577, 2.718, 3.14, 1.618, 1729, 6, 37))

The total of the numbers is 1780.053

In [88]:

1 # Define a func on regarding a dic onary example


2 def func on(**args):
3 for key in args:
4 print(key, ':', args[key])
5
6 func on(Micoorganism='Aspergillus niger', Substrate='Molasses', Product='Inulinase', Fermenta on_mode='Batch', A

Micoorganism : Aspergillus niger


Substrate : Molasses
Product : Inulinase
Fermenta on_mode : Batch
Ac vity : 1800 U/mL

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 11/14


5.06.2022 16:01 09. funct ons_python - Jupyter Notebook

In [96]:

1 # Define a func on regarding the addi on of elements into a list


2 def addi on(nlist):
3 [Link](3.14)
4 [Link](1.618)
5 [Link](1729)
6 [Link](6)
7 [Link](37)
8
9 my_list= [0.577, 2.718]
10 addi on(my_list)
11 print(my_list)
12 print(sum(my_list))
13 print(min(my_list))
14 print(max(my_list))
15 print(len(my_list))

[0.577, 2.718, 3.14, 1.618, 1729, 6, 37]


1780.053
0.577
1729
7

Doctst ng n Funct ons

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))

The following func on returns the sum of two parameters.


5.8580000000000005

Recurs ve funct ons

In [103]:

1 # Calcula ng the factorial of a certain number.


2
3 def factorial(number):
4 if number == 0:
5 return 1
6 else:
7 return number*factorial(number-1)
8
9 print('The value is', factorial(6))

The value is 720

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 12/14


5.06.2022 16:01 09. funct ons_python - Jupyter Notebook

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))

The total of first ten numbers is 55

Nested funct ons

In [111]:

1 # Define a func on that add a number to another number


2 def added_num(num1):
3 def incremented_num(num1):
4 num1 = num1 + 1
5 return num1
6 num2 = incremented_num(num1)
7 print(num1, '------->>', num2)
8
9 added_num(25)

25 ------->> 26

nonlocal funct on

In [112]:

1 # Define a func on regarding 'nonlocal' func on


2 def print_year():
3 year = 1990
4 def print_current_year():
5 nonlocal year
6 year += 32
7 print('Current year is', year)
8 print_current_year()
9 print_year()

Current year is 2022

In [117]:

1 # Define a func on giving a message


2 def func on(name):
3 msg = 'Hi ' + name
4 return msg
5
6 name = input('Enter a name: ')
7 print(func on(name))

Hi Mustafa

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 13/14


5.06.2022 16:01 09. funct ons_python - Jupyter Notebook

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 14/14


5.06.2022 16:04 10. except on_handl ng_python - Jupyter Notebook

Python Tutor al
Created by Mustafa Germec, PhD

10. Except on Handl ng n Python


An except on s an event, wh ch occurs dur ng the execut on of a program that d srupts the normal flow of
the program's nstruct ons.
In general, when a Python scr pt encounters a s tuat on that t cannot cope w th, t ra ses an except on.
An except on s a Python object that represents an error.
When a Python scr pt ra ses an except on, t must e ther handle the except on mmed ately otherw se t
term nates and qu ts.
If you have some susp c ous code that may ra se an except on, you can defend your program by plac ng
the susp c ous code n a try: block.
After the try: block, nclude an except: statement, followed by a block of code wh ch handles the problem
as elegantly as poss ble.
Common except ons
ZeroD v s onError
NameError
ValueError
IOError
EOFError
Identat onError

ZeroD v s onError

In [1]:

1 # If a number is divided by 0, it gives a ZeroDivisionError.


2 try:
3 1/0
4 except ZeroDivisionError:
5 print('This code gives a ZeroDivisionError.')
6
7 print(1/0)

This code gives a ZeroDivisionError.

---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/[Link] in <module>
5 print('This code gives a ZeroDivisionError.')
6
----> 7 print(1/0)

ZeroDivisionError: division by zero

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 1/10


5.06.2022 16:04 10. except on_handl ng_python - Jupyter Notebook

In [2]:

1 nlis = []
2 count = 0
3 try:
4 mean = count/len(nlis)
5 print('The mean value is', mean)
6 except ZeroDivisionError:
7 print('This code gives a ZeroDivisionError')
8
9 print(count/len(nlis))

This code gives a ZeroDivisionError

---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/[Link] in <module>
7 print('This code gives a ZeroDivisionError')
8
----> 9 print(count/len(nlis))

ZeroDivisionError: division by zero

In [3]:

1 # The following code is like 1/0.


2 try:
3 True/False
4 except ZeroDivisionError:
5 print('The code gives a ZeroDivisionError.')
6
7 print(True/False)

The code gives a ZeroDivisionError.

---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/[Link] in <module>
5 print('The code gives a ZeroDivisionError.')
6
----> 7 print(True/False)

ZeroDivisionError: division by zero

NameError

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 2/10


5.06.2022 16:04 10. except on_handl ng_python - Jupyter Notebook

In [4]:

1 nlis = []
2 count = 0
3 try:
4 mean = count/len(nlis)
5 print('The mean value is', mean)
6 except ZeroDivisionError:
7 print('This code gives a ZeroDivisionError')
8
9 # Since the variable 'mean' is not defined, it gives us a 'NameError
10 print(mean)

This code gives a ZeroDivisionError

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/[Link] in <module>
8
9 # Since the variable 'mean' is not defined, it gives us a 'NameError
---> 10 print(mean)

NameError: name 'mean' is not defined

In [5]:

1 try:
2 y = x+5
3 except NameError:
4 print('This code gives a NameError.')
5
6 print(y)

This code gives a NameError.

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/[Link] in <module>
4 print('This code gives a NameError.')
5
----> 6 print(y)

NameError: name 'y' is not defined

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 3/10


5.06.2022 16:04 10. except on_handl ng_python - Jupyter Notebook

In [6]:

1 # Define a func on giving a NameError


2 def addi on(x, y):
3 z=x+y
4 return z
5
6 print('This func on gives a NameError.')
7 total = add(3.14, 1.618)
8 print(total)

This func on gives a NameError.

---------------------------------------------------------------------------
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)

NameError: name 'add' is not defined

In [7]:

1 # Since 'Mustafa' is not defined, the following code gives us a 'NameError.'


2 try:
3 name = (Mustafa)
4 print(name, 'today is your wedding day.')
5 except NameError:
6 print('This code gives a NameError.')
7
8 name = (Mustafa)
9 print(name, 'today is your wedding day.')

This code gives a NameError.

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/[Link] in <module>
6 print('This code gives a NameError.')
7
----> 8 name = (Mustafa)
9 print(name, 'today is your wedding day.')

NameError: name 'Mustafa' is not defined

IndexError

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 4/10


5.06.2022 16:04 10. except on_handl ng_python - Jupyter Notebook

In [8]:

1 nlis = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]


2 try:
3 nlis[10]
4 except IndexError:
5 print('This code gives us a IndexError.')
6
7 print(nlis[10])

This code gives us a IndexError.

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/[Link] in <module>
5 print('This code gives us a IndexError.')
6
----> 7 print(nlis[10])

IndexError: list index out of range

In [9]:

1 # You can also supplytake this error type with tuple


2 tuple_sample = (0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729)
3 try:
4 tuple_sample[10]
5 except IndexError:
6 print('This code gives us a IndexError.')
7
8 print(tuple_sample[10])

This code gives us a IndexError.

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/[Link] in <module>
6 print('This code gives us a IndexError.')
7
----> 8 print(tuple_sample[10])

IndexError: tuple index out of range

KeyError

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 5/10


5.06.2022 16:04 10. except on_handl ng_python - Jupyter Notebook

In [10]:

1 dic onary = {'euler_constant': 0.577, 'golden_ra o': 1.618}


2 try:
3 dictonary = dic onary['euler_number']
4 except KeyError:
5 print('This code gives us a KeyError.')
6
7 dictonary = dic onary['euler_number']
8 print(dictonary)

This code gives us a KeyError.

---------------------------------------------------------------------------
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'

You can f nd more Error Types ([Link] brary/except [Link]?


utm_med um=Ex nfluencer&utm_source=Ex nfluencer&utm_content=000026UJ&utm_term=10006555&utm_ d=N
Sk llsNetwork-Channel-Sk llsNetworkCoursesIBMDeveloperSk llsNetworkPY0101ENSk llsNetwork19487395-
2021-01-01) from th s connect on.

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.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 6/10


5.06.2022 16:04 10. except on_handl ng_python - Jupyter Notebook

In [1]:

1 num1 = float(input('Enter a number:'))


2 print('The entered value is', num1)
3 try:
4 num2 = float(input('Enter a number:'))
5 print('The entered value is', num2)
6 value = num1/num2
7 print('This process is running with value = ', value)
8 except:
9 print('This process is not running.')

The entered value is 3.14


The entered value is 0.577
This process is running with value = 5.441941074523397

Mult ple Except Blocks

try/except/except etc.

In [2]:

1 num1 = float(input('Enter a number:'))


2 print('The entered value is', num1)
3 try:
4 num2 = float(input('Enter a number:'))
5 print('The entered value is', num2)
6 value = num1/num2
7 print('This process is running with value = ', value)
8 except ZeroDivisionError:
9 print('This func on gives a ZeroDivisionError since a number cannot divide by 0.')
10 except ValueError:
11 print('You should provide a number.')
12 except:
13 print('Soething went wrong!')

The entered value is 2.718


The entered value is 0.0
This func on gives a ZeroDivisionError since a number cannot divide by 0.

try/except/else

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 7/10


5.06.2022 16:04 10. except on_handl ng_python - Jupyter Notebook

In [3]:

1 num1 = float(input('Enter a number:'))


2 print('The entered value is', num1)
3 try:
4 num2 = float(input('Enter a number:'))
5 print('The entered value is', num2)
6 value = num1/num2
7 except ZeroDivisionError:
8 print('This func on gives a ZeroDivisionError since a number cannot divide by 0.')
9 except ValueError:
10 print('You should provide a number.')
11 except:
12 print('Soething went wrong!')
13 else:
14 print('This process is running with value = ', value)

The entered value is 37.0


The entered value is 1.618
This process is running with value = 22.867737948084052

try/except/else/f nally

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 8/10


5.06.2022 16:04 10. except on_handl ng_python - Jupyter Notebook

In [5]:

1 num1 = float(input('Enter a number:'))


2 print('The entered value is', num1)
3 try:
4 num2 = float(input('Enter a number:'))
5 print('The entered value is', num2)
6 value = num1/num2
7 except ZeroDivisionError:
8 print('This func on gives a ZeroDivisionError since a number cannot divide by 0.')
9 except ValueError:
10 print('You should provide a number.')
11 except:
12 print('Soething went wrong!')
13 else:
14 print('This process is running with value = ', value)
15 finally:
16 print('The process is completed.')

The entered value is 1.618


The entered value is 0.577
This process is running with value = 2.8041594454072793
The process is completed.

Mult ple except clauses

In [6]:

1 num1 = float(input('Enter a number:'))


2 print('The entered value is', num1)
3 try:
4 num2 = float(input('Enter a number:'))
5 print('The entered value is', num2)
6 value = num1/num2
7 except (ZeroDivisionError, NameError, ValueError): #Mul ple except clauses
8 print('This func on gives a ZeroDivisionError, NameError or ValueError.')
9 except:
10 print('Soething went wrong!')
11 else:
12 print('This process is running with value = ', value)
13 finally:
14 print('The process is completed.')

The entered value is 3.14


The entered value is 0.0
This func on gives a ZeroDivisionError, NameError or ValueError.
The process is completed.

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.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 9/10


5.06.2022 16:04 10. except on_handl ng_python - Jupyter Notebook

In [7]:

1 num = int(input('Enter a number:'))


2 print('The entered value is', num)
3 try:
4 if num>1000 and num %2 == 0 or num %2 !=0:
5 raise Excep on('Do not allow to the even numbers higher than 1000.')
6 except:
7 print('Even or odd numbers higher than 1000 are not allowed!')
8 else:
9 print('This process is running with value = ', num)
10 finally:
11 print('The process is completed.')

The entered value is 1006


Even or odd numbers higher than 1000 are not allowed!
The process is completed.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 10/10


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

Python Tutor al
Created by Mustafa Germec, PhD

11. Bu lt- n Funct ons n Python


Python has several funct ons that are read ly ava lable for use. These funct ons are called bu lt- n funct ons. You
can f nd more nformat on about bu lt- n funct ons from th s L nk.
([Link] [Link])

abs()
Returns the absolute value of a number

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 1/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

In [3]:

1 num1 = int(input('Enter a number: '))


2 print('The entered number is', num1)
3 num2 = float(input('Enter a number: '))
4 print('The entered number is', num2)
5 print('The absolute value of the first number is', abs(num1))
6 print('The absolute number of the second number is', abs(num2))
7 print('The difference between the two numbers is', abs(num1-num2))

The entered number is -6


The entered number is -37.0
The absolute value of the first number is 6
The absolute number of the second number is 37.0
The difference between the two numbers is 31.0

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]:

1 nlis1 = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]


2 print(all(nlis1))
3 [Link](0) # Add '0' to the end of the list
4 print(nlis1)
5 print(all(nlis1))
6 [Link](False) # Adds 'False' to the end of the list
7 print(nlis1)
8 print(all(nlis1))
9 [Link]() # It returns an emtpy list
10 print(nlis1)
11 print(all(nlis1))

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]:

1 num = int(input('Enter a number: '))


2 print(f'The entered number is {num}.')
3 print(f'The binary representa on of {num} is {bin(num)}.')

The entered number is 37.


The binary representa on of 37 is 0b100101.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 2/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

bool()
Converts a value to boolean, namely True and False

In [25]:

1 lis, dict, tuple = [], {}, ()


2 print(bool(lis), bool(dict), bool(tuple))
3 lis, dict, tuple = [0], {'a': 1}, (1,)
4 print(bool(lis), bool(dict), bool(tuple))
5 lis, dict, tuple = [0.0], {'a': 1.0}, (1.0,)
6 print(bool(lis), bool(dict), bool(tuple))
7 a, b, c = 0, 3.14, 'Hello, Python!'
8 print(bool(a), bool(b), bool(c))
9 statement = None
10 print(bool(None))
11 true = True
12 print(bool(true))

False False False


True True True
True True True
False True True
False
True

bytes()
Returns a btyes object

In [26]:

1 msg = 'Hello, Python!'


2 new_msg = bytes(msg, 'u -8')
3 print(new_msg)

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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 3/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

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.

ValueError: chr() arg not in range(0x110000)

In [135]:

1 print(chr('Python')) # The argument maut be integer.

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_16192/[Link] in <module>
----> 1 print(chr('Python')) # The argument maut be integer.

TypeError: 'str' object cannot be interpreted as an integer

comp le()
Returns a code object that can subsequently be executed by exec() funct on

In [35]:

1 code_line = 'x=3.14\ny=2.718\nprint("Result =", 2*x+5*y)'


2 code = compile(code_line, '[Link]', 'exec')
3 print(type(code))
4 exec(code)

<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

Executes the spec f ed code or object

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)

The euler number is 2.718


The golden ra o is 1.618

delattr()
It deletes the spec f ed attr bute (property or method) from the spec f ed object.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 5/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

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.

0.577 2.718 3.14 1.618 These numbers are special.

---------------------------------------------------------------------------
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()

A ributeError: 'SpecialNumbers' object has no a ribute 'msg'

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.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 6/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

In [156]:

1 str_list = ['Hello Python!','Hello, World!']


2 for i, str_list in enumerate(str_list):
3 print(i, str_list)

0 Hello Python!
1 Hello, World!

In [155]:

1 str_list = ['Hello Python!','Hello, World!']


2 enumerate_list = enumerate(str_list)
3 print(list(enumerate_list))

[(0, 'Hello Python!'), (1, 'Hello, World!')]

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.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 7/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

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}.')

The number is 3.14.

frozen()
It returns a frozenset object

In [36]:

1 nlis = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]


2 frozen_nlis = frozenset(nlis)
3 print('Frozen set is', frozen_nlis)

Frozen set is frozenset({0.577, 1.618, 2.718, 3.14, 1729, 37, 6, 28})

any()
It returns True f any terable s True.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 8/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

In [10]:

1 nlis = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]


2 print(nlis)
3 print(any(nlis))
4 [Link]()
5 print(nlis)
6 print(any(nlis)) # An emptly list returns False
7 [Link](0)
8 print(nlis)
9 print(any(nlis)) # 0 in a list returns False
10 [Link](False)
11 print(nlis)
12 print(any(nlis)) # False in a list returns False
13 [Link](True)
14 print(nlis)
15 print(any(nlis)) # True in a list returns True
16 [Link](1)
17 print(nlis)
18 print(any(nlis)) # 1 in a list returns True
19 [Link]()
20 [Link](None)
21 print(nlis)
22 print(any(nlis)) # None in a list returns False

[0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]


True
[]
False
[0]
False
[0, False]
False
[0, False, True]
True
[0, False, True, 1]
True
[None]
False

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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 9/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

In [17]:

1 txt = 'Hello, Python!'


2 print(ascii(txt))
3 text = 'Hello, Pythän!'
4 print(ascii(text))
5 print('Hello, Pyth\xe4n!')
6 msg = 'Hellü, World!'
7 print(ascii(msg))
8 print('Hell\xfc, World!')

'Hello, Python!'
'Hello, Pyth\xe4n!'
Hello, Pythän!
'Hell\xfc, World!'
Hellü, World!

bytearray()
It returns a new array of bytes.

In [23]:

1 txt = 'Hello, Python!'


2 print(bytearray(txt, 'u -8')) # String with encoding 'UTF-8'
3 int_num = 37
4 print(bytearray(int_num))
5 nlis = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] # Fibonacci numbers
6 print(bytearray(nlis))
7 float_num = 3.14
8 print(bytearray(float_num)) # It returns TypeError

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))

TypeError: cannot convert 'float' object to bytearray

hasattr()
It returns True f the spec f ed object has the spec f ed attr bute (property/method).

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 10/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

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

The euler number is True


The golden ra o is True
The golden ra o is False

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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 11/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

In [167]:

1 help()

Welcome to Python 3.10's help u lity!

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".

To get a list of available modules, keywords, symbols, or topics, type


"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".

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.

Help on package pandas:

NAME
pandas

DESCRIPTION
pandas - a powerful data analysis and manipula on library for Python
=====================================================================

**pandas** is a Python package providing fast, flexible, and expressive data


structures designed to make working with "rela onal" or "labeled" data both
easy and intui ve. It aims to be the fundamental high-level building block for
doing prac cal, **real world** data analysis in Python. Addi onally, it has
the broader goal of becoming **the most powerful and flexible open source data
analysis / manipula on tool available in any language**. It is already well on
its way toward this goal.

Main Features
-------------
H j t f f th thi th t d d ll

d()
Returns the d of an object

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 12/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

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]:

1 num = int(input('Enter a number: '))


2 print(f'The entered number is {num}.')
3 print(eval('num*num'))

The entered number is 37.


1369

map()
It returns the spec f ed terator w th the spec f ed funct on appl ed to each tem.

In [77]:

1 special_nums = [0.577, 1.618, 2.718, 3.14, 28, 37, 1729]


2 def division(number):
3 return number/number
4
5 division_number_iterator = map(division, special_nums)
6 divided_nums = list(division_number_iterator)
7 print(divided_nums)
8
9 # Similar codings can be made for other opera ons

[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 13/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

len()
It returns the length of an object

In [54]:

1 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]


2 print('The length of the list is', len(special_nums))

The length of the list is 8

In [59]:

1 # Calculate the average of values in the following list


2 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]
3 count = 0
4 for i in special_nums:
5 count = count + i
6 print('The average of the values in the list is', count/len(special_nums))

The average of the values in the list is 226.00662499999999

m n()
Returns the smallest tem n an terable

In [170]:

1 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]


2 print(min(special_nums))

0.577

max()
Returns the largest tem n an terable

In [171]:

1 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]


2 print(max(special_nums))

1729

sum()
To get the sum of numbers n a l st

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 14/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

In [172]:

1 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]


2 print(sum(special_nums))

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))

ValueError: could not convert string to float: 'Hello, Python!'

locals()
It returns an updated d ct onary of the current local symbol table.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 15/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

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]:

1 def func on():


2 variable = True
3 print(variable)
4 locals()['variable'] = False # locals() dic onary may not change the informa on inside the locals table.
5 print(variable)
6
7 func on()

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())

If there is no locals(), it returns an empty dic onary {}


If there is locals(), it returns a dic onary {'program': 'Python'}

format()
Th s funct on formats a spec f ed value. d, f, and b are a type.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 16/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

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]:

1 txt = input('Enter a message: ')


2 print('The entered message is', txt)

The entered message is Hello, Python!

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}.')

The numbers are 6, 3,and 28.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 17/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

s nstance()
It checks f the object (f rst argument) s an nstance or subclass of class nfo class (second argument).

In [226]:

1 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]


2 result = isinstance(special_nums, list)
3 print(result)

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).

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 18/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

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]:

1 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]


2 special_nums_iter = iter(special_nums)
3 print('Euler constant is', next(special_nums_iter))
4 print('The golden ra o is', next(special_nums_iter))
5 print('Euler number is', next(special_nums_iter))
6 print('Pi number is', next(special_nums_iter))
7 print(next(special_nums_iter), 'is a perfect number.')
8 print(next(special_nums_iter), 'is a perfect number.')
9 print(next(special_nums_iter), 'is a special and prime number.')
10 print(next(special_nums_iter), 'is Ramanujan-Hardy number.')

Euler constant is 0.577


The golden ra o is 1.618
Euler number is 2.718
Pi number is 3.14
6 is a perfect number.
28 is a perfect number.
37 is a special and prime number.
1729 is Ramanujan-Hardy number.

object()
It returns a new object.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 19/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

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]:

1 num = int(input('Enter a number:'))


2 print(f'The octal value of {num} us {oct(num)}.')

The octal value of 37 us 0o45.

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))

oct(1729) is: 0o3301


oct(0b101) is: 0o5
oct(0XA) is: 0o12

l st()
It creates a l st n Python.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 20/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

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]:

1 ba = bytearray('XYZ', 'u -8')


2 mv = memoryview(ba)
3 print(mv)
4 print(mv[0])
5 print(mv[1])
6 print(mv[2])
7 print(bytes(mv[0:2]))
8 print(list(mv[:]))
9 print(set(mv[:]))
10 print(tuple(mv[:]))
11 mv[1] = 65 # 'Y' was replaced with 'A'
12 print(list(mv[:]))
13 print(ba)

<memory at 0x0000018BB24C5D80>
88
89
90
b'XY'
[88, 89, 90]
{88, 89, 90}
(88, 89, 90)
[88, 65, 90]
bytearray(b'XAZ')

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 21/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

In [ ]:

In [218]:

1 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]


2 number = iter(special_nums) # Create an itera on
3 item = next(number) # First item
4 print(item)
5 item = next(number) # Second item
6 print(item)
7 item = next(number) # Third item, etc
8 print(item)
9 item = next(number)
10 print(item)
11 item = next(number)
12 print(item)
13 item = next(number)
14 print(item)
15 item = next(number)
16 print(item)
17 item = next(number)
18 print(item)

0.577
1.618
2.718
3.14
6
28
37
1729

open()
It opens a f le and returns a f le object.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 22/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 23/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

In [122]:

1 # Open file using with


2 path = "[Link]"
3 with open(path, "r") as file:
4 FileContent = fi[Link]()
5 print(FileContent)

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.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 24/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

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!'))

TypeError: unsupported operand type(s) for divmod(): 'str' and 'str'

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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 26/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

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).

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 27/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

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])

slice(None, 2.718, None)


slice(0.577, 1.618, 3.14)
Hello
[0.577, 1.618, 2.718, 3.14]
[1729, 28, 3.14]
[0.577, 1.618, 2.718, 3.14]
[6, 28, 37]

sorted()
Returns a sorted l st

In [213]:

1 special_nums = [2.718, 1729, 0.577, 1.618, 28, 3.14, 6, 37]


2 print(sorted(special_nums))
3 txt = 'Hello, Python!'
4 print(sorted(txt))

[0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]


[' ', '!', ',', 'H', 'P', 'e', 'h', 'l', 'l', 'n', 'o', 'o', 't', 'y']

ord()
Convert an nteger represent ng the Un code of the spec f ed character

Type Markdown and LaTeX:

In [241]:

1 print(ord('9'))
2 print(ord('X'))
3 print(ord('W'))
4 print(ord('^'))

57
88
87
94

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 28/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

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]:

1 msg = 'Hello, Python!'


2 print(msg)

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)))

['n', 'o', 'h', 't', 'y', 'P']


[37, 6, 3.14, 28, 1.618, 0.577, 1729, 2.718]
[27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6]
[37, 6, 3.14, 28, 1.618, 0.577, 1729, 2.718]

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.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 30/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

In [271]:

1 special_nums = [2.718, 1729, 0.577, 1.618, 28, 3.14, 6, 37]


2 special_nums_tuple = tuple(special_nums)
3 print(special_nums_tuple)
4
5 txt = 'Hello, Python!'
6 txt_tuple = tuple(txt)
7 print(txt_tuple)
8
9 dic onary = {'A': 0.577, 'B': 2.718, 'C': 3.14}
10 dic onary_tuple = tuple(dic onary)
11 print(dic onary_tuple)

(2.718, 1729, 0.577, 1.618, 28, 3.14, 6, 37)


('H', 'e', 'l', 'l', 'o', ',', ' ', 'P', 'y', 't', 'h', 'o', 'n', '!')
('A', 'B', 'C')

type()
It e ther returns the type of the object or returns a new type object based on the arguments passed.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 31/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

In [276]:

1 special_nums = [2.718, 1729, 0.577, 1.618, 28, 3.14, 6, 37]


2 special_nums_tuple = tuple(special_nums)
3 print(special_nums_tuple)
4 print(type(special_nums))
5 print()
6 txt = 'Hello, Python!'
7 txt_tuple = tuple(txt)
8 print(txt_tuple)
9 print(type(txt))
10 print()
11 dic onary = {'A': 0.577, 'B': 2.718, 'C': 3.14}
12 dic onary_tuple = tuple(dic onary)
13 print(dic onary_tuple)
14 print(type(dic onary))
15 print()
16 special_nums_set = {2.718, 1729, 0.577, 1.618, 28, 3.14, 6, 37}
17 special_nums_tuple = tuple(special_nums_set)
18 print(special_nums_tuple)
19 print(type(special_nums_set))
20 print()
21 class SpecialNumbers:
22 euler_constant = 0.577
23 euler_number = 2.718
24 pi = 3.14
25 golden_ra o = 1.618
26 msg = 'These numbers are very special'
27
28 def __init__(self, euler_constant, euler_number, pi, golden_ra o, msg):
29 self.euler_constant = euler_constant
30 self.euler_number = euler_number
31 [Link] = pi
32 self.golden_ra o = golden_ra o
33 [Link] = msg
34
35 special_numbers = SpecialNumbers(0.577, 2.718, 3.14, 1.618, 'These numbers are very special.')
36 print(type(special_numbers))

(2.718, 1729, 0.577, 1.618, 28, 3.14, 6, 37)


<class 'list'>

('H', 'e', 'l', 'l', 'o', ',', ' ', 'P', 'y', 't', 'h', 'o', 'n', '!')
<class 'str'>

('A', 'B', 'C')


<class 'dict'>

(0.577, 1729, 2.718, 3.14, 1.618, 37, 6, 28)


<class 'set'>

<class '__main__.SpecialNumbers'>

vars()
The vars() funct on returns the d ct attr bute of the g ven object.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 32/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

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]:

1 special_nums = [2.718, 1729, 0.577, 1.618, 28, 3.14, 37]


2 special_nums_name = ['Euler number', 'Ramanujan-Hardy number', 'Euler constant', 'Golden ra o', 'Perfect number',
3 output = zip()
4 output_list = list(output)
5 print(output_list)
6 reel_output = zip(special_nums_name, special_nums)
7 reel_output_set = set(reel_output)
8 print(reel_output_set)

[]
{('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.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 33/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

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()

6 and 28 are perfect numbers.


These numbers are very special in mathema k.

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()

Cow gives us milk.


Cow lives in a farm.

mport()
It s a funct on that s called by the mport statement.

In [303]:

1 math = __import__('math', globals(), locals(), [], 0)


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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 34/35


7.06.2022 01:23 11. bu lt_ n_funct ons_python - Jupyter Notebook

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

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 35/35


8.06.2022 01:57 12. classes_objects_python - Jupyter Notebook

Python Tutor al
Created by Mustafa Germec

12. Classes and Objects n Python


Python s an object-or ented programm ng language.
Unl ke procedure-or ented programm ng, where the ma n emphas s s on funct ons, object-or ented
programm ng stresses on objects.
An object s s mply a collect on of data (var ables) and methods (funct ons) that act on those data.
S m larly, a class s a bluepr nt for that object.
L ke funct on def n t ons beg n w th the def keyword n Python, class def n t ons beg n w th a class keyword.
The f rst str ng ns de the class s called docstr ng and has a br ef descr pt on of the class.
Although not mandatory, th s s h ghly recommended.

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()

The euler number is 2.718


The golden ra o is 1.618
The pi number is 3.14

Self parameter

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 2/15


8.06.2022 01:57 12. classes_objects_python - Jupyter Notebook

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()

The euler number is 2.718


The golden ra o is 1.618
The pi number is 3.14

Creat ng a Class to draw a Rectangle

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 3/15


8.06.2022 01:57 12. classes_objects_python - Jupyter Notebook

In [1]:

1 # Crea ng a class to draw a rectangle


2 class Rectangle(object):
3
4 # Contructor
5 def __init__(self, width, height, color):
6 [Link] = width
7 [Link] = height
8 [Link] = color
9
10 # Method
11 def drawRectangle(self):
12 [Link]().add_patch([Link]((0, 0), [Link], [Link], fc=[Link]))
13 [Link]('scaled')
14 [Link]()
15
16 # import library to draw the Rectangle
17 import [Link] as plt
18 %matplotlib inline
19
20 # crea ng an object blue rectangle
21 one_Rectangle = Rectangle(20, 10, 'blue')
22
23 # Prin ng the object a ribute width
24 print(one_Rectangle.width)
25
26 # Prin ng the object a ribute height
27 print(one_Rectangle.height)
28
29 # Prin ng the object a ribute color
30 print(one_Rectangle.color)
31
32 # Drawing the object
33 one_Rectangle.drawRectangle()
34
35 # Learning the methods that can be u lized on the object 'one_rectangle'
36 print(dir(one_Rectangle))
37
38 # We can change the proper es of the rectangle
39 one_Rectangle.width = 15
40 one_Rectangle.height = 15
41 one_Rectangle.color = 'green'
42 one_Rectangle.drawRectangle()
43
44 # Using new variables, we can change the proper es of the rectangle
45 two_Rectangle = Rectangle(100, 50, 'yellow')
46 two_Rectangle.drawRectangle()
47
48

20
10

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 4/15


8.06.2022 01:57 12. classes_objects_python - Jupyter Notebook

['__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']

Creat ng a class to draw a c rcle

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 5/15


8.06.2022 01:57 12. classes_objects_python - Jupyter Notebook

In [3]:

1 # Crea ng a class to draw a circle


2 class Circle(object):
3
4 # Contructor
5 def __init__(self, radius, color):
6 [Link] = radius
7 [Link] = color
8
9 # Method
10 def increase_radius(self, r):
11 [Link] = [Link] + r
12 return [Link]
13
14 # Method
15 def drawCircle(self):
16 [Link]().add_patch([Link]((0, 0), [Link], fc=[Link]))
17 [Link]('scaled')
18 [Link]()
19
20 # import library to draw the circle
21 import [Link] as plt
22 %matplotlib inline
23
24 # crea ng an object blue circle
25 one_Circle = Circle(3.14, 'blue')
26
27 # Prin ng the object a ribute radius
28 print(one_Circle.radius)
29
30 # Prin ng the object a ribute color
31 print(one_Circle.color)
32
33 # Drawing the object
34 one_Circle.drawCircle()
35
36 # Learning the methods that can be u lized on the object 'one_rectangle'
37 print(dir(one_Circle))
38
39 # We can change the proper es of the rectangle
40 one_Circle.radius = 15
41 one_Circle.color = 'green'
42 one_Circle.drawCircle()
43
44 # Using new variables, we can change the proper es of the rectangle
45 two_Circle = Circle(100, 'yellow')
46 print(two_Circle.radius)
47 print(two_Circle.color)
48 two_Circle.drawCircle()
49
50 # Changing the radius of the object
51 print('Before increment: ',one_Circle.radius)
52 one_Circle.drawCircle()
53
54 # Increment by 15 units
55 one_Circle.increase_radius(15)
56 print('Increase the radius by 15 units: ', one_Circle.radius)
57 one_Circle.drawCircle()
58
59 # Increment by 30 units
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 6/15
8.06.2022 01:57 12. classes_objects_python - Jupyter Notebook

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']

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 7/15


8.06.2022 01:57 12. classes_objects_python - Jupyter Notebook

100
yellow

Before increment: 15

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 8/15


8.06.2022 01:57 12. classes_objects_python - Jupyter Notebook

Increase the radius by 15 units: 30

Increase the radius by 30 units: 60

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebo… 9/15


8.06.2022 01:57 12. classes_objects_python - Jupyter Notebook

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'))

The euler number is 2.718


The golden ra o is 1.618
The pi number is 3.14
The message is These numbers are special.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 10/15


8.06.2022 01:57 12. classes_objects_python - Jupyter Notebook

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.

0.577 2.718 3.14 1.618 These numbers are special.

---------------------------------------------------------------------------
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()

A ributeError: 'SpecialNumbers' object has no a ribute 'msg'

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

Create a Data Classs

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 11/15


8.06.2022 01:57 12. classes_objects_python - Jupyter Notebook

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]()

The name of a microorganism is in the form of Aspergillus niger.

Create a Ch ld Class n Data Class

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]()

The name of a microorganism is in the form of Aspergillus sojae.

Add t on of n t() Funct ons

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 12/15


8.06.2022 01:57 12. classes_objects_python - Jupyter Notebook

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]()

The name of a microorganism is in the form of Aspergillus sojae.

Add t on of super() Funct on

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()

6 and 28 are perfect numbers.


These numbers are very special in mathema k.

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()

Cow gives us milk.


Cow lives in a farm.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 13/15


8.06.2022 01:57 12. classes_objects_python - Jupyter Notebook

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]()

The name of a microorganism is in the form of Aspergillus sojae.

Add t on of Propert es under the super() Funct on

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.')

The enzyme ac vity increased to 2500 U/mL.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 14/15


8.06.2022 01:57 12. classes_objects_python - Jupyter Notebook

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.')

The enzyme ac vity increased to 2500 U/mL.

Add t on of Methods under the Ch ld Class

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.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteb… 15/15


9.06.2022 12:33 13. read ng_f les_python - Jupyter Notebook

Python Tutor al
Created by Mustafa Germec, PhD

13. Read ng F les n Python


To read a text f le n Python, you follow these steps:

F rst, open a text f le for read ng by us ng the open() funct on


Second, read text from the text f le us ng the f le read(), readl ne(), or readl nes() method of the f le object.
Th rd, close the f le us ng the f le close() method. Th s frees up resources and ensures cons stency across
d fferent python vers ons.

Read ng f le

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 1/8


9.06.2022 12:33 13. read ng_f les_python - Jupyter Notebook

In [2]:

1 # Reading the txt file


2 file_name = "pcr_fi[Link]"
3 file = open(file_name, "r")
4 content = fi[Link]()
5 content

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]:

1 # Prin ng the path of file


2 print(fi[Link])
3 # Prin ng the mode of file
4 print(fi[Link])
5 # Prin ng the file with '\n' as a new file
6 print(content)
7 # Prin ng the type of file
8 print(type(content))

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]:

1 # Close the file


2 fi[Link]()

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 2/8


9.06.2022 12:33 13. read ng_f les_python - Jupyter Notebook

In [5]:

1 # Verifica on of the closed file


2 fi[Link]

Out[5]:

True

Another way to read a f le

In [6]:

1 fname = 'pcr_fi[Link]'
2 with open(fname, 'r') as f:
3 content = [Link]()
4 print(content)

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.

In [7]:

1 # Verifica on of the closed file


2 [Link]

Out[7]:

True

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 3/8


9.06.2022 12:33 13. read ng_f les_python - Jupyter Notebook

In [8]:

1 # See the content of the file


2 print(content)

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.

In [9]:

1 # Reading the first 20 characters in the text file


2 with open(fname, 'r') as f:
3 print([Link](20))

I dedicate this book

In [10]:

1 # Reading certain amount of characters in the file


2 with open(fname, 'r') as f:
3 print([Link](20))
4 print([Link](20))
5 print([Link](50))
6 print([Link](100))

I dedicate this book


to Nancy Lier Cosgr
ove Mullis.
Jean-Paul Sartre somewhere observed th
at we each of us make our own hell out of the people around us. Had Jean-Paul known Nancy, he may h
a

In [11]:

1 # Reading first line in the text file


2 with open(fname, 'r') as f:
3 print('The first line is: ', [Link]())

The first line is: I dedicate this book to Nancy Lier Cosgrove Mullis.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 4/8


9.06.2022 12:33 13. read ng_f les_python - Jupyter Notebook

In [12]:

1 # Difference between read() and readline()


2 with open(fname, 'r') as f:
3 print([Link](20))
4 print([Link](20)) # This code returns the next 20 characters in the line.

I dedicate this book


to Nancy Lier Cosgr

Loop usage n the text f le

In [13]:

1 with open(fname, 'r') as f:


2 line_number = 1
3 for line in f:
4 print('Line number', str(line_number), ':', line)
5 line_number+=1

Line number 1 : I dedicate this book to Nancy Lier Cosgrove Mullis.

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.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 5/8


9.06.2022 12:33 13. read ng_f les_python - Jupyter Notebook

In [14]:

1 with open(fname, 'r') as f:


2 print([Link]())

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.

In [15]:

1 with open(fname, 'r') as f:


2 print([Link](30))

I dedicate this book to Nancy

readl ne() funct on

Reads one l ne at a t me from the f le n the form of str ng

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 6/8


9.06.2022 12:33 13. read ng_f les_python - Jupyter Notebook

In [16]:

1 with open(fname, 'r') as f:


2 file_list = [Link]()
3 # Prin ng the first line
4 print(file_list[0])
5 # Prin ng the second line
6 print(file_list[1])
7 # Prin ng the third line
8 print(file_list[2])
9 # Prin ng the fourth line
10 print(file_list[3])

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.

readl nes() funct on

Reads all the l nes from the f le and returns a l st of l nes.

In [17]:

1 fname = r'C:/Users/test/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sha


2 with open(fname, 'r') as f:
3 content=[Link]()
4 print(content)

['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']

str p() funct on

Removes the lead ng and tra l ng spaces from the g ven str ng.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 7/8


9.06.2022 12:33 13. read ng_f les_python - Jupyter Notebook

In [18]:

1 with open(fname, 'r') as f:


2 len_file = 0
3 total_len_file = 0
4 for line in f:
5 # Total length of line in the text file
6 total_len_file = total_len_file+len(line)
7
8 # Lenght of the line a er removing leading and trailing spaces
9 len_file = len_file+len([Link]())
10 print(f'Total lenght of the line is {total_len_file}.')
11 print(f'The length of the line a er removing leading and trailing spaces is {len_file}.')
12

Total lenght of the line is 1029.


The length of the line a er removing leading and trailing spaces is 1024.

S ze of the text f le

In [19]:

1 with open(fname, 'r') as f:


2 str = ""
3 for line in f:
4 str+=line
5 print(f'The size of the text file is {len(str)}.')

The size of the text file is 1029.

Number of l nes n the text

In [20]:

1 with open(fname, 'r') as f:


2 count = 0
3 for line in f:
4 count = count + 1
5 print(f'The number of lines in the text file is {count}.')

The number of lines in the text file is 5.

localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_noteboo… 8/8


10.06.2022 11:17 14. wr t ng_f les_python - Jupyter Notebook

Python Tutor al
Created by Mustafa Germec, PhD

14. Wr t ng F les n Python


To wr te to a text f le n Python, you follow these steps:

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.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/14. wr t ng_f les… 1/10


10.06.2022 11:17 14. wr t ng_f les_python - Jupyter Notebook

Wr t ng f les

In [17]:

1 # Wri ng lines to a file.


2 fname = 'pcr_fi[Link]'
3 with open(fname, 'w') as f:
4 [Link]("I dedicate this book to Nancy Lier Cosgrove Mullis.\n")
5 [Link]("Jean-Paul Sartre somewhere observed that we each of us make our own hell out of the people around us. H
6 [Link]("Or maybe he would have just said, 'If I would had a woman like that, my books would not have been about
7 [Link]("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
8 [Link]("A feedback from Elle on the book\n")
9 [Link]("This bona-fide wild card of the scien fic community writes with eccentric gusto.… Mullis has created a free

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/14. wr t ng_f les… 2/10


10.06.2022 11:17 14. wr t ng_f les_python - Jupyter Notebook

In [18]:

1 # Checking the file whether it was wri en or not


2 with open(fname, 'r') as f:
3 content = [Link]()
4 print(content)

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.

In [20]:

1 # Wri ng a list to a file


2 added_text = ["From The New Yorker\n",
3 "Entertaini ng … [Mullis is] usefully cranky and comba ve, raising provoca ve ques ons about receive
4 "From Chicago Sun-Times\n",
5 "One of the most unusual scien sts of our mes, a man who would be a joy to put under a microscope
6 "From Andrew Weil, M.D.\n",
7 "In this entertaining romp through diverse fields of inquiry, [Mullis] displays the openmindedness, ecc
8 ]
9
10 fname = '[Link]'
11 with open(fname, 'w') as f:
12 for line in added_text:
13 print(line)
14 [Link](line)

From The New Yorker

Entertaini ng … [Mullis is] usefully cranky and comba ve, raising provoca ve ques ons about received tr
uths from the scien fic establishment.

From Chicago Sun-Times

One of the most unusual scien sts of our mes, a man who would be a joy to put under a microscope.

From Andrew Weil, M.D.

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.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/14. wr t ng_f les… 3/10


10.06.2022 11:17 14. wr t ng_f les_python - Jupyter Notebook

Append ng f les

In [24]:

1 # Wr ng and tehn reading the file


2 new_file = 'pcr_fi[Link]'
3 with open(new_file, 'w') as f:
4 [Link]('Overright\n')
5 with open(new_file, 'r') as f:
6 print([Link]())

Overright

In [25]:

1 # Wri ng a new line to the text file


2 with open(new_file, 'a') as f: # To append a new line to the text file, use 'a' in the syntax string
3 [Link]("I dedicate this book to Nancy Lier Cosgrove Mullis.\n")
4 [Link]("Jean-Paul Sartre somewhere observed that we each of us make our own hell out of the people around us. H
5 [Link]("Or maybe he would have just said, 'If I would had a woman like that, my books would not have been about
6 [Link]("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
7 [Link]("A feedback from Elle on the book\n")
8 [Link]("This bona-fide wild card of the scien fic community writes with eccentric gusto.… Mullis has created a free
9
10 # Verifica on of the new lines in the text file
11 with open(new_file, 'r') as f:
12 print([Link]())

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+

Append ng and Read ng. Creates a new f le, f none ex sts.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/14. wr t ng_f les… 4/10


10.06.2022 11:17 14. wr t ng_f les_python - Jupyter Notebook

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]:

1 # To verify the text file whether it is added or not


2 with open(fname, 'r') as f:
3 print([Link]())

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.

tell() and seek() funct ons w th a+

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/14. wr t ng_f les… 5/10


10.06.2022 11:17 14. wr t ng_f les_python - Jupyter Notebook

In [10]:

1 with open(fname, 'a+') as f:


2 print("First loca on: {}".format([Link]())) # it returns the current posi on in bytes
3
4 content = [Link]()
5 if not content:
6 print('Read nothing.')
7 else:
8 print([Link]())
9
10 [Link](0, 0)
11 """
12 seek() func on is used to change the posi on of the File Handle to a given specific posi on.
13 File handle is like a cursor, which defines from where the data has to be read or wri en in the file.
14 Syntax: [Link](offset, from_what), where f is file pointer
15 Parameters:
16 Offset: Number of posi ons to move forward
17 from_what: It defines point of reference.
18 Returns: Return the new absolute posi on.
19 The reference point is selected by the from_what argument. It accepts three values:
20 0: sets the reference point at the beginning of the file
21 1: sets the reference point at the current file posi on
22 2: sets the reference point at the end of the file
23 """
24 print('\nSecond loca on: {}'.format([Link]()))
25 content = [Link]()
26 if not content:
27 print('Read nothing.')
28 else:
29 print(content)
30 print('Loca on a er reading: {}'.format([Link]()))

First loca on: 1641


Read nothing.

Second loca on: 0


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.

Loca on a er reading: 1641


localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/14. wr t ng_f les… 6/10
10.06.2022 11:17 14. wr t ng_f les_python - Jupyter Notebook

r+

Read ng and wr t ng. Cannot truncate the f le.

In [13]:

1 with open(fname, 'r+') as f:


2 content=[Link]()
3 [Link](0,0) # wri ng at the beginning of the file
4 [Link]('From The San Diego Union-Tribune' + '\n')
5 [Link]("Refreshing … brashly confident … indisputably entertaining." + "\n")
6 [Link]("To my family..." + '\n')
7 [Link](0,0)
8 print([Link]())

From The San Diego Union-Tribune


Refreshing … brashly confident … indisputably entertaining.
To my family...
...
s make our own hell out of the people around us. Had Jean-Paul known Nancy, he may have noted that
at least one man, someday, might get very lucky, and make his own heaven out of one of the people aro
und him. She will be his morning and his evening star, shining with the brightest and the 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 faith 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.

Copy the f le

In [14]:

1 # Let's copy the text file 'pcr_fi[Link]' to another one 'pcr_file_1.txt'


2 fname = 'pcr_fi[Link]'
3 with open(fname, 'r') as f_reading:
4 with open('pcr_file_1.txt', 'w') as f_wri ng:
5 for line in f_reading:
6 f_wri [Link](line)

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/14. wr t ng_f les… 7/10


10.06.2022 11:17 14. wr t ng_f les_python - Jupyter Notebook

In [15]:

1 # For the verifica on, execute the following codes


2 fname = 'pcr_file_1.txt'
3 with open(fname, 'r') as f:
4 print([Link]())
5
6 # Now, there are 2 files from the same file content.

From The San Diego Union-Tribune


Refreshing … brashly confident … indisputably entertaining.
To my family...
...
s make our own hell out of the people around us. Had Jean-Paul known Nancy, he may have noted that
at least one man, someday, might get very lucky, and make his own heaven out of one of the people aro
und him. She will be his morning and his evening star, shining with the brightest and the 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 faith 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.

Some examples

In [36]:

1 # Wri ng the student names into a file


2 fname = open(r'student_name.txt', 'w')
3 for i in range(3):
4 name = input('Enter a student name: ')
5 [Link](name)
6 [Link]('\n') # To write names as a new line
7 fname = open(r'student_name.txt', 'r')
8 for line in fname:
9 print(line)
10 [Link]()

Daniela

Axel

Leonardo

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/14. wr t ng_f les… 8/10


10.06.2022 11:17 14. wr t ng_f les_python - Jupyter Notebook

In [40]:

1 # To write the file


2 fname = open(r'student_name.txt', 'w')
3 name_list = []
4 for i in range(3):
5 name = input('Enter a student name: ')
6 name_list.append(name + '\n')
7 [Link](name_list)
8
9 # To read the file
10 fname = open(r'student_name.txt', 'r')
11 for line in fname:
12 print(line)
13 [Link]()

Daniel

Axel

Leonardo

In [41]:

1 lines = ['Hello, World!', 'Hi, Python!']


2 with open('new_fi[Link]', 'w') as f:
3 for line in lines:
4 [Link](line)
5 [Link]('\n')
6
7 with open('new_fi[Link]', 'r') as f:
8 print([Link]())

Hello, World!
Hi, Python!

In [43]:

1 # Add more lines into the file


2 more_lines = ['Hi, Sun!', 'Hello, Summer!', 'Hi, See!']
3 with open('new_fi[Link]', 'a') as f:
4 [Link]('\n' .join(more_lines))
5
6 with open('new_fi[Link]', 'r') as f:
7 print([Link]())
8
9 [Link]()

Hello, World!
Hi, Python!
Hi, Sun!
Hello, Summer!
Hi, See!Hi, Sun!
Hello, Summer!
Hi, See!

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/14. wr t ng_f les… 9/10


10.06.2022 11:17 14. wr t ng_f les_python - Jupyter Notebook

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/14. wr t ng_f le… 10/10


20.06.2022 16:06 15. Str ngs Operators and Funct ons n Python - Jupyter Notebook

Python Tutor al
Created by Mustafa Germec

15. Str ngs Operators and Funct ons n Python

Spec al Str ng Operators n Python

Str ngs are unchangeable

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/15. Str ngs Ope… 1/14


20.06.2022 16:06 15. Str ngs Operators and Funct ons n Python - Jupyter Notebook

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]:

1 text = 'Python is a programming language.'


2 print(text)
3 del text[1]
4 print(text)

Python is a programming language.

---------------------------------------------------------------------------
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)

TypeError: 'str' object doesn't support item dele on

In [7]:

1 text = 'Python is a programming language.'


2 print(text)
3 del text
4 print(text)

Python is a programming language.

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_18660/[Link] in <module>
2 print(text)
3 del text
----> 4 print(text)

NameError: name 'text' is not defined

Concetanat on of str ngs


It comb nes two or more str ngs us ng the s gn '+' to form a new str ng.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/15. Str ngs Ope… 2/14


20.06.2022 16:06 15. Str ngs Operators and Funct ons n Python - Jupyter Notebook

In [9]:

1 text1 = 'Hello '


2 text2 = 'Python!'
3 new_text = text1 + text2
4 print(new_text)

Hello Python!

Append ng (+=) adds a new str ng the the end of the current str ng

In [10]:

1 text1 = 'Hello '


2 text2 = 'Python!'
3 text1+=text2
4 print(text1)

Hello Python!

To repeat a str ng, the mult pl cat on (*) operator s used

In [12]:

1 text = 'Hello, Python! '


2 print(text*4)

Hello, Python! Hello, Python! Hello, Python! Hello, Python!

Access ng the tem by ndex ng

In [21]:

1 text = 'Hello, Python!'


2 print(text[0:5]) # Pozi ve indexing
3 print(text[4])
4 print(text[-7:]) # Nega ve indexing
5 print(text[-7:-1])

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.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/15. Str ngs Ope… 3/14


20.06.2022 16:06 15. Str ngs Operators and Funct ons n Python - Jupyter Notebook

In [29]:

1 text = 'Hello, Python!'


2 print(len(text))
3 print(text[:14]) # Default stride value is 1.
4 print(text[0:14:2])
5 print(text[::3])

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]:

1 text = 'Hello, Python!'


2 print(text[::-1])

!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]:

1 text = 'Hello, Python!'


2 print('H' in text)
3 print('H' not in text)
4 print('c' not in text)
5 print('c' in text)

True
False
True
False

Str ng Funct ons n Python


You can f nd some useful funct ons from the below table.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/15. Str ngs Ope… 4/14


20.06.2022 16:06 15. Str ngs Operators and Funct ons n Python - Jupyter Notebook

cap tal ze() funct on


It converts the f rst character of the str ng nto uppercase.

In [31]:

1 text = 'hello, python!'


2 print(f'Before capitalizing: {text}')
3 text = [Link]()
4 print(f'A er capitalizing: {text}')

Before capitalizing: hello, python!


A er capitalizing: Hello, python!

casefold() funct on
It converts the characters n the certa n str ng nto lowercase.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/15. Str ngs Ope… 5/14


20.06.2022 16:06 15. Str ngs Operators and Funct ons n Python - Jupyter Notebook

In [32]:

1 text = 'Hello, Python!'


2 print(f'Before casefold: {text}')
3 text = [Link]()
4 print(f'A er casefold: {text}')

Before casefold: Hello, Python!


A er casefold: hello, python!

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]:

1 text = 'Hello, Python!'


2 print(f'Before center() func on: {text}')
3 text = [Link](50)
4 print(f'A er center() func on: {text}')
5 new_text = 'Hi, Python!'
6 new_text = new_text.center(50, '-')
7 print(f'A er center() func on: {new_text}')

Before center() func on: Hello, Python!


A er center() func on: Hello, Python!
A er center() func on: -------------------Hi, Python!--------------------

count() funct on
It returns the number of a certa n characters n a str ng.

In [45]:

1 text = 'Hello, Python!'


2 print(f"The number of the character 'o' in the string is {[Link]('o')}.")

The number of the character 'o' in the string is 2.

endsw th() funct on


It returns True f the str ngs ends w th a certa n value.

In [49]:

1 text = 'Hello, Python!'


2 text = [Link]('Python!')
3 print(text)
4 new_text = 'Hi, Python!'
5 new_text = new_text.endswith('World!')
6 print(new_text)

True
False

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/15. Str ngs Ope… 6/14


20.06.2022 16:06 15. Str ngs Operators and Funct ons n Python - Jupyter Notebook

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]:

1 text = 'Hello, Python!'


2 print(text.find('Python'))
3 print(text.find('World', 0, 14)) # It returns -1 if the value is not found.

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]:

1 text = 'Hello {} and Hi {}'.format('World!', 'Python!')


2 print(text)
3 text = 'Hello {world} and Hi {python}'.format(world='World!', python='Python!')
4 print(text)
5 text = 'Hello {0} and Hi {1}'.format('World!', 'Python!')
6 print(text)
7 text = 'Hello {1} and Hi {0}'.format('World!', 'Python!')
8 print(text)

Hello World! and Hi Python!


Hello World! and Hi Python!
Hello World! and Hi Python!
Hello Python! and Hi World!

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.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/15. Str ngs Ope… 7/14


20.06.2022 16:06 15. Str ngs Operators and Funct ons n Python - Jupyter Notebook

In [71]:

1 text = 'Hello, Python!'


2 print([Link]('Python!'))
3 print([Link]('Hello'))
4 print([Link]('Hi')) # If the value is not found, it returns a 'ValueError'

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'

ValueError: substring not found

salnum() funct on
It returns True f all characters n the str ng are alphanumer c.

In [76]:

1 text = 'Hello, Python!'


2 print([Link]())
3 msg = 'Hello1358'
4 print([Link]())

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

sdec mal() funct on


It returns True f all the characters n the g ven str ng are dec mal numbers ( 0-9).
localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/15. Str ngs Ope… 8/14
20.06.2022 16:06 15. Str ngs Operators and Funct ons n Python - Jupyter Notebook

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

s dent f er() funct on


It returns True f the str ng s a val d dent f er, on the contrary False.

In [85]:

1 numbered_text = '011235813'
2 print(numbered_text.isiden fier())
3 variable = 'numbered_text'
4 print([Link] fier())

False
True

spr ntable() funct on


It returns True f all the characters n the str ng are pr ntable features.

In [89]:

1 text = 'Hello, Python!'


2 print([Link]())
3 new_text = 'Hello, \n Python!'
4 print(new_text.isprintable())
5 space = ' '
6 print([Link]())

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]:

1 text = 'Hello, Python!'


2 print([Link]())
3 space = ' '
4 print([Link]())

False
True

slower() and lower() funct ons


The funct on slower() returns True f all the characters n the str ng are lower case, on the contrary False.
The funct on lower() converts the certa n str ng to lower case.

In [94]:

1 text = 'Hello, Python!'


2 print([Link]())
3 text = [Link]() # It converts to lower case all the characters in the string.
4 print([Link]()) # Now, it returns True.

False
True

supper() and upper() funct ons


The funct on supper() returns True f all the characters n the str ng are upper case, on the contrary False.
The funct on upper() converts the str ng to uppercase.

In [95]:

1 text = 'Hello, Python!'


2 print([Link]())
3 text = [Link]() # It converts to upper case all the characters in the string.
4 print([Link]()) # Now, it returns True.

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.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/15. Str ngs Op… 10/14


20.06.2022 16:06 15. Str ngs Operators and Funct ons n Python - Jupyter Notebook

In [100]:

1 text_list = ['Hello', 'World', 'Hi', 'Python']


2 print('#'. join(text_list))
3 text_tuple = ('Hello', 'World', 'Hi', 'Python')
4 print('+'. join(text_tuple))
5 text_set = {'Hello', 'World', 'Hi', 'Python'}
6 print('--'. join(text_set))
7 text_dict = {'val1': 'Hello', 'val2': 'World', 'val3': 'Hi', 'val4': 'Python'}
8 print('--'. join(text_dict))

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.')

Python------------------------ 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.')

------------------------Python is my favorite programming language.

lstr p() funct on


It removes characters from the left based on the argument (a str ng spec fy ng the set of characters to be
removed).

In [103]:

1 text = ' Hello Python! '


2 print([Link]()) # It did not delete the white spaces in the right side.

Hello Python!

rstr p() funct on


localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/15. Str ngs Op… 11/14
20.06.2022 16:06 15. Str ngs Operators and Funct ons n Python - Jupyter Notebook

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]:

1 text = ' Hello Python! '


2 print([Link]()) # It did not delete the white spaces in the le side.

Hello Python!

str p() funct on


It removes or truncates the g ven characters from the beg nn ng and the end of the or g nal str ng.
The default behav or of the str p() method s to remove the wh tespace from the beg nn ng and at the end
of the str ng.

In [105]:

1 text = ' Hello Python! '


2 print([Link]()) # It deleted the white spaces in the both side.

Hello Python!

replace() funct on
Replaces a spec f ed phrase w th another spec f ed phrase.

In [106]:

1 text = 'JavaScript is a programming language.'


2 print(text)
3 modified_text = [Link]('JavaScript', 'Python', 1)
4 print(modified_text)

JavaScript is a programming language.


Python is a programming language.

In [107]:

1 text = 'Jython is a programming language.'


2 print(text)
3 modified_text = [Link]('J', 'P')
4 print(modified_text)

Jython is a programming language.


Python is a programming language.

part t on() funct on


It searches for a spec f ed str ng, and spl ts the str ng nto a tuple conta n ng three elements.
The f rst element conta ns the part before the spec f ed str ng.
The second element conta ns the spec f ed str ng.
The th rd element conta ns the part after the str ng.
localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/15. Str ngs Op… 12/14
20.06.2022 16:06 15. Str ngs Operators and Funct ons n Python - Jupyter Notebook

In [114]:

1 text = 'Hello World!, Hi Python!'


2 print([Link] on('Hi'))

('Hello World!, ', 'Hi', ' Python!')

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]:

1 text = 'Hello, Python is my favorite programming language.'


2 print(f"'Python' is in the posi on {text.rfind('Python')}.")
3 print(f"'my' is in the posi on {text.rfind('my')}.")
4 print(f"'close' is in the posi on {text.rfind('close')}.")

'Python' is in the posi on 7.


'my' is in the posi on 17.
'close' is in the posi on -1.

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]:

1 text = 'Hello, Python is my favorite programming language.'


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')}.")

'Python' is in the posi on 7.


'my' is in the posi on 17.

---------------------------------------------------------------------------
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')}.")

ValueError: substring not found

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]:

1 text = 'Hello Python!'


2 print([Link]())
3 text = 'hELLO pYTHON!'
4 print([Link]())

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]:

1 text = 'hello world, hi python!'


2 print(text. tle())

Hello World, Hi Python!

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/15. Str ngs Op… 14/14


13.06.2022 13:12 16. Arrays n Python - Jupyter Notebook

Python Tutor al
Created by Mustafa Germec, PhD

16. Arrays n Python


Array s a conta ner wh ch can hold a f x number of tems and these tems should be of the same type.
Most of the data structures make use of arrays to mplement the r algor thms.
L sts can be used to form arrays.
Follow ng are the mportant terms to understand the concept of Array.
Element: Each tem stored n an array s called an element.
Index: Each locat on of an element n an array has a numer cal ndex, wh ch s used to dent fy the
element.

Array ndex beg ns w th 0.


Each element n the array can be accessed w th ts ndex number.
The length of the array descr bes the capac ty to store the elements.
Bas c array operat ons are Traverse, Insert on, Delet on, Search, and Update.

Creat ng an array
You should mport the module name 'array' as follows:

mport array or from array mport (*).


(*) means that t covers all features of the array.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/16. Arrays n Py… 1/10


13.06.2022 13:12 16. Arrays n Python - Jupyter Notebook

In [4]:

1 # Import the module


2 import array as arr
3 from array import *

In [5]:

1 # To access more informa on regarding array, you can execute the following commands
2 help(arr)

Help on built-in module array:

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

ArrayType = class array(buil [Link])


| array(typecode [, ini alizer]) -> array
|
| Return a new array whose items are restricted by typecode, and
| ini alized from the op onal ini alizer value which must be a list

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:

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/16. Arrays n Py… 2/10


13.06.2022 13:12 16. Arrays n Python - Jupyter Notebook

In [6]:

1 special_nums = [Link]('d', [0.577, 1.618, 2.718, 3.14, 6, 37, 1729])


2 for i in special_nums:
3 print(i)

0.577
1.618
2.718
3.14
6.0
37.0
1729.0

Access ng

In [7]:

1 special_nums = [Link]('d', [0.577, 1.618, 2.718, 3.14, 6, 37, 1729])


2 print(f'First element of numbers is {special_nums[0]}, called euler constant.')
3 print(f'Second element of numbers is {special_nums[1]}, called golden_ra o.')
4 print(f'Last element of numbers is {special_nums[-1]}, called Ramanujan-Hardy number.')

First element of numbers is 0.577, called euler constant.


Second element of numbers is 1.618, called golden_ra o.
Last element of numbers is 1729.0, called Ramanujan-Hardy number.

Chang ng or Updat ng

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/16. Arrays n Py… 3/10


13.06.2022 13:12 16. Arrays n Python - Jupyter Notebook

In [8]:

1 nums = [Link]('i', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34])


2
3 # Changing the first element of the array
4 nums[0] = 55
5 print(nums)
6
7 # Changing 2nd to 4th elements of the array
8 nums[1:4] =[Link]('i', [89, 144, 233, 377])
9 print(nums)

array('i', [55, 1, 1, 2, 3, 5, 8, 13, 21, 34])


array('i', [55, 89, 144, 233, 377, 3, 5, 8, 13, 21, 34])

Delet ng

In [9]:

1 nums = [Link]('i', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34])


2
3 # Dele ng the first element of the array
4 del nums[0]
5 print(nums)
6
7 # Dele ng the 2nd to 4th elements of the array
8 del nums[1:4]
9 print(nums)

array('i', [1, 1, 2, 3, 5, 8, 13, 21, 34])


array('i', [1, 5, 8, 13, 21, 34])

Lenght of the array

In [10]:

1 special_nums = [Link]('d', [0.577, 1.618, 2.718, 3.14, 6, 37, 1729])


2 print(f'The length of the array is {len(special_nums)}.')

The length of the array is 7.

Concatenat on

In [11]:

1 special_nums = [Link]('d', [0.577, 1.618, 2.718, 3.14, 6, 37, 1729])


2 fibonacci_nums = [Link]('d', [1, 1, 2, 3, 5, 8, 13, 21, 34])
3 special_fibonacci_nums = [Link]('d')
4 special_fibonacci_nums = special_nums + fibonacci_nums
5 print(f'The new array called special_fibonacci_nums is {special_fibonacci_nums}.')

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]).

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/16. Arrays n Py… 4/10


13.06.2022 13:12 16. Arrays n Python - Jupyter Notebook

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]

Add t on w th the funct ons nsert() and append()

In [14]:

1 # Using the func on 'insert()'


2 fibonacci_nums = [Link]('i', [1, 1, 2, 3, 5, 8, 13, 21, 34])
3 print('Before any additon into fibonacci numbers')
4 for i in fibonacci_nums:
5 print(i, end = ' ')
6 print()
7 print('A er an element additon into fibonacci numbers')
8 added_num = fibonacci_nums[-1] + fibonacci_nums[-2]
9 fibonacci_nums.insert(9, added_num)
10 for i in fibonacci_nums:
11 print(i, end = ' ')
12 print()
13 print('A er an element additon into fibonacci numbers')
14 added_num = fibonacci_nums[-1] + fibonacci_nums[-2]
15 fibonacci_nums.insert(10, added_num)
16 for i in fibonacci_nums:
17 print(i, end = ' ')

Before any additon into fibonacci numbers


1 1 2 3 5 8 13 21 34
A er an element additon into fibonacci numbers
1 1 2 3 5 8 13 21 34 55
A er an element additon into fibonacci numbers
1 1 2 3 5 8 13 21 34 55 89

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/16. Arrays n Py… 5/10


13.06.2022 13:12 16. Arrays n Python - Jupyter Notebook

In [15]:

1 # Using the func on 'append()'


2 fibonacci_nums = [Link]('i', [1, 1, 2, 3, 5, 8, 13, 21, 34])
3 print('Before any additon into fibonacci numbers')
4 for i in fibonacci_nums:
5 print(i, end = ' ')
6 print()
7 print('A er an element additon into fibonacci numbers')
8 added_num = fibonacci_nums[-1] + fibonacci_nums[-2]
9 fibonacci_nums.append(added_num)
10 for i in fibonacci_nums:
11 print(i, end = ' ')
12 print()
13 print('A er an element additon into fibonacci numbers')
14 added_num = fibonacci_nums[-1] + fibonacci_nums[-2]
15 fibonacci_nums.append(added_num)
16 for i in fibonacci_nums:
17 print(i, end = ' ')

Before any additon into fibonacci numbers


1 1 2 3 5 8 13 21 34
A er an element additon into fibonacci numbers
1 1 2 3 5 8 13 21 34 55
A er an element additon into fibonacci numbers
1 1 2 3 5 8 13 21 34 55 89

Remov ng w th the funct on remove() and pop()

In [16]:

1 # Using the func on 'remove()'


2 special_nums = [Link]('d', [0.577, 1.618, 2.718, 3.14, 6, 37, 1729])
3 print('Before removing an element from the array')
4 for i in special_nums:
5 print(i, end = ' ')
6 print()
7 print('A er removing an element from the array')
8 special_nums.remove(0.577)
9 for i in special_nums:
10 print(i, end=' ')
11 print()
12 print('A er removing one more element from the array')
13 special_nums.remove(special_nums[0]) # We can make this using indexing
14 for i in special_nums:
15 print(i, end=' ')

Before removing an element from the array


0.577 1.618 2.718 3.14 6.0 37.0 1729.0
A er removing an element from the array
1.618 2.718 3.14 6.0 37.0 1729.0
A er removing one more element from the array
2.718 3.14 6.0 37.0 1729.0

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/16. Arrays n Py… 6/10


13.06.2022 13:12 16. Arrays n Python - Jupyter Notebook

In [17]:

1 # Using the func on 'pop()'


2 # The func on pop() removes the last element from the array
3 special_nums = [Link]('d', [0.577, 1.618, 2.718, 3.14, 6, 37, 1729])
4 print('Before removing an element from the array')
5 for i in special_nums:
6 print(i, end = ' ')
7 print()
8 print('A er removing last element from the array')
9 special_nums.pop()
10 for i in special_nums:
11 print(i, end=' ')
12 print()
13 print('A er removing one more last element from the array')
14 special_nums.pop()
15 for i in special_nums:
16 print(i, end=' ')
17 print()
18 print('A er removing one more element using index from the array')
19 special_nums.pop(3) # It deleted the pi number
20 for i in special_nums:
21 print(i, end=' ')
22 print()

Before removing an element from the array


0.577 1.618 2.718 3.14 6.0 37.0 1729.0
A er removing last element from the array
0.577 1.618 2.718 3.14 6.0 37.0
A er removing one more last element from the array
0.577 1.618 2.718 3.14 6.0
A er removing one more element using index from the array
0.577 1.618 2.718 6.0

Sl c ng

In [18]:

1 special_nums = [Link]('d', [0.577, 1.618, 2.718, 3.14, 6, 37, 1729])


2 sliced_special_nums = special_nums[1:5] # It returns between index 1 and index 4, not index 5.
3 print(sliced_special_nums)
4 # or using for loop
5 for i in sliced_special_nums:
6 print(i, end = " ")

array('d', [1.618, 2.718, 3.14, 6.0])


1.618 2.718 3.14 6.0

In [19]:

1 special_nums = [Link]('d', [0.577, 1.618, 2.718, 3.14, 6, 37, 1729])


2 sliced_special_nums = special_nums[3:] # It returns index 3 and later.
3 print(sliced_special_nums)

array('d', [3.14, 6.0, 37.0, 1729.0])

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/16. Arrays n Py… 7/10


13.06.2022 13:12 16. Arrays n Python - Jupyter Notebook

In [20]:

1 special_nums = [Link]('d', [0.577, 1.618, 2.718, 3.14, 6, 37, 1729])


2 sliced_special_nums = special_nums[:3] # It returns un l index 2, not index 3.
3 print(sliced_special_nums)

array('d', [0.577, 1.618, 2.718])

In [21]:

1 special_nums = [Link]('d', [0.577, 1.618, 2.718, 3.14, 6, 37, 1729])


2 sliced_special_nums = special_nums[:] # It returns all elements in the array
3 print(sliced_special_nums)

array('d', [0.577, 1.618, 2.718, 3.14, 6.0, 37.0, 1729.0])

In [22]:

1 special_nums = [Link]('d', [0.577, 1.618, 2.718, 3.14, 6, 37, 1729])


2 sliced_special_nums = special_nums[::-1] # It reverses the array.
3 print(sliced_special_nums)

array('d', [1729.0, 37.0, 6.0, 3.14, 2.718, 1.618, 0.577])

Search ng

In [23]:

1 # To make a search in an array, use the func on index()


2 special_nums = [Link]('d', [0.577, 1.618, 2.718, 3.14, 6, 37, 1729])
3 searched_item = special_nums.index(2.718)
4 print(f'The searched item euler number 2.718 is present at index {searched_item}.')
5 # prin ng with format
6 print('The searched item euler number {} is present at index {}.'.format(2.718, searched_item))

The searched item euler number 2.718 is present at index 2.


The searched item euler number 2.718 is present at index 2.

Copy ng

Copy ng us ng ass gnment

Th s process g ves the same ID number.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/16. Arrays n Py… 8/10


13.06.2022 13:12 16. Arrays n Python - Jupyter Notebook

In [24]:

1 special_nums = [Link]('d', [0.577, 1.618, 2.718, 3.14, 6, 37, 1729])


2 copied_special_nums = special_nums
3 print(special_nums, 'with the ID number', id(special_nums))
4 print(copied_special_nums, 'with the ID number', id(copied_special_nums))
5
6 # Using for loop
7 for i in special_nums:
8 print(i, end= ' ')
9 print()
10 print(f'The ID number of the array special_nums is {id(special_nums)}.')
11 for i in copied_special_nums:
12 print(i, end= ' ')
13 print()
14 print(f'The ID number of the array copied_special_nums is {id(copied_special_nums)}.')

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()

Th s process g ves the d fferent ID number.

In [25]:

1 # import numpy library


2 import numpy as np
3
4 # Copying the array
5 special_nums = [Link]( [0.577, 1.618, 2.718, 3.14, 6, 37, 1729])
6 copied_special_nums = special_nums.view()
7 print(special_nums, 'with the ID number', id(special_nums))
8 print(copied_special_nums, 'with the ID number', id(copied_special_nums))
9
10 #Using for loop
11 for i in special_nums:
12 print(i, end = ' ')
13 print()
14 for i in copied_special_nums:
15 print(i, end = ' ')
16

[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()

Th s process g ves the d fferent ID number.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/16. Arrays n Py… 9/10


13.06.2022 13:12 16. Arrays n Python - Jupyter Notebook

In [26]:

1 # import numpy library


2 import numpy as np
3
4 # Copying the array
5 special_nums = [Link]( [0.577, 1.618, 2.718, 3.14, 6, 37, 1729])
6 copied_special_nums = special_nums.copy()
7 print(special_nums, 'with the ID number', id(special_nums))
8 print(copied_special_nums, 'with the ID number', id(copied_special_nums))
9
10 #Using for loop
11 for i in special_nums:
12 print(i, end = ' ')
13 print()
14 for i in copied_special_nums:
15 print(i, end = ' ')
16

[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

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/16. Arrays n P… 10/10


20.06.2022 16:07 17. Lambda Funct ons n Python - Jupyter Notebook

Python Tutor al
Created by Mustafa Germec, PhD

17. Lambda Funct ons n Python


A lambda funct on s a small anonymous funct on.
A lambda funct on can take any number of arguments, but can only have one express on.
The express on s evaluated and returned.
Lambda funct ons can be used wherever funct on objects are requ red.
Lambda express ons (or lambda funct ons) are essent ally blocks of code that can be ass gned to var ables,
passed as an argument, or returned from a funct on call, n languages that support h gh-order funct ons.
They have been part of programm ng languages for qu te some t me.
The ma n role of the lambda funct on s better descr bed n the scenar os when we employ them
anonymously ns de another funct on.
In Python, the lambda funct on can be ut l zed as an argument to the h gher order funct ons as
arguments.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/17. Lambda Fun… 1/6


20.06.2022 16:07 17. Lambda Funct ons n Python - Jupyter Notebook

In [1]:

1 # Define a func on using 'def'


2 def f(x):
3 return x + 6
4 print(f(3.14))
5
6 # Define the same func on using 'lambda'
7 (lambda x: x+6) (3.14)

9.14

Out[1]:

9.14

In [2]:

1 # Define a func on using 'def'


2 def f(x, y):
3 return x + y
4
5 print('The sum of {} and {} is'.format(3.14, 2.718), f(3.14, 2.718))
6
7 # Define the same func on using 'lambda
8 print(f'The sum of pi number and euler number is {(lambda x, y: x+y)(3.14, 2.718)}.')

The sum of 3.14 and 2.718 is 5.8580000000000005


The sum of pi number and euler number is 5.8580000000000005.

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)}.')

The volume of a cube using def func on is 30.959144000000002.


The volume of a cube using lambda func on is 30.959144000000002.

Mult pl cat on table

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/17. Lambda Fun… 2/6


20.06.2022 16:07 17. Lambda Funct ons n Python - Jupyter Notebook

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

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/17. Lambda Fun… 3/6


20.06.2022 16:07 17. Lambda Funct ons n Python - Jupyter Notebook

In [7]:

1 nums = [lambda a=a:a+3.14 for a in range(5)]


2 nlis = []
3 for num in nums:
4 [Link](num())
5 print(nlis)

[3.14, 4.140000000000001, 5.140000000000001, 6.140000000000001, 7.140000000000001]

lambda funct on w th f/else

In [8]:

1 age = int(input('Enter an age: '))


2 print(f'The entered age is {age}.')
3 (lambda age: print('Therefore, you can use a vote.') if (age>=18) else print('Therefore, you do not use a vote.'))(age)

Enter an age: 18
The entered age is 18.
Therefore, you can use a vote.

lambda funct on usage w th mult ple statements

In [9]:

1 special_nums = [[0.577, 1.618, 2.718, 3.14], [6, 28, 37, 1729]]


2 special_nums_sorted = lambda a: (sorted(i) for i in a)
3
4 # Get the maximum of special numbers in the list
5 special_nums_max = lambda a, f: [y[len(y)-1] for y in f(a)]
6 print(f'The maximum of special numbers in each list is {special_nums_max(special_nums, special_nums_sorted)}.')
7
8 # Get the minimum of special numbers in the list
9 special_nums_min = lambda a, f: [y[len(y)-len(y)] for y in f(a)]
10 print(f'The minimum of special numbers in each list is {special_nums_min(special_nums, special_nums_sorted)}.')
11
12 # Get the second maximum of special numbers in the list
13 special_nums_second_max = lambda a, f: [y[len(y)-2] for y in f(a)]
14 print(f'The second maximum of special numbers in each list is {special_nums_second_max(special_nums, special_num

The maximum of special numbers in each list is [3.14, 1729].


The minimum of special numbers in each list is [0.577, 6].
The second maximum of special numbers in each list is [2.718, 37].

Some examples

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/17. Lambda Fun… 4/6


20.06.2022 16:07 17. Lambda Funct ons n Python - Jupyter Notebook

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)}.')

The mul plica on of euler number and pi number is equal to 8.53452.


The mul plica on of euler number and euler constant is equal to 1.5682859999999998.

In [11]:

1 text = 'Python is a programming language.'


2 print(lambda text: text)

<func on <lambda> at 0x00000210C5812820>

In [12]:

1 text = 'Python is a programming language.'


2 (lambda text: print(text))(text)

Python is a programming language.

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)

[37.68, 3.821656050955414, 15.14, 8.86, 2.5799999999999996, 3.0, 2446.972635086879]

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/17. Lambda Fun… 5/6


20.06.2022 16:07 17. Lambda Funct ons n Python - Jupyter Notebook

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))))

[(1, 1, 2), (2, 1, 2), (3, 1, 2)]


[1.4142135623730951, 2.23606797749979, 3.1622776601683795]

In [16]:

1 help(functools)

Help on module 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)

The following documenta on is automa cally generated from the Python


source files. It may be incomplete, incorrect or include features that
are considered implementa on detail and may vary between Python
implementa ons. When in doubt, consult the module reference at the
loca on listed above.

CLASSES
buil [Link]
cached_property
par al
par almethod
singledispatchmethod

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/17. Lambda Fun… 6/6


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

Math Module Funct ons n Python


Created by Mustafa Germec, PhD

18. Math Module Funct ons n Python


Python math module s def ned as the most famous mathemat cal funct ons, wh ch ncludes
tr gonometr c funct ons, representat on funct ons, logar thm c funct ons, etc.
Furthermore, t also def nes two mathemat cal constants, .e., P e and Euler number, etc.
P e (n): It s a well-known mathemat cal constant and def ned as the rat o of c rcumstance to the d ameter
of a c rcle. Its value s 3.141592653589793.
Euler's number(e):It s def ned as the base of the natural logar thm c, and ts value s
2.718281828459045.
The math module has a set of methods and constants.

In [1]:

1 # Import math module and func ons


2 import math
3 from math import *

In [2]:

1 # Many func ons regarding math modules in python can be find using helf(math) method.
2 help(math)

Help on built-in module 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.

The result is between 0 and pi.

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.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Modul… 1/21


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

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

[-4.951718775643098, 0.0, 4.951718775643098]

ce l() funct on
Rounds a number up to the nearest nteger
Returns the smalles nteger greater than or equal to var able.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Modul… 3/21


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

In [22]:

1 pi_number = [Link] # [Link] is equal to pi_number 3.14.


2 print(f'The nearest integer greater than pi number is {[Link](pi_number)}.')

The nearest integer greater than pi number is 4.

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]:

1 print(f'The combina on of 6 with 2 is {[Link](6, 2)}.')


2 print([Link](10, 3.14)) # It returns a TypeError

The combina on of 6 with 2 is 15.

---------------------------------------------------------------------------
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

TypeError: 'float' object cannot be interpreted as an integer

copys gn() funct on


Returns a float cons st ng of the value of the f rst parameter and the s gn of the second parameter.

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)}.')

The copysign of thes two numbers -3.14 and 2.718 is 3.14.


The copysign of thes two numbers 1729 and -0.577 is -1729.0.

cos() funct on
Return the cos ne of x (measured n rad ans).

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Modul… 4/21


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

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)

[1.5430806348152437, 1.0, 74.20994852478785]

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)

[90.0, 180.0, 45.0, -180.0]

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)))

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Modul… 5/21


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

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)

[1.0, 0.9999911238536323, 0.9998790689599072, 1.0, 0.0, 1.0, 0.9778739803135315, 0.585500565194


3818, -1.0]

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.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Modul… 6/21


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

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)

[0.0, 8.876146367641612e-06, 0.00012093104009276267, 6.348191705159502e-19, 1.0, 2.1519736712


498913e-17, 0.022126019686468514, 0.41449943480561824, 2.0]

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)

[inf, 23.140692632779267, 15.154262241479262, 535.4916555247646, 1.0, 403.4287934927351, 5.042


994235377287, 1.780688344599613, 0.0]

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.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Modul… 7/21


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

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)

[inf, 22.140692632779267, 14.154262241479262, 534.4916555247646, 0.0, 402.4287934927351, 4.042


994235377287, 0.7806883445996128, 6.38905609893065, -1.0]

fabs() funct on
Returns the absolute value of a number

In [14]:

1 print(f'The absolute value of the number -1.618 is {[Link](-1.618)}.')

The absolute value of the number -1.618 is 1.618.

factor al() funct on


Returns the factor al of a number.

In [28]:

1 print(f'The factorial of the number 6 is {[Link](6)}.')

The factorial of the number 6 is 720.

In [29]:

1 # Factorial of nega ve numbers returns a ValueError.


2 print([Link](-6))

---------------------------------------------------------------------------
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))

ValueError: factorial() not defined for nega ve values

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Modul… 8/21


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

In [30]:

1 # Factorial of non-unteger numbers returns a TypeError.


2 print([Link](3.14))

---------------------------------------------------------------------------
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))

TypeError: 'float' object cannot be interpreted as an integer

floor() funct ons:


Rounds a number down to the nearest nteger

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.)

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Modul… 9/21


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

In [142]:

1 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]


2 print([Link](special_nums))

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).

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Mod… 10/21


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

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]:

1 print([Link]([Link], [Link])) # tau number is 2 mes higher than pi number


2 print([Link](3.14, 2.718))
3 print([Link](3.14, 1.618))
4 print([Link](10, 5, rel_tol = 3, abs_tol=0))
5 print([Link](3.14, 3.1400000000001))

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]

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Modu… 11/21


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

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)

[True, False, False, False, False, False, False, False, True]

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.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Mod… 12/21


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

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))

ValueError: isqrt() argument must be nonnega ve

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))

TypeError: 'float' object cannot be interpreted as an integer

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)

[75, 54, 378]

ldexp() funct on
Returns the nverse of [Link]() wh ch s x*(2^ ) of the g ven numbers x and

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Mod… 13/21


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

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)

[4.499809670330265, 0.0, 1.0, 1.1447298858494002, 1.8378770664093453, inf, nan]

log10() funct on
Return the base 10 logar thm of x.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Mod… 14/21


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

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)

[1.954242509439325, 0.0, 0.4342944819032518, 0.49714987269413385, 0.798179868358115, inf, nan]

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)

[4.51085950651685, 0.6931471805599453, 1.3132616875182228, 1.4210804127942926, 1.985568308


7099187, inf, nan]

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)

[6.491853096329675, 1.0, 0.0, 1.4426950408889634, 1.6514961294723187, 2.651496129472319, inf, n


an]

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Mod… 15/21


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

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)

[3.1400000000000006, 5.999999999999999, 2.9999999999999996, 28.000000000000004, nan, 1.0, 0.


0]

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.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Mod… 16/21


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

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]:

1 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]


2 print([Link](special_nums))

85632659.07026622

rad ans() funct on


Convert angle x from degrees to rad ans.

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)

[0.0, 0.5235987755982988, 0.7853981633974483, 1.0471975511965976, 1.5707963267948966, 2.0943


951023931953, 3.141592653589793, 4.71238898038469, 6.283185307179586]

rema nder() funct on


D fference between x and the closest nteger mult ple of y.
Return x - ny where ny s the closest nteger mult ple of y.
ReturnIn the case where x s exactly halfway between two mult ples of
y, the nearest even value of n s used. The result s always exact.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Mod… 17/21


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

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)

[0.42200000000000015, 6.0, -1.0, -10.0]

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)

[1.2246467991473532e-16, 1.0, 0.41078129050290885, nan, -2.4492935982947064e-16, -0.988031624


0928618, 0.9589242746631385, -0.6435381333569995]

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)

[1.1752011936438014, 0.0, -74.20321057778875, 11.548739357257746, 7.544137102816975, 267.744


89404101644, nan, inf]

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

Return the square root of x.

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)

[1.0, 0.0, 6.082762530298219, 1.7724538509055159, 1.6487212707001282, 2.5066282746310002, na


n, inf]

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)

[0.0, -6.405331196646276, 1.6197751905438615, 0.320040389379563, -1.995200412208242, 0.71312


30097859091, 1.3386902103511544, -0.17883906379845224, -3.380140413960958]

tanh() funct on
Return the hyperbol c tangent of x.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Mod… 19/21


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

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)

[0.7615941559557649, 0.0, -0.9999092042625951, 0.99627207622075, 0.9913289158005998, 0.99999


30253396107, nan, 1.0]

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.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Mod… 20/21


15.06.2022 13:55 18. Math Module Funct ons n Python - Jupyter Notebook

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)

[2.220446049250313e-16, 5e-324, 8.881784197001252e-16, 1.1102230246251565e-16, 2.2204460492


50313e-16, 4.440892098500626e-16, 4.440892098500626e-16, 8.881784197001252e-16, nan, inf, inf, n
an, inf, 1.99584030953472e+292]

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/18. Math Mod… 21/21


16.06.2022 11:27 19. L st Comprehens on n Python - Jupyter Notebook

Python Tutor al
Created by Mustafa Germec, PhD

19. L st Comprehens on n Python


L st comprehens on n Python s an easy and compact syntax for creat ng a l st from a str ng or another
l st.
It s a very conc se way to create a new l st by perform ng an operat on on each tem n the ex st ng l st.
L st comprehens on s cons derably faster than process ng a l st us ng the for loop.

Examples

In [3]:

1 import math
2 from math import *

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/19. L st Compreh… 1/8


16.06.2022 11:27 19. L st Comprehens on n Python - Jupyter Notebook

In [24]:

1 # Using for loop


2 cubic_nums = []
3 for i in range(5):
4 i**=3
5 cubic_nums.append(i)
6 print(cubic_nums)
7
8 # Using list comprehension
9 cubic_nums = [i**3 for i in range(5)]
10 print(cubic_nums)
11
12 # Using list comprehension
13 cubic_nums = [[Link](i, 3) for i in range(5)]
14 print(cubic_nums)

[0, 1, 8, 27, 64]


[0, 1, 8, 27, 64]
[0.0, 1.0, 8.0, 27.0, 64.0]

In [90]:

1 # Using for loop


2 even_numbers = []
3 for i in range(21):
4 if i%2 == 0:
5 even_numbers.append(i)
6 print(even_numbers)
7
8 # Using list comprehension
9 even_numbers = [i for i in range(21) if i%2==0]
10 print(even_numbers)

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]


[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

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.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/19. L st Compreh… 2/8


16.06.2022 11:27 19. L st Comprehens on n Python - Jupyter Notebook

In [31]:

1 # Using for loop


2 n = int(input('Enter a number: '))
3 print(f'The entered number is {n}.')
4 insect_nums = []
5 for i in range(12):
6 i = n*(2**i)
7 insect_nums.append(i)
8 print(insect_nums)
9
10 # Using list comprehension
11 insect_nums = [n*(2**i) for i in range(0, 12)]
12 print(insect_nums)

The entered number is 10.


[10, 20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240, 20480]
[10, 20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240, 20480]

In [20]:

1 # Create a list of mul plies of three from 0 to 30


2 # Using for loop
3 nlis =[]
4 for i in range(30):
5 if i%3 == 0:
6 [Link](i)
7 print(nlis)
8
9 # Using list comprehension
10 nlis = [i for i in range(30) if i%3==0]
11 print(nlis)

[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]


[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

In [19]:

1 # Using for loop


2 text = []
3 for i in 'Python is a programming language':
4 [Link](i)
5 print(text)
6
7 # Using list comprehension
8 text = [i for i in 'Python is a programming language']
9 print(text)

['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']

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/19. L st Compreh… 3/8


16.06.2022 11:27 19. L st Comprehens on n Python - Jupyter Notebook

In [33]:

1 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]


2
3 #Using for loop
4 three_ mes = []
5 for i in special_nums:
6 i*=3
7 three_ [Link](i)
8 print(three_ mes)
9
10 # Using list comprehension
11 three_ mes = [x*3 for x in special_nums]
12 print(three_ mes)

[1.7309999999999999, 4.854, 8.154, 9.42, 18, 84, 111, 5187]


[1.7309999999999999, 4.854, 8.154, 9.42, 18, 84, 111, 5187]

In [39]:

1 # Using for loop


2 languages = ['Python', 'Java', 'JavaScript', 'C', 'C++', 'PHP']
3 lang_lis = []
4 for i in languages:
5 if 't' in i:
6 lang_lis.append(i)
7 print(lang_lis)
8
9 #Using list comprehension
10 lang_lis = [i for i in languages if 't' in i]
11 print(lang_lis)

['Python', 'JavaScript']
['Python', 'JavaScript']

In [46]:

1 languages = ['Python', 'Java', 'JavaScript', 'C', 'C++', 'PHP']


2 # Using for loop
3 lang_lis = []
4 for i in languages:
5 if i != 'C':
6 lang_lis.append(i)
7 print(lang_lis)
8
9 #Using list comprehension
10 lang_lis = [i for i in languages if i != 'C']
11 print(lang_lis)

['Python', 'Java', 'JavaScript', 'C++', 'PHP']


['Python', 'Java', 'JavaScript', 'C++', 'PHP']

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/19. L st Compreh… 4/8


16.06.2022 11:27 19. L st Comprehens on n Python - Jupyter Notebook

In [48]:

1 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]


2
3 # Using for loop
4 new_lis = []
5 for i in special_nums:
6 if i < 5:
7 new_lis.append(i)
8 print(new_lis)
9
10 # Using list comprehension
11 new_lis = [i for i in special_nums if i < 5]
12 print(new_lis)

[0.577, 1.618, 2.718, 3.14]


[0.577, 1.618, 2.718, 3.14]

In [51]:

1 languages = ['Java', 'JavaScript', 'C', 'C++', 'PHP']


2 # Using for loop
3 lang_lis = []
4 for i in languages:
5 i = 'Python'
6 lang_lis.append(i)
7 print(lang_lis)
8
9 #Using list comprehension
10 lang_lis = ['Python' for i in languages]
11 print(lang_lis)

['Python', 'Python', 'Python', 'Python', 'Python']


['Python', 'Python', 'Python', 'Python', 'Python']

In [53]:

1 languages = ['Java', 'JavaScript', 'C', 'C++', 'PHP']


2 # Using for loop
3 lang_lis = []
4 for i in languages:
5 if i != 'Java':
6 lang_lis.append(i)
7 else:
8 lang_lis.append('Python')
9 print(lang_lis)
10
11
12 #Using list comprehension
13 lang_lis = [i if i != 'Java' else 'Python' for i in languages]
14 print(lang_lis)

['Python', 'JavaScript', 'C', 'C++', 'PHP']


['Python', 'JavaScript', 'C', 'C++', 'PHP']

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/19. L st Compreh… 5/8


16.06.2022 11:27 19. L st Comprehens on n Python - Jupyter Notebook

In [56]:

1 languages = ['Python', 'Java', 'JavaScript', 'C', 'C++', 'PHP']


2 # Using for loop
3 lang_lis = []
4 for i in languages:
5 i = [Link]()
6 lang_lis.append(i)
7 print(lang_lis)
8
9 #Using list comprehension
10 lang_lis = [[Link]() for i in languages]
11 print(lang_lis)

['PYTHON', 'JAVA', 'JAVASCRIPT', 'C', 'C++', 'PHP']


['PYTHON', 'JAVA', 'JAVASCRIPT', 'C', 'C++', 'PHP']

In [59]:

1 # Using for loop


2 python = []
3 for i in 'Python':
4 [Link](i)
5 print(python)
6
7 # Using list comprehension
8 python = [i for i in 'Python']
9 print(python)
10
11 # Using lambda func on
12 python = list(map(lambda i: i, 'Python'))
13 print(python)

['P', 'y', 't', 'h', 'o', 'n']


['P', 'y', 't', 'h', 'o', 'n']
['P', 'y', 't', 'h', 'o', 'n']

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/19. L st Compreh… 6/8


16.06.2022 11:27 19. L st Comprehens on n Python - Jupyter Notebook

In [85]:

1 # Using for loop


2 numbers = []
3 for i in range(11):
4 if i%2 == 0:
5 [Link]('Even')
6 else:
7 [Link]('Odd')
8 print(f'For loop: {numbers}')
9
10 # Using list comprehension
11 numbers = ['Even' if i%2==0 else 'Odd' for i in range(11)]
12 print(f'List comprehension: {numbers}')
13
14 # Using lambda func on
15 numbers = list(map(lambda i: i, ['Even' if i%2==0 else 'Odd' for i in range(11)]))
16 print(f'Lambda: {numbers}')

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]:

1 # Using nested for loop


2 empty_list = []
3 matrix_list = [[0.577, 1.618, 2.718, 3.14], [6, 28, 37, 1729]]
4
5 for i in range(len(matrix_list[0])):
6 T_row = []
7 for row in matrix_list:
8 T_row.append(row[i])
9 empty_list.append(T_row)
10 print(empty_list)
11
12 # Using list comprehension
13 empty_list = [[row[i] for row in matrix_list] for i in range(4)]
14 print(empty_list)

[[0.577, 6], [1.618, 28], [2.718, 37], [3.14, 1729]]


[[0.577, 6], [1.618, 28], [2.718, 37], [3.14, 1729]]

In [82]:

1 # Using nested for loop


2 empty_matrix = []
3 for i in range(5):
4 empty_matrix.append([])
5 for j in range(5):
6 empty_matrix[i].append(j)
7 print(empty_matrix)
8
9 # Using list comprehension
10 empty_matrix = [[j for j in range(5)] for i in range(5)]
11 print(empty_matrix)

[[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]]

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/19. L st Compreh… 7/8


16.06.2022 11:27 19. L st Comprehens on n Python - Jupyter Notebook

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)

[[0.577, 2.718, 6], [1.618, 3.14, 28], [0, 1, 28]]

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/19. L st Compreh… 8/8


20.06.2022 16:06 20. Decorators n Python - Jupyter Notebook

Python Tutor al
Created by Mustafa Germec, PhD

20. Decorators n Python


Decorators prov de a s mple syntax for call ng h gher-order funct ons.
By def n t on, a decorator s a funct on that takes another funct on and extends the behav or of the latter
funct on w thout expl c tly mod fy ng t.
A decorator n Python s a funct on that takes another funct on as ts argument, and returns yet another
funct on.
Decorators can be extremely useful as they allow the extens on of an ex st ng funct on, w thout any
mod f cat on to the or g nal funct on source code.
In fact, there are two types of decorators n Python nclud ng class decorators and funct on
decorators.
In appl cat on, decorators are majorly used n creat ng m ddle layer n the backend, t performs task l ke
token authent cat on, val dat on, mage compress on and many more.

Syntax for Decorator

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/20. Decorators … 1/14


20.06.2022 16:06 20. Decorators n Python - Jupyter Notebook

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)

Help on func on decorator in module decorator:

decorator(caller, _func=None, kwsyntax=False)


decorator(caller) converts a caller func on into a 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!')

Python is a programming language.


Hell, Python!

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/20. Decorators … 2/14


20.06.2022 16:06 20. Decorators n Python - Jupyter Notebook

In [1]:

1 def mul plica on(num):


2 return num * num
3
4 mult = mul plica on
5 mult(3.14)

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

Python is a programming language.


Hello, Python!
Hi, World!

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()

Python is a programming language.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/20. Decorators … 3/14


20.06.2022 16:06 20. Decorators n Python - Jupyter Notebook

In [4]:

1 def func on(num):


2 def mult(num):
3 return num*num
4
5 output = mult(num)
6 return output
7 mult(3.14)

Out[4]:

9.8596

In [13]:

1 def msg(text):
2 'Hello, World!'
3 def mail():
4 'Hi, Python!'
5 print(text)
6
7 mail()
8
9 msg('Python is the most popular programming language.')

Python is the most popular programming language.

Pass ng funct ons

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

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/20. Decorators … 4/14


20.06.2022 16:06 20. Decorators n Python - Jupyter Notebook

In [7]:

1 def addi on(num):


2 return num + [Link]
3
4 def called_func on(func):
5 added_number = math.e
6 return func(added_number)
7
8 called_func on(addi on)

Out[7]:

5.859874482048838

In [111]:

1 def decorator_one(func on):


2 def inner():
3 num = func on()
4 return num * (num**num)
5 return inner
6
7 def decorator_two(func on):
8 def inner():
9 num = func on()
10 return (num**num)/num
11 return inner
12
13 @decorator_one
14 @decorator_two
15 def number():
16 return 4
17
18 print(number())
19
20 # The above decorator returns the following code
21 x = pow(4, 4)/4
22 print(x*(x**x))

2.5217283965692467e+117
2.5217283965692467e+117

Funct ons revert ng other funct ons

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())

Python is a programming language.

Decorat ng funct ons


localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/20. Decorators … 5/14
20.06.2022 16:06 20. Decorators n Python - Jupyter Notebook
g

In [8]:

1 # Define a decora ng func on


2 """
3 In the following example, the func on outer_addi on that is some voluminous is decorated.
4 """
5 def addi on(a, b):
6 print(a+b)
7 def outer_addi on(func):
8 def inner(a, b):
9 if a < b:
10 a, b = b, a
11 return func(a, b)
12 return inner
13
14 result = outer_addi on(addi on)
15 result([Link], math.e)

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

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/20. Decorators … 6/14


20.06.2022 16:06 20. Decorators n Python - Jupyter Notebook

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())

PYTHON IS THE MOST POPULAR PROGRAMMING LANGUAGE.


PYTHON IS THE MOST POPULAR PROGRAMMING LANGUAGE.

Reprocess ng decorator
The decorator can be reused by recall ng that decorator funct on.

In [37]:

1 def do_twice(func on):


2 def wrapper_do_twice():
3 func on()
4 func on()
5 return wrapper_do_twice
6
7 @do_twice
8 def text():
9 print('Python is a programming language.')
10 text()

Python is a programming language.


Python is a programming language.

Decorators w th Arguments

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/20. Decorators … 7/14


20.06.2022 16:06 20. Decorators n Python - Jupyter Notebook

In [39]:

1 def do_twice(func on):


2 """
3 The func on wrapper_func on() can admit any number of argument and pass them on the func on.
4 """
5 def wrapper_func on(*args, **kwargs):
6 func on(*args, **kwargs)
7 func on(*args, **kwargs)
8 return wrapper_func on
9
10 @do_twice
11 def text(programming_language):
12 print(f'{programming_language} is a programming language.')
13 text('Python')

Python is a programming language.


Python is a programming language.

Return ng values from decorated funct on

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')

Python is a programming language.


Python is a programming language.

Fancy decorators
@propertymethod
@stat cmethod
@classmethod

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/20. Decorators … 8/14


20.06.2022 16:06 20. Decorators n Python - Jupyter Notebook

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]}.')

Microorganism name: Aspergillus niger


Microorganism product: inulinase
Message: Aspergillus niger produces inulinase enzyme.

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]()

Aspergillus niger is a fungus that produces inulinase enzyme.


Aspergillus niger is a fungus that produces inulinase enzyme.

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

The fungus Aspergillus niger produces inulinase enzyme.

Decorator w th arguments

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/20. Decorators … 9/14


20.06.2022 16:06 20. Decorators n Python - Jupyter Notebook

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")

The arguments are Python and R.


My favorite programming languages are Python and R.

Mult ple decorators

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/20. Decorators… 10/14


20.06.2022 16:06 20. Decorators n Python - Jupyter Notebook

In [18]:

1 def spli ed_text(text):


2 def wrapper():
3 func on = text()
4 text_spli ng = func [Link]()
5 return text_spli ng
6
7 return wrapper
8
9 @spli ed_text
10 @decorator_text_uppercase # Calling other decorator above
11 def text():
12 return 'Python is the most popular programming language.'
13 text()

Out[18]:

['PYTHON', 'IS', 'THE', 'MOST', 'POPULAR', 'PROGRAMMING', 'LANGUAGE.']

Arb trary arguments

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/20. Decorators… 11/14


20.06.2022 16:06 20. Decorators n Python - Jupyter Notebook

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")

1. Without arguments decorator


These are posi onal arguments ().
These are keyword arguments {}.
There is no argument in this decorator.
2. With posi onal arguments decorator
These are posi onal arguments (inf, 6.283185307179586, 3.141592653589793, 2.718281828459045, na
n, -inf).
These are keyword arguments {}.
inf 6.283185307179586 3.141592653589793 2.718281828459045 nan -inf
3. With keyword arguments decorator
These are posi onal arguments ().
These are keyword arguments {'language_1': 'Python', 'language_2': 'R'}.
Python and R are my favorite programming languages and keyword arguments.

Debugg ng decorators

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/20. Decorators… 12/14


20.06.2022 16:06 20. Decorators n Python - Jupyter Notebook

In [69]:

1 def capitalize_dec(func on):


2 @[Link](func on)
3 def wrapper():
4 return func on().capitalize()
5 return wrapper
6
7 @capitalize_dec
8 def message():
9 "Python is the most popular programming language."
10 return 'PYTHON IS THE MOST POPULAR PROGRAMMING LANGUAGE. '
11
12 print(message())
13 print()
14 print(message.__name__)
15 print(message.__doc__)

Python is the most popular programming language.

message
Python is the most popular programming language.

Preserv ng decorators

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/20. Decorators… 13/14


20.06.2022 16:06 20. Decorators n Python - Jupyter Notebook

In [85]:

1 def preserved_decorator(func on):


2 def wrapper():
3 print('Before calling the func on, this is printed.')
4 func on()
5 print('A er calling the func on, this is printed.')
6 return wrapper
7
8 @preserved_decorator
9 def message():
10 """This func on prints the message when it is called."""
11 print('Python is the most popular programming language.')
12
13 message()
14 print(message.__name__)
15 print(message.__doc__)
16 print(message.__class__)
17 print(message.__module__)
18 print(message.__code__)
19 print(message.__closure__)
20 print(message.__annota ons__)
21 print(message.__dir__)
22 print(message.__format__)

Before calling the func on, this is printed.


Python is the most popular programming language.
A er calling the func on, this is printed.
wrapper
None
<class 'func on'>
__main__
<code object wrapper at 0x0000029986F96970, file "C:\Users\test\AppData\Local\Temp/ipykernel_118
0/[Link]", line 2>
(<cell at 0x0000029986311840: func on object at 0x0000029981A03F40>,)
{}
<built-in method __dir__ of func on object at 0x0000029986273250>
<built-in method __format__ of func on object at 0x0000029986273250>

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/20. Decorators… 14/14


19.06.2022 03:57 21. Generators n Python - Jupyter Notebook

Python Tutor al
Created by Mustafa Germec, PhD

21. Generators n Python


Python generators are the funct ons that return tha traversal object and a s mple way of creat ng terators.
It traverses the ent re tems at once.
The generator can alos be an express on n wh ch syntax s sm lar to the l st comprehens on n python.
There s a lot of complex ty n creat ng terat on n Python, t s requ red to mplement ter() and next()
methods to keep track of nternal states.
It s a lenghty process to create terators.
That s why the generator plays a s gn f cant role n s mplfy ng th s process.
If there s no value found n terat on, t ra ses StopIterat on except on.
t s qu te s mple to create a generator n Python.
It s s m lar to the normal funct on def ned by the def keyword and employs a y eld keyword nstead of
return.
If the body of any funct on ncludes a y eld statement, t automat cally becomes a generator funct on.
The y eld keyword s respons bel to control the flow of the generator funct on.
It pauses the funct on execut on by sav ng all states and y elded to the caller.
Later t resumes execut on when a success ve funct on s called.
The return keyword returns a value and term nates the whole funct on and only one return statement can
be employed n the funct on.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/21. Generators n… 1/7


19.06.2022 03:57 21. Generators n Python - Jupyter Notebook

In [22]:

1 def func on():


2 for i in range(10):
3 if i%2==0:
4 yield i
5
6 nlis = []
7 for i in func on():
8 [Link](i)
9 print(nlis)

[0, 2, 4, 6, 8]

In [26]:

1 def func():
2 for i in range(25):
3 if i%4==0:
4 yield i
5
6 num_lis = []
7 for i in func():
8 num_lis.append(i)
9 print(num_lis)

[0, 4, 8, 12, 16, 20, 24]

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.

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/21. Generators n… 2/7


19.06.2022 03:57 21. Generators n Python - Jupyter Notebook

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)

[1.7309999999999999, 4.854, 8.154, 9.42, 18, 111, 5187]


<generator object <genexpr> at 0x000002572F0E1230>

In [8]:

1 special_nums = [0.577, 1.618, 2.718, 3.14, 6, 37, 1729]


2
3 generator_exp = (i*3 for i in special_nums) # This is a generator expression.
4
5 nums_list = []
6 nums_list.append(next(generator_exp))
7 nums_list.append(next(generator_exp))
8 nums_list.append(next(generator_exp))
9 nums_list.append(next(generator_exp))
10 nums_list.append(next(generator_exp))
11 nums_list.append(next(generator_exp))
12 nums_list.append(next(generator_exp))
13 print(nums_list)

[1.7309999999999999, 4.854, 8.154, 9.42, 18, 111, 5187]

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]

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/21. Generators n… 3/7


19.06.2022 03:57 21. Generators n Python - Jupyter Notebook

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)}.')

Memory in bytes with list comprehension is 12728.


Memory in bytes with generator expression is 104.

You can f nd more nformat on by execut ng the follow ng command


help(sys)

The follw ng generator produces nf n te numbers.

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)

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/21. Generators n… 4/7


19.06.2022 03:57 21. Generators n Python - Jupyter Notebook

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:

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/21. Generators n… 5/7


19.06.2022 03:57 21. Generators n Python - Jupyter Notebook

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}.')

The number using while loop is 1.


The number using while loop is 1.
The number using while loop is 4.
The number using while loop is 27.
The number using while loop is 256.
The number using while loop is 3125.
The numbers using for loop are [1, 1, 4, 27, 256, 3125].
The numbers using generator comprehension are [1, 1, 4, 27, 256, 3125].

In [42]:

1 import math
2 sum(i**i for i in range(6))

Out[42]:

3414

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/21. Generators n… 6/7


19.06.2022 03:57 21. Generators n Python - Jupyter Notebook

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

localhost:8888/notebooks/Desktop/PROGRAMMING/PYTHON_TUTORIAL/01. python_f les_for_shar ng/jupyter_notebook_f les/21. Generators n… 7/7

You might also like