A-Z in Python
A-Z in Python
P
ython is a popular programming language created by Guido van
Rossum and launched in 1991. It can be used to build web
applications, servers, in combination with other software to create
workflows, connect to a relational database system that uses Structured
Query Languages (SQLs) such as Oracle, DB2 or MySQL, as well as
connect to non-relational database systems (NoSQL) such as MongoDB.
This is explained in detail in the Advanced Python Programming Textbook.
Advantages of the Python language include:
Installing Python
Many PCs and Macs have Python pre-installed. To check, launch the
Terminal App on Mac, or Command Line on the PC and enter the command
below.
python
Download the appropriate version for your operating system (in this
example we will install on macOS) using the following steps:
1. Select macOS to download. You should receive file python-3.12.3-
macos11.pkg. Double click the file. The result is shown in Figure 1-2.
Figure 1-2: 1st python installation window for macOS
4. Click
5. You will find various files for programming with python. The result
is shown as Figure 1-5.
Installing a Package
After installing pip, try installing the “numpy” package
VaritSris>pip3 install numpy
Results
Collecting numpy
Downloading numpy-1.26.4-cp312-cp312-macosx_10_9_x86_64.whl.metadata (61 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 61.1/61.1 kB 1.2 MB/s eta 0:00:00
Downloading numpy-1.26.4-cp312-cp312-macosx_10_9_x86_64.whl (20.3 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 20.3/20.3 MB 6.0 MB/s eta 0:00:00
Installing collected packages: numpy
Successfully installed numpy-1.26.4
To check which packages or modules are installed, use the following command:
VaritSris>pip3 list
Results
ackage
P Version
------- -------
numpy 1.26.4
pip 24.0
To use Terminal to program Python, follow these steps:
VaritSris>python3
Results
Python 3.12.3 (v3.12.3:f6650f9ad7, Apr 9 2024, 08:18:48) [Clang 13.0.0
(clang-1300.0.29.30)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
When using the command print('Hi')
>>> print('Hi')
Results
Hi
Click to download the appropriate installer and the installation file will be
shown.
VSCODE Has
its own terminal that runs python, so we need to create a work folder to
keep all programming files. For this textbook, we will use the folder
Click open, then open the newly created folder used to keep our python
files as in Figure 1-11.
Figure 1-11: folder created to keep files for Python software development
Select and open the ExamplePythonCode folder and the following window
will appear in Figure 1-12.
Figure 1-12: Visual Studio Code asking for permission to use the folder
Choose to confirm that you trust the authors, since
you created this folder yourself.
When selected this screen will be shown in Figure 1-13.
Then select “New terminal.” A new terminal window will appear as shown
in Figure 1-15.
After that, select the terminal window and enter the following instructions:
VaritSris>python Hi.py
Results
What is your name?
Enter VariitSris
What is your name?VariitSris
Results
Hi VariitSris
The Code input('What is your name?') is using the text “What is your
name?” To query its user to enter information.
Changing the program text to
print("Welcome "+input("What is your name?")+ " to Thailand")
Then running Hi.py
VaritSris>python3 Hi.py
Results
What is your name? VariitSris
Results
Welcome VariitSris to Thailand
Example
print('No.of Character '+
str(len(input('What is your name? '))))
Results
What is your name? VariitSris
No.of Character 10
Example
name = "Jack"
print(name)
name = "Angela"
print(name)
name = input("What is your name?")
length = len(name)
print(length)
Results
Jack
Angela
What is your name?VariitSris
10
virtual environment
In case you want to use multiple versions of Python and mutiple projects on
single machine
The methods and steps for using a virtual environment vary according
to different operating systems. For this textbook, let's use macOS as an
example.
1. Install brew
2. Update brew
brew update
3. Install pyenv
5. Install pyenv-virtualenv
Game
pyenv virtualenv 3.9.16 PyGame
Web Application
pyenv virtualenv 3.9.16 PyWebApp
Data Analysis
pyenv virtualenv 3.9.16 PyDataAnalysis
AI
pyenv virtualenv 3.9.16 PyAI
The command used to create a virtual environment with python
version is shown as follows.
pyenv virtualenv <python_version> <environment_name>
9. Exit environment.
source deactivate
10. uninstall environment.
P
ython has the following Data Types:
● Integers
Data that is any whole number, such as 123247289343214
● Floats
Data that is any numbers with decimal places, such as 23.5 or 8.63
● Strings
Characters enclosing quotes, such as “Hi”
● Boolean
Can only be True or False
● Lists/Dictionaries/Sets/Tuples
(Examples and programming functions in Chapter 3)
To determine the correct data class that will function as such, you
must use variables to configure the data class you need.
Integers
Floats
Strings
In case of String Class Data
Determine the Tourist’s name (TouristName) as Character strings
by using quotation marks. either “” or ‘’ will work.
TouristName =’Peter’ or TouristName =”Peter”
String Functions
String values have the following functions:
print(“Top"[0]) Results: T
print("Top"[2]) Results: p
print("56"+"211") Results 56211 (as a string)
We can also find the number of characters in the string:
num_char = len(input("What is your name? "))
print("Your name has "+str(num_char)+" characters.")
Results
What is your name? Top
Your name has 3 characters.
We can combine string values, but if the value is not a string value but an
integer, you convert its class into string like this:
num_char = len(input("What is your name? "))
print(type(num_char))
print("Your name has "+str(num_char)+" characters.")
Results
What is your name? Top
<class 'int'>
Your name has 3 characters.
print(str(4.8)+str(9)) to convert values to string
Results
4.89
Boolean
Boolean has a value of True or False only, as in the example.
Finding a value in a string whether it exists or not. If there is a result,
it will be True, if it is not there, it will be False.
sentence = "Lisa is beautiful girl"
print("Lisa" in sentence)
Result
True
Table 2-2: Frequently Functions Used in String Type Data for Python
Frequently Functions Used in String Type Data for Python
Function Descriptio Example
n
capitalize( Capitalizes sentence = "lisa is a beautiful girl"
) first print(sentence.capitalize())
character Results
Lisa is a beautiful girl
casefold() Make all sentence = "lISa Is a beaUtiful Girl"
characters print(sentence.casefold())
lowercase Results
lisa is a beautiful girl
center() Centers all sentence = "Lisa is beautiful "
characters print(sentence.center(40))
according Results
to the Lisa is beautiful
number of
characters
in brackets.
Frequently Functions Used in String Type Data for Python
Function Descriptio Example
n
count() Find the sentence = "Lisa is a beautiful girl. "
number of print(sentence.count("a"))
words or Results
letters in 3
brackets of
a string
sentence = "Lisa is a beautiful girl. She
has a child. She has two dogs."
print(sentence.count("has"))
Results
2
sentence = "Lisa is a beautiful girl. She
likes to eat bananas. And likes to give
bananas to her friends. She grows
bananas in her garden"
print(sentence.count("i"))
Results
9
sentence = "Lisa is
a beautiful girl. She likes to eat
bananas, and likes to give
bananas to her
friends. She grows bananas in her
garden."
indexPosition = sentence. index("xxx")
print(indexPosition)
Returns
Results
ValueError: substring not found
Frequently Functions Used in String Type Data for Python
Function Descriptio Example
n
format() Format To display the amount decimal value,
decimal sentence = "Yesterday, Lisa bought
places. e.g.: bananas for {amount:.2f} baht.”
.2f, print(sentence.format(amount=50))
displays 2 Results
decimal
Yesterday, Lisa bought bananas for
places,
50.00 baht.
rounded
up. .0f
displays an If the next decimal is 5 or more, it will
integer. round up. 50.558
rounds to 50.56
sentence = "Yesterday, Lisa bought
bananas for {price:.2f} baht."
print(sentence.format(price=50.558))
Results
Yesterday, Lisa bought bananas for
50.56 baht.
25, 45672
etc.
Frequently Functions Used in String Type Data for Python
Function Descriptio Example
n
isprintable If all the sentence = "Yesterday, Lisa bought
() characters bananas for 50 baht."
in a string print(sentence.isprintable())
are Results
printable True
only, sentence = "Yesterday, \n Lisa bought
returns bananas for 50 baht."
True. print(sentence.isprintable())
Results
False
bananas to her
friends. She grows bananas in her
garden."
print(sentence.replace("bananas",
"apples",1))
Results
Lisa is a beautiful girl. She likes to eat
apples, and likes to give bananas to her
friends. She grows bananas in her
garden.
Results
[‘Lisa’, ‘is’, ‘a’, ‘beautiful’, ‘girl.’,
‘She’, ‘likes’, ‘to’, ‘eat’, ‘bananas,’,
‘and’, ‘likes’, ‘to’, ‘give’, ‘bananas’,
‘to’, ‘her’, ‘friends.’, ‘She’, ‘grows’,
‘bananas’, ‘in’, ‘her’, ‘garden.’]
splitlines( Split lines sentence = "Lisa is a beautiful girl.
) in a string. \nShe likes to eat bananas. And likes to
requires /n give bananas to her friends. \nShe
to create grows bananas in her garden."
line breaks. splitLinesSentence =
sentence.splitlines()
print(splitLinesSentence)
Results
[‘Lisa is a beautiful girl.’, ‘She likes to
eat bananas, and likes to give bananas
to her friends.’, ‘She grows bananas in
her garden.’]
Results
True
Exercises
Example
print(fruit[0])
Results
orange
print(fruit[1])
Results
mango
If you want the last index value in the list, we need to know the total number of items
in a list with this function:
len(List)
Example
print(len(fruit))
Results
7
Therefore, if you want to return the last value in the list, then we need to use fruit[6] as
the last value is always len(List)-1 with the first index being 0.
In case you don't want to search with len(List), alternatively we could use negative
indexes, with -1 as the last index as shown in Syntax 3-3.
Syntax 3-3: Negative index of element in List
print(fruit[-1])
Results
papaya
If the index is -3, it will return the 3rd item from the end.
print(fruit[-3])
Results
durian
For functions, refer to Table 3-1.
Table 3-1: Functions Used in Lists for Python
Functions Used in Lists for Python
Funct Descript Example
ion ion
Functions Used in Lists for Python
Funct Descript Example
ion ion
appen Append fruit = ["orange","mango","banana",
d() the new "rambutan", "durian","pineapple",
value at
"papaya"]
the end of
fruit.append("strawberry")
the list.
Duplicate print(fruit)
s can only
be added Results
one value [‘orange’, ‘mango’, ‘banana’, ‘rambutan’, ‘durian’, ‘pineapple’,
at a time.
‘papaya’, ‘strawberry’]
clear() Clear the Clear the “fruit” list of all values.
list. No fruit =
values
["orange","mango","banana","rambutan", "durian","pineapple","papa
kept.
ya"]
fruit.clear()
print(fruit)
Results
[]
exten Results
d() [‘orange’, ‘mango’, ‘banana’, ‘rambutan’, ‘durian’, ‘pineapple’,
‘papaya’, ‘strawberry’, ‘loquat’, ‘lychee’]
index( Returns Find the index of value "mango"
) Index fruit = ["orange","mango","banana", "rambutan","durian","pineapple",
number of
"papaya"]
a value.
indexOfMango=fruit.index("mango")
print(indexOfMango)
Results
1
insert( Insert a Add "strawberry" as the first value in the list.
) value into fruit = ["orange","mango","banana", "rambutan","durian","pineapple",
a list by
"papaya"]
specifying
fruit.insert(0, "strawberry")
its index
number. print(fruit)
Results
[‘strawberry’, ‘orange’, ‘mango’, ‘banana’, ‘rambutan’, ‘durian’,
‘pineapple’, ‘papaya’]
pop() Removes To remove the value indexed as 0, "orange" from the “fruit” list.
a value fruit = ["orange","mango","banana", "rambutan","durian","pineapple",
from the
"papaya"]
list using
fruit.pop(0)
its index.
print(fruit)
Results
[’mango’, ‘banana’, ‘rambutan’, ‘durian’, ‘pineapple’, ‘papaya’]
Functions Used in Lists for Python
Funct Descript Example
ion ion
remov Removes To remove the value "orange" from the list
e() the fruit = ["orange","mango","banana",
specified
"rambutan","durian","pineapple","papaya"]
value
fruit.remove("orange")
from the
list. print(fruit)
Results
[‘mango’, ‘banana’, ‘rambutan’, ‘durian’, ‘pineapple’, ‘papaya’]
sort() Sort the Tube the values alphabetically in ascending order of fruit list:
values fruit = ["orange","mango","banana", "rambutan","durian",
alphabetic
"pineapple","papaya"]
ally or
fruit.sort()
numerical
ly in print(fruit)
ascending
order.
Results
[‘durian’,‘mango’, ‘banana’,’orange’,’papaya’, ‘pineapple’,
‘rambutan’]
If the values within the list have multiple languages, upper and
lowercase, as well as numbers, the
values will be sorted by
numbers value, then all the uppercase values, then all lowercase values,
and finally any other languages.
listSort = ["orange","mango",
"banana",
"Apple","Tomato",
"Peach","5","4","2",
"6"]
listSort.sort()
print(listSort)
Results
['2', '4', '5', '6', 'Apple', 'Peach', 'Tomato', 'mango', 'banana', 'orange']
Functions Used in Lists for Python
Funct Descript Example
ion ion
join() Join the to display values in the fruit list separated by /
values in fruit = ["orange","mango","banana",
the list
"rambutan","durian","pineapple","papaya"]
and
display. print("/".join(fruit))
Results
orange/mango/banana/rambutan/durian/pineapple/papaya
To combine two lists together, use Syntax 3-4.
Syntax 3-4: Combining Two Lists
Note
Example:
fruit = ["orange","mango","banana","rambutan", "durian","pineapple", "papaya"]
vegetable = ["tomato","avocado","bean","pepper", "pumpkin"]
plant = [fruit,vegetable]
print(plant)
Results
[[‘orange’, ‘mango’, ‘banana’, ‘rambutan’, ‘durian’, ‘pineapple’, ‘papaya’], [‘tomato’,
‘avocado’, ‘bean’, ‘pepper’, ‘pumpkin’]]
Another way to create lists is with Syntax 3-5.
Syntax 3-5: Create Lists 2
Example:
fruit = list(("orange","mango","banana","rambutan","durian","pineapple", "papaya"))
print(fruit)
Results
[‘orange’, ‘mango’, ‘banana’, ‘rambutan’, ‘durian’, ‘pineapple’, ‘papaya’]
Dictionaries
Dictionaries in Python are data kept in pairs, using the syntax key:value, as shown in
Syntax 3-6.
Syntax 3-6: Create Dictionaries
Tourist={'Ammie','Ann','Minnie','Jame','Mike','Ann'}
print(Tourist)
Results
{'Minnie', 'Ann', 'Jame', 'Ammie', 'Mike'}
For functions, refer to Table 3-3.
Table 3-3: Functions Used in Sets for Python
Functions Used in Sets for Python
Function Description Example
add() Add values into fruit = {"apple","banana",
the set must be a "cherry","orange",
value not
"mango","banana","rambutan","durian",
already
"pineapple", "papaya"}
contained in the
set, otherwise it fruit.add("papaya")
will not be print(fruit)
added. Results
{‘cherry’, ‘mango’, ‘rambutan’, ‘papaya’,
‘banana’, ‘apple’, ‘banana’, ‘durian’,
‘pineapple’, ‘orange’}
fruit =
{"apple","banana","cherry","orange",
"mango", "banana", "rambutan",
"durian", "pineapple", "papaya"}
fruit.add(“strawberry”)
print(fruit)
Results
{‘orange’, ‘durian’, ‘mango’, ‘banana’,
‘strawberry’, ‘pineapple’, ‘cherry’,
‘papaya’, ‘apple’, ‘rambutan’, ‘banana’}
Functions Used in Sets for Python
Function Description Example
clear() Clear the set of fruit =
all values. {"apple","banana","cherry","orange",
"mango","banana","rambutan","durian",
"pineapple","papaya","papaya"}
fruit.clear()
print(fruit)
Results
set()
copy() Copy the set. fruit =
{"apple","banana","cherry","orange",
"mango","banana","rambutan","durian",
"pineapple","papaya","papaya"}
Copy_fruit=fruit.copy()
print(Copy_fruit)
Results
{‘mango’, ‘papaya’, ‘durian’, ‘cherry’,
‘banana’, ‘pineapple’, ‘rambutan’, ‘orange’,
‘apple’, ‘banana’}
Functions Used in Sets for Python
Function Description Example
difference() Display the interfruit =
differences {"apple","banana","cherry","orange",
between two
"mango", "banana", "rambutan",
sets.
"durian", "pineapple",
"papaya","papaya"}
Thaifruit = {"banana","orange","mango",
"banana", "rambutan", "durian",
"pineapple", "papaya"}
print(interfruit.difference(Thaifruit))
Results
{'cherry', 'apple'}
Thaifruit = {"banana","orange","mango",
"banana",
"rambutan","durian","pineapple",
"papaya"}
interfruit.difference_update(Thaifruit)
print(interfruit)
Results
{‘apple’,’cherry’}
Functions Used in Sets for Python
Function Description Example
discard() Clears the values fruit = {"apple","banana",
in brackets from "cherry","orange", "mango", "banana",
the set
"rambutan","durian",
"pineapple","papaya","papaya"}
fruit.discard("apple")
print(fruit)
Results
{‘pineapple’, ‘orange’, ‘banana’,
‘rambutan’, ‘cherry’, ‘durian’, ‘banana’,
‘papaya’, ‘mango’}
intersection() Display like fruit1 = {"apple","banana","banana",
values between "rambutan","durian","pineapple",
2 or more sets.
"papaya"}
fruit2 = {"apple","mango","banana",
"rambutan","durian","pineapple",
"papaya"}
print( fruit1.intersection( fruit2))
Results
{‘papaya’, ‘pineapple’, ‘durian’, ‘apple’,
‘rambutan’, ‘banana’}
fruit1 = {"apple","banana","banana",
"rambutan","durian","pineapple","papaya"
}
fruit2 = {"banana","rambutan","durian",
"pineapple","banana"}
fruit3 = {"rambutan","banana"}
print(fruit1.intersection(fruit2,fruit3))
print(fruit2.intersection(fruit1,fruit3))
print(fruit3.intersection(fruit1,fruit2))
Result of each computation will be the
same, as follows:
Results
{'banana', 'rambutan'}
{'banana', 'rambutan'}
{'banana', 'rambutan'}
Functions Used in Sets for Python
Function Description Example
intersection_upda Display like fruit1 = {"apple","banana","banana",
te() values between "rambutan","durian","pineapple","papaya"
2 or more sets,
}
then remove all
fruit2 =
other values
from the set {"apple","mango","banana","rambutan",
preceding "durian","pineapple","papaya"}
.intersection_up fruit1.intersection_update(fruit2)
date print(fruit1)
Results
{‘banana’, ‘rambutan’, ‘apple’, ‘pineapple’,
‘durian’, ‘papaya’}
fruit1 = {"apple","banana","banana",
"rambutan","durian","pineapple","papaya"
}
fruit2 = {"banana","rambutan",
"durian","pineapple","banana"}
fruit3 = {"rambutan","banana"}
fruit1.intersection_update(fruit2,fruit3)
print(fruit1)
Result of each computation will be the
same, as follows:
{'rambutan', 'banana'}
Functions Used in Sets for Python
Function Description Example
isdisjoint() Find the same fruit1 = {"apple","banana","banana",
value between "rambutan","durian","pineapple","papaya"
two sets. If there
}
is none, return
fruit2 = {"apple","mango","banana",
true, if not, false.
"rambutan","durian","pineapple","papaya"
}
print(fruit1.isdisjoint(fruit2))]
Results
False
print(fruit2.issubset(fruit1))
Results
True
issuperset() check whether fruit1 = {"apple","banana","banana",
the first set is a "rambutan","durian","pineapple","papaya"
superset of the
}
second. If yes,
fruit2 = {"banana","banana","rambutan",
return true, if not
then false. "durian","pineapple"}
print(fruit1.issuperset(fruit2))
Functions Used in Sets for Python
Function Description Example
Results
True
print(fruit2.issuperset(fruit1))
Results
False
pop() Removes a value fruit1 = {"apple","banana","banana",
from the set. "rambutan","durian","pineapple","papaya"
(Random)
}
fruit1.pop()
print(fruit1)
Results
{‘pineapple’, ‘banana’, ‘banana’,
‘rambutan’, ‘apple’, ‘papaya’}
Results
{‘papaya’, ‘durian’, ‘banana’, ‘pineapple’,
strawberry’, ‘banana’, ‘rambutan’, ‘apple’,
‘mango’}
Tuples
Tuples in python are used to store multiple items ordered under a single variable. It is
unchangeable, but does allow duplicates. To write tuples, use Syntax 3-8.
Syntax 3-8: Create Tuples
Example
fruit = ("apple","banana","cherry","orange","mango","banana",
"rambutan","durian","pineapple", "papaya")
print(fruit)
Results
(‘apple’, ‘banana’, ‘cherry’, ‘orange’, ‘mango’, ‘banana’, ‘rambutan’, ‘durian’,
‘pineapple’, ‘papaya’)
With duplicates:
fruit = ("apple", "banana","cherry","orange","mango","banana",
"rambutan","durian","pineapple","papaya", "papaya")
print(fruit)
Results
(‘apple’, ‘banana’, ‘cherry’, ‘orange’, ‘mango’, ‘banana’, ‘rambutan’, ‘durian’,
‘pineapple’, ‘papaya’)
Therefore, when using len() to count the number of items, all items will be counted.
print(len(fruit))
Results
11
There are two different data types to keep a variable as a single item. These are:
Case 1
As a tuple
Tourist = ("Jame",)
print(type(Tourist))
Results
<class 'tuple'>
Case 2
As a String
Tourist = ("Jame")
print(type(Tourist))
For functions, refer to Table 3-4.
Table 3-4: Functions Used in Tuples for Python
Functions Used in Tuples for Python
Functio Descriptio Example
n n
count() Count the fruit = ("apple","banana",
instances of "cherry","orange",
the "mango","banana",
bracketed "rambutan","durian",
value in the
"pineapple","papaya","papaya")
tuple.
print(fruit.count("papaya"))
Results
2
index() Find the first fruit =
indexed ("apple","banana","cherry","orange",
location of
"mango","banana","rambutan","durian
the
", "pineapple","papaya","papaya")
bracketed
value in the print(fruit.index("papaya"))
tuple, Results
Starting 9
from 0. fruit = ("apple","banana",
"cherry","orange",
"mango", "banana",
"rambutan","durian",
"pineapple","papaya","papaya")
print(fruit.index( "apple"))
Results
0
P
ython has the following operators:
● Arithmetic operators
● Comparison operators
● Logical operators
● Identity operators
● Membership operators
● Bitwise operators
● Assignment operators
Arithmetic Operators
Used in basic calculations, Table 4-1 contains all the arithmetic operators
used by Python.
x=8
y=8
print(x >= y)
Results
True
<= lesser or equal to x=8
y=3
print(x <= y)
Results
False
x=8
y=8
print(x <= y)
Results
True
Logical Operators
Logical operators combine two conditional propositions. They return true or
false under the following tables:
For AND operators, use Table 4-5.
Table 4-5: AND Truth Table
AND Truth Table
p q p and q
True True True
True False False
False True False
False False False
For OR operators, use Table 4-6.
Table 4-6: OR Truth Table
OR Truth Table
p q p or q
True True True
True False True
False True True
False False False
Note: Statements are either true or false, where symbol p Represents the
first proposition or sq represents the second.
For example:
a=5
b=6
p proposes a<b, which is True
q proposes a=b, which is False
Considering the table,
p and q, True and False, Result is False
p or q , True and False, Result is True
not p, not True, result is False
Examples in Table 4-9.
Table 4-9: Logical Operators
Logical operators
Logical Example
Operator
and x=8
y=3
print(x == y and x>y)
Results
False
x==y is false
x>y is True
When checking the AND Truth Table,
Result is False.
or x=8
y=3
print(x == y or x>y)
Results
True
x==y is false
x>y is True
When checking the OR Truth Table,
Result is True.
Logical operators
Logical Example
Operator
not x=8
y=3
print(not(x == y or x>y))
Results
False
x==y is false
x>y is True
When checking the OR Table, Result is
True,
adding not, result is False.
x==y is false
x>y is True
When checking the And Table, Result is
False
adding not, result is True.
Identity operators
Identity operators as shown in Table 4-10.
Table 4-10: Identity Operators
Identity Operators
Identity operator Example
Identity Operators
Identity operator Example
is x=8
y=3
print(x is y)
Results
False
x=8
y=8
print(x is y)
Results
True
x=8
y = "8"
print(x is y)
Results
False
Identity Operators
Identity operator Example
is not x=8
y=3
print(x is not y)
Results
True
x=8
y=8
print(x is not y)
Results
False
x=8
y = "8"
print(x is not y)
Results
True
Membership operators
Membership operators as shown in Table 4-11.
Table 4-11: Membership Operators
Membership Operators
Membership Meaning Example
operator
Membership Operators
Membership Meaning Example
operator
in is a member of fruit =
["strawberry",
"mango",
"banana"]
print("banana" in
fruit)
Results
True
print("papaya" in
fruit)
Results
False
not in is not a member fruit =
of ["strawberry",
"mango",
"banana"]
print("banana" not
in fruit)
Results
False
print("papaya" not
in fruit)
Results
True
Bitwise operators
Bitwise operators as shown in Table 4-12.
Table 4-12: Bitwise Operators
Bitwise Operators
Bitwise Meaning Example
operator
& And (for bits), that x=8
is, Converting both y=3
values in the logical print(x & y)
operator into bits Results
(binary) before
0
performing said
This will compare each
logical operator for
of the 16 digits, one by
each digit.
one, using the AND
truth table, where 0 is
false and 1 is true.
8 in binary is
0000000000001000
3 in binary is
0000000000000011
Using the AND logic
operator for each bit:
0000000000001000
0000000000000011
---------------------------
0000000000000000
Therefore, result is
Results
0
Bitwise Operators
Bitwise Meaning Example
operator
| Or (for bits), that is, x=8
Converting both y=3
values in the logic print(x | y)
operator into bits Results
(binary) before
11
performing said
logical operator for
each digit. This will compare each
of the 16 digits, one by
one, using the OR truth
table, where 0 is false
and 1 is true.
8 in binary is
0000000000001000
3 in binary is
0000000000000011
Using the OR logic
operator for each bit:
0000000000001000
0000000000000011
---------------------------
0000000000001011
Therefore, result is
Results
11
^ Xor (for bits), that x = 5
is, Converting both y = 6
values in the logic print(x^y)
operator into bits Results
(binary) before
3
performing said
logical Bitwise
operatorOperators
for
Bitwise each digit.
Meaning Example
operator
This will compare each
of the 16 digits, one by
one, using the XOR
truth table, where 0 is
false and 1 is true.
5 in binary is
0000000000000101
6 in binary is
0000000000000110
Using the XOR logic
operator for each bit:
0000000000000101
0000000000000110
---------------------------
0000000000000011
Therefore, result is
Results
3
Assignment operators
Assignment operators as shown in Table 4-13.
Table 4-13: Assignment Operators
Assignment Operators
Assignment Example Equivalent Result
= x=7 x=7
+= x+=7 x=x+7
-= x-=7 x=x-7
*= x*=7 x=x*7
/= x/=7 x=x/7
//= x//=7 x=x//7
**= x**=7 x=x**7
%= x%=7 x=x%7
&= x&=7 x=x&7
|= x|=7 x=x|7
^= x^=7 x=x^7
>>= x>>=7 x=x>>7
<<= x<<=7 x=x<<7
Assignment Examples
num=0
num +=1
print(num)
Results
1
num=0
num +=50
print(num)
Results
50
Deduct values
num=0
num -=50
Results
-50
display the variable using f-String
num=0
num -=50
Logic = True
print(f"num is {num} Logic is {Logic}")
Results
num is -50 Logic is True
Exercises
W
hen writing a conditional statement, The program checks whether
the statement is true or false. If true, it executes 1.1, then 1.2 (if
available) then 1.3 (if available) until all commands are executed. if
false, it executes 2.1, then 2.2 (if available) then 2.3 (If available) until all
commands are executed. In python, there are additional statements that help
us write conditional statements, namely elif with...as and pass accordingly.
Conditional statements in python are as follows:
if..else
while..loop
for..loop
elif
Commands that make writing conditional statements more convenient are:
with...as, continue and pass
if
An if statement has the following syntax:
Syntax 5-1: if statement
if..else
An if..else statement has the following syntax:
Syntax 5-2: if..else statement
Programming conditional statements is easier if you organize your thoughts
with a flow chart, which is useful for debugging and software testers
checking if the program is running properly. Symbols used in drawing Flow
Charts are as Table 5-1.
Table 5-1: Symbols for Flow Chart
Example Program
Programming to find BMI values and display results begins with
designing and drawing a flow chart before coding the program, shown as
Figure 5-1.
Figure 5-1: Flow Chart for finding BMI values and displaying results.
To calculate the BMI value and know whether the result is over,
under or normal weight, write a program using additional conditions of
BMI table values to find the result, that is, using if or else, which after if
must be a condition that gives the result TRUE or FALSE (FALSE) and
when the result is true, it will do command 1 and if it is false, it will do
command 2 as follows.
Weight_kg = float(input('Your Weight(Kg) is '))
Height_m = float(input('Your Height(M) is '))
BMI = round(float(Weight_kg/Height_m**2),2)
if BMI > 22.9:
print("You are overweight")
Results
Your Weight(Kg) is 60
Your Height(M)is 1.4
You are overweight
Weight_kg = float(input('Your Weight(Kg) is '))
Height_m = float(input('Your Height(M) is '))
BMI = round(float(Weight_kg/Height_m**2),2)
if BMI > 22.9:
print("You are overweight")
else: print("You are normal or underweight")
Results
Your Weight(Kg) is 40
Your Height(M)is 1.60
You are normal or underweight
if..elif..else
In the case of overlapping conditions, an if..elif..else command has the
following syntax:
Syntax 5-3: if..elif..else statement
Commands can be programmed as if_else as well.
Weight_kg = float(input('Your Weight(Kg) is '))
Height_m = float(input('Your Height(M) is '))
BMI = round(float(Weight_kg/Height_m**2),2)
if BMI > 22.9:
print("You are overweight")
elif BMI < 18.5:
print("You are underweight")
else:
print("You are normal weight")
Results
Your Weight(Kg) is 50
Your Height(M)is 1.5
You are normal weight
Results
Your Weight(Kg) is 60
Your Height(M)is 1.4
You are overweight
Results
Your Weight(Kg) is 40
Your Height(M)is 1.60
You are underweight
You can also write the program as nested if_else chains. For example, if
condition 1 is this:
if BMI < 18.5:
print("You are underweight")
else:
print("You are normal")
Therefore, you can write the BMI calculation program in this manner:
Weight_kg = float(input('Your Weight(Kg) is '))
Height_m = float(input('Your Height(M) is '))
BMI = round(float(Weight_kg/Height_m**2),2)
if BMI < 22.9:
if BMI < 18.5:
print("You are underweight")
else:
print("You are normal")
else:
print("You are overweight")
Results
Your Weight(Kg) is 50
Your Height(M)is 1.5
You are normal weight
Your Weight(Kg) is 60
Your Height(M)is 1.4
You are overweight
Your Weight(Kg) is 40
Your Height(M)is 1.60
You are underweight
while..loop
The syntax of the while..loop conditional statement has the following
syntax:
Syntax 5-4: while..loop statement
fruit =
list(("orange","mango","banana","rambutan","durian","pineapple","papaya"
))
i=0
j = len(fruit)
while i < j:
print(fruit[i])
if (fruit[i] == "durian"):
print("position of durian is "+str(i))
break
i += 1
Results
orange
mango
banana
rambutan
durian
position of durian is 4
with…as
with...as is a command that is similar to defining a variable with a different
way to code, but yields the same results. Examples of its use could be found
in Chapter 11: with…as.
continue
Or if you want to show all the items in the list along with a certain item’s
position, you can use continue, but remember to use break to not go
beyond the total values in the list, which can cause errors in the display.
We can use break and continue during the process if there is a condition
that requires break and continue. The syntax of the while..loop with break
and continue as shown in Syntax 5-6
fruit =
list(("orange","mango","banana","rambutan","durian","pineapple","papaya"
))
i=0
j = len(fruit)
while i < j:
print(fruit[i])
i += 1
if (i == j): break
if (fruit[i] == "durian"):
print("Location of Durian is "+str(i))
continue
Result
orange
mango
banana
rambutan
Location of Durian is 4
durian
pineapple
papaya
while..else
We can use else during the process if there is a condition that requires else.
With this, after completing the designated number of loops, will execute
commands after else.The syntax of the while with else, as shown in Syntax
5-7:
for..loop
The syntax of for..loop is as follows:
Syntax 5-8: for..loop statement
For if…else
Example A
m=2
n=m=2
n = 33
if m > n:
print("m>n")
print("m is more n")
print("results as stated")
Results orange
results as stated
Example B
m=2
n = 33
if m > n:
print("m>n")
print("m is more n")
print("results as stated")
Results
m is more than n
results as stated
Because in example A, print("m is more n") is within if, whereas
example B has print("m is more n") outside if.
For while..loop
Example A
i=0
while i < 11:
i += 1
print(i)
Results
1
2
3
4
5
6
7
8
9
10
11
Example B
i=0
while i < 11:
i += 1
print(i)
Results
11
Because in example A, print(n) is within while, whereas example B has
print(n) outside while.
For for..loop
Example A
fruit =
list(("orange","mango","banana","rambutan","durian","pineapple","papaya"
))
p=0
for n in fruit:
if n == "mango":
continue
print(n)
Results
orange
mango
banana
rambutan
durian
pineapple
papaya
Example B
fruit =
list(("orange","mango","banana","rambutan","durian","pineapple","papaya"
))
p=0
for n in fruit:
if n == "mango":
continue
print(n)
Results
papaya
Because in example A, print(n) is within for, whereas example B has
print(n) outside for.
elif
e lif checks if the condition preceding if is not true, executes elif
commands instead.
Example
num1 = 2
num2 = 10
if num2>num1:
print("num2 is more than num1")
elif num1 == num2:
print("num2 is equal to num 1")
else:
print("num1 is more than num2")
Results num2 is more than num1
pass
pass check if the condition is true, will not display anything.
Example
num1 = 2
num2 = 10
if num2>num1:
pass
elif num1 == num2:
print("num2 is equal to num 1")
else:
print("num1 is more than num2")
Results
Nothing is displayed
Exercises
C
reating a function for Python is creating a block of program code that
runs when it is called and can pass data called parameters into the
function. The function can return data as a result.
define function
The following is the syntax for defining a function in Python:
Syntax 6-1: defining a function
Where parameter1,…,parameterN are arguments. Whether
arguments are present or not depends on whether perimeters are needed.
calling a function
To call a function, use the following syntax:
Syntax 6-2: calling a function
Where value1,…,valueM are arguments. Whether arguments are present or
not depends on whether perimeters are needed to execute that function.
Results
favoriteFruit("apple")
Results
favoriteFruit("orange")
Results
def favoriteFruit(fName,fFruit):
favoriteFruit(“Som”,"orange")
Results
favoriteFruit("Sansuay","mango")
Results
The fruit Sansuay likes most is mango
The fruits that Sansuay Sakunsaendeengam likes most are orange banana
mangowatermelon
defining a function with default values to parameters
The following is the syntax for defining a function with default
values to parameters in Python:
Syntax 6-5: defining a function with default values to parameters
Example Program
def favoriteFruit(fName="Sansuay",lName
="Sakunsaedeengam",fFruit="orange"):
print("The fruit that "+fName+" "+lName+" likes is
"+fFruit)
favoriteFruit(fName ="Ma",lName
="Boonlaimakmay",fFruit="papaya")
favoriteFruit()
Results
The fruit that Ma Boonlaimakmay likes is papaya
The fruit that Sansuay Sakunsaedeengam likes is orange
Results
The input value is 20
The return value is 200
The input value is 5
The return value is 50
The input value is 34
The return value is 340
Using the returned value as a variable can be done as follows:
Example Program
def my_function(n):
print(“The input value is “+str(n))
return “The return value is “+str(10 * n)
m = my_function(20)
print(m)
Results
The input value is 20
The return value is 200
Example Program
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
n=5
print("Factorial value of", n, "is", factorial(n))
Results
Example Program
sawasdee = lambda : print("Hi")
sawasdee()
Results
Hi
sawasdee = lambda name: print("Hi "+name)
sawasdee("Sansuay")
Results
Hi Sansuay
add5 = lambda n : n + 5
print(add5(5))
Results
10
multi = lambda n,m : n * m
print(multi(5,6))
Results
30
defining a function with return value of the lambda function
The following is the syntax for defining a function with return value
of the lambda function in Python:
Syntax 6-8: defining a function with return value of the lambda function
The lambda command can use function parameters as demonstrated in the
following
Example programs
def funcandlambda(n):
return lambda m : m * n
callfunclamb = funcandlambda(10)
print(callfunclamb(50))
Results
500
Finding exponents
def powerVal(n):
return lambda m : m ** n
power2 = powerVal(2)
power3 = powerVal(3)
print(power2(5))
print(power3(5))
Results
25
125
def funcandlambda(n,q=5):
q=4
n=6
return lambda m : m * n * q
callfunclamb = funcandlambda(10)
print(callfunclamb(50))
Results
1200
def funcandlambda(n,q=5):
q=4
n=6
return lambda m,p : m * n * q * p
callfunclamb = funcandlambda(10)
print(callfunclamb(50,10))
Results
12000
Exercises
1. Create a function called sumX to get the values of 5 variables and
sum them up and display the result.
2. Create a lambda function to take the values of 5 variables and
combine them and display a result.
CHAPTER 7 MODULES
T
o create a module, go to https://replit.com/ which lets you write Python code
through a browser.Once there, you will find a previously created module
called “main.py”. Let’s create a new file and name a new .py module with the
following syntax:
create module
Syntax 7-1: create python file
using module
By naming our module my_module.py, we will get a module named my_module.
When we want to use it, use the following syntax:
Syntax 7-2: use a module
Example Program
Add a dictionary to the my_module module:
Tourist_gender =
{'Ammy':'Female','Jame':'Male','Mike':'Male',
'Minnie':'Female'}
Then, run my_module and call this function as follows:
import my_module
print(my_module.Tourist_gender['Jame'])
Results
Male
rename module
To rename the module, use the following syntax:
Syntax 7-6: rename a module
Once the name is changed, the new module name must be used throughout.
Example Program
import my_module as mm
print(mm.Tourist_gender['Jame'])
Results
Male
Python has built-in modules that can be viewed at
https://docs.python.org/3/py-modindex.html
using random module
To use the random module to randomly pick an integer value between 1 to 10,
import random and write the program as follows:
import random
random_int = random.randint(1,10)
print(random_int)
When run, it displays a random value between 1 to 10.
First executed result could be:
2
Second executed result could be:
4
python has created a Python Random Module that has functions that can be
used without having to write a new program. You can go see more at:
https://docs.python.org/3/library/random.html
Frequently Python Random Module is shown in Table 7-1
Table 7-1: Frequently Used Functions of Random Module Provided by Python
Frequently Used Functions of Random Module Provided by Python
Functio Description Example
n
seed() Generate a To generate a random number with 8 as the
random number seed value with random.seed(8), it will always
based on the return 0.2267058593810488 as the same
bracketed seed random number
value. Will always Example
return the same import random
random number. random.seed(8)
print(random.random())
Results
0.2267058593810488
Frequently Used Functions of Random Module Provided by Python
Functio Description Example
n
randint() Returns a random To get a random integer
number between value between 50 and 60:
the given range, import random
including the
given integers. print(random.randint(50, 60))
Results
52
print(random.randint(50, 60))
Results
59
randran Returns a random To get a random integer value between 50 and
ge() number between 59:
the given range, import random
including the first
integer but not the print(random.randrange(50, 60))
last. Results
52
print(random.randrange(50, 60))
Results
59
choice() Returns a random To return 1 random element from the fruit list:
element from the import random
given list (see
chapter 3) fruit =
["orange","mango","banana","rambutan","duria
n",
"pineapple","papaya"]
print(random.choice(fruit))
Results
pineapple
Frequently Used Functions of Random Module Provided by Python
Functio Description Example
n
sample() Returns a given To return a sample of 3 random elements from
sample of a list the fruit list:
(see chapter 3)
import random
fruit =
["orange","mango","banana","rambutan","duria
n",
"pineapple","papaya"]
print(random.sample(fruit,3))
Results
['mango', 'rambutan', 'orange']
To use generate a random integer value between 1 and 10, navigate the menu to
randint() as shown:
or scan QR Code
Exercises
P
ython string formatting is a method that lets programmers make sure
the string will display variables as expected, using the following
syntax:
Syntax 8-1: String formatting for Strings
Example
animal1 = 'lions'
zoo = "There are {} at The Beauty Zoo."
print(zoo.format(animal1))
Results
There are lions at The Beauty Zoo.
If the variable to be displayed in the string has the decimal value
to be displayed. The programmer can specify using the following syntax:
Syntax 8-2: String format for decimal values
Example
foodPrice1 = 199.50
zoo = "Beauty Zoo sells animal feed for {:.2f} THB per bag."
print(zoo.format(foodPrice1))
Results
Beauty Zoo sells animal feed for 199.50 THB per bag.
For multiple variables to display in a string, use the following
syntax:
Syntax 8-3: format to display multiple values inside a string
Example
animal1 = 'lion'
foodPrice1 = 199.50
animal2 = 'fish'
foodPrice2 = 19.50
zoo = "Beauty Zoo sells {} feed for {:.2f} THB per bag and {} feed for
{:.2f} THB per bag."
print(zoo.format(animal1,foodPrice1,animal2,foodPrice2))
Results
Beauty Zoo sells lion feed for 199.50 THB per bag and fish feed for 19.50
THB per bag.
Example
animal1 = 'lion'
foodPrice1 = 199.50
animal2 = 'fish'
foodPrice2 = 19.50
zoo = "Beauty Zoo sells {0} feed for {1:.2f} THB per bag and {2} feed for
{3:.2f} THB per bag. The {0} feeding time is from 10am to 3pm, while the
{2} feeding time is from 9am to 4pm."
print(zoo.format(animal1,foodPrice1,animal2,foodPrice2))
Results
Beauty Zoo sells lion feed for 199.50 THB per bag and fish feed for 19.50
THB per bag. The lion feeding time is from 10am to 3pm, while the fish
feeding time is from 9am to 4pm.
Alternatively, you may use the following syntax:
Syntax 8-4: format with variables inside the string
Example
zoo = "Beauty Zoo sells {animal1} feed for {foodprice1:.2f} THB per bag
and {animal2} feed for {foodprice2:.2f} THB per bag. The {animal1}
feeding time is from 10am to 3pm, while the {animal2} feeding time is
from 9am to 4pm."
print(zoo.format(animal1= 'lion',foodPrice1 = 199.50,animal2 = 'fish',
foodPrice2= 19.50))
Results
Beauty Zoo sells lion feed for 199.50 THB per bag and fish feed for 19.50
THB per bag. The lion feeding time is from 10am to 3pm, while the fish
feeding time is from 9am to 4pm.
Exercises
O
bject-Oriented Programming, discovered in 1960, is a method of
writing code to be consistent with the analysis and design of real-
world object-oriented systems by creating abstract Classes and
creating identifiable Objects within those classes. You can then change the
state of the class according to the environment with a State Chart Diagram,
create relationships between classes with a Class Diagram, show details of
the relationship between classes or objects in Sequence Diagrams or
Collaboration Diagrams and show work steps in an Activity Diagram to
visualize how the whole system works before coding a program. System
design analysts will make these diagrams to review the understanding of the
system and use it as a summary before bringing it to the programmer to
write a program, as well as use them to check the programmer's work
before delivering it to the user. Since object-oriented programming is also
compatible with C++, Java, Smalltalk, Delphi, C#, Perl, Python, Ruby, and
PHP, using object-oriented programming in Python will be helpful for
coders in making programs consistent with system design analysis using
object-oriented principles. More importantly, object-oriented language
programmers must be able to understand the diagrams mentioned above.
For more information refer to the Advanced Python manual.
Create Class and Object
Class is the classification of things: types of animals, organizational
positions, tools, equipment, machinery, furniture etc. When creating classes,
create only ones we will use. For example, if we are going to create a
system for a zoo, we must create animal-related classes, such as animals,
pens, cages, feed, staff, etc. to be used in the system. As programmers, we
must understand the diagrams, and if we are acting as both programmers
and system analysts, we need to create diagrams to easily communicate to
users.By using Unified Modeling Language(UML) class diagrams, it is a
standard that ensures every programmer understands how to code object-
oriented programs according to the user’s needs. Therefore, we should use
language in diagrams that is easy to understand. Creating a class consists of
three parts,as shown in Figure 9-1.
This class diagram shows a parent and its children, where the parent
is the Animal class. The base of the is divided into 2 child classes:
LandAnimal and AquaticAnimal, which contain the same attributes in the
Animal class, while different methods and attributes are that the child class,
i.e. land animals having number of legs and top running speed, whereas
aquatic animals have number of fins and top swimming speed.
To program Parent/Child classes in Python, Using only its parent's attributes
and methods, without defining attributes and method for the child class, use
the following syntax:
Syntax 9-4: Creating a child class in python
Create an and object of child class in python with the following syntax:
Syntax 9-5: Creating an object in a child class in python
Example
class LandAnimal(Animal):
pass
LA1 = LandAnimal("Sudsuay","lion", "3", "female")
print(LA1)
Results
A 3 year-old female lion named Sudsuay.
To add attributes or methods to a Child ,use the following syntax:
Syntax 9-6: Adding attributes or methods to a child class
Example
class LandAnimal(Animal):
def __init__(do,name,type, age, gender,noOfLeg,runSpeed):
do.noOfLeg = noOfLeg
do.runSpeed = runSpeed
Animal.__init__(do,name,type, age, gender)
LA1 = LandAAnimal("Sudsuay","lion", "3", "female", "4", "74")
print(LA1)
def intro(do):
print('A land animal '+'with '+LA1.noOfLeg+' legs'+' and a top speed
of ' —--+LA1.runSpeed+' km/h')
LA1 = LandAnimal("Sudsuay","lion", "3", "female", "4", "74")
LA1.intro()
Results
A 3 year-old female lion named Sudsuay.
A land animal with 4 legs and a top speed of 74 km/h
Overrides
To Override an Attribute or Method of a parent class with one in
a child class, you use an Attribute or Method with the same name as the
parent class. For example:
class LandAnimal(Animal):
def __init__(do,name,type, age, gender,noOfLeg,runSpeed):
Animal.__init__(do,name,type, age, gender)
do.noOfLeg = noOfLeg
do.runSpeed = runSpeed
do.type = 'land animal, the '+type
def __str__(do):
return f"A {do.age} year-old {do.gender} {do.type} named {do.name}
has —--{do.noOfLegs} legs and a top speed of {do.runSpeed} km/h.”
LA1 = LandAnimal("Sudsuay","lion", "3", "female", "4", "74")
print(LA1)
This overrides the attribute of the parent class: type.This also overrides the
method of the parent class: def __str__(do)
Results
A 3 year-old female land animal, the lion named Sudsuay has 4 legs and a
top speed of 74 km/h.
Polymorphism
olymorphisms, meaning “many forms,” allows coders to
P
program and manage data types and function using a single interface. For
example, A Tourist's GPA can have multiple statuses, such as “normal”
with a GPA of not less than 2.00, “Under probation” with a GPA under
2.00, or “dropped” with a GPA below 1.50. Thus, creating the Tourist class
that changes according to their context and impacts execution. This in turn
lets us overload methods, meaning create a method with the same name but
behaves differently depending on the input data. An easy example of this in
Python are methods that are not class-based for programmers, such as using
the '+'.
int1 = 22
int2 = 145
float1 = 19.1
str1 = "hi
str2 = "Python"
print(int1 + int2)
print(type(int1 + int2))
print(float1 + float1)
print(type (float1 + float1))
print(str1 + str2)
print(type(str1 + str2))
Results
167
<class 'int'>
38.2
<class 'float'>
hiPython
<class 'str'>
or len()
str = 'Fruits starting with M'
fruit = ('Mango','Mangosteen','Melon','Mandarin')
fruit_list = ['Mango','Mangosteen','Melon','Mandarin']
fruit_dict = {'1':'Mango','2':'Mangosteen','3':'Melon','4':'Mandarin'}
print(len(str))
print(len(fruit))
print(len(fruit_list))
print(len(fruit_dict))
Results
21
4
4
4
Despite using the same len() method, Different values could be found
depending on the type of data inputted.
For example, when animals of different ages receive different types of feed,
such as lions over one years old be fed meat instead of milk, do as follows:
def eat(animal):
if animal.age>=1:
print(animal.name+ 'is over one years old and must be fed meat.')
else :
print(animal.name+ ''is less than a year old and must be fed milk.')
LA1 = LandAnimal("Sandsuay","lion", 4, "wife", "4", "74")
LA1.eat()
Results
Sandsuay is over one years old and must be fed meat.
Example: polymorphism of multiple classes using a method with the same
name.
class Cat:
def __hot__(do, name, moveSpeed):
do.name = name
do.moveSpeed = moveSpeed
def move(animal):
print("The "+animal.name+" runs at a speed of "+animal.moveSpeed)
class Fish:
def __hot__(do, name, moveSpeed):
do.name = name
do.moveSpeed = moveSpeed
def move(animal):
print("The "+animal.name+" swims at a speed of "+animal.moveSpeed)
class Bird:
def __hot__(do, name, moveSpeed):
do.name = name
do.moveSpeed = moveSpeed
def move(animal):
print("The "+animal.name+" flies at a speed of"+animal.moveSpeed)
tiger1 = Cat("leopard", "60 kilometers per hour")
bird1 = Bird("parrot", "5 kilometers per hour")
fish1 = Fish("Goby", "20 kilometers per hour")
for x in (tiger1, bird1, fish1):
x.move()
Results
The Leopard runs at a speed of 60 kilometers per hour.
The parrot flies at a speed of 5 kilometers per hour.
The goby swims at a speed of 20 kilometers per hour.
Inheriting Multiple Classes
Multi-class inheritance is when multiple parent classes are
inherited to a child class, as shown in Figure 9-4:
Figure 9-4: UML representation an inheritance relationship with multiple classes.
Example
Diagram of animals in the zoo to show how lions are land animals and
mammals.
Figure 9-5: Class diagram of animals in the zoo that show an inheritance
relationship with multiple classes.
The syntax used to program Python child classes that have multiple
parents.
o create a child class that have multiple parents, using the
T
following syntax:
Syntax 9-7: Create a child class that have multiple parent classes in python
Example program:
class Animal:
place = 'Beauty Zoo'
def __init__(do,name,type, age, gender):
do.name = name
do.type = type
do.age = age
do.gender = gender
def __str__(do):
return f"A {do.age} year-old {do.gender} {do.type} named {do.name}"
def eat(animal):
if animal.age>=1:
print(animal.name+ ' is over one years old and must be fed meat.')
else :
print(animal.name+ ' is less than a year old and must be fed milk.')
def sleep(animal):
print(animal.name+" is sleeping.")
A1 = Animal("Rashun","lion", 3, "female")
print('At '+A1.place+' are these animals:')
print(A1)
A1.eat()
A1.sleep()
class LandAnimal(Animal):
def __init__(do,name,type, age, gender,noOfLeg,runSpeed):
Animal.__init__(do,name,type, age, gender)
do.noOfLeg = noOfLeg
do.runSpeed = runSpeed
do.type = type+', a land animal'
do.legFin = 'legs,'
do.moveMethod = 'and runs with a top speed of'
def __str__(do):
return f"A {do.age} year-old {do.gender} {do.type} named {do.name}
has {do.noOfLeg} {do.legFin} {do.moveMethod} {do.runSpeed} km/h. "
def run(landAnimal):
print(landAnimal.name+" is running at the top speed of "
+landAnimal.runSpeed+' km/h.')
LA1 = LandAnimal("Sudsuay","lion", 4, "female", "4", "74")
LA1.run()
print(LA1)
class AquaticAnimal(Animal):
def __init__(do,name,type, age, gender,noOfFin,swimSpeed):
Animal.__init__(do,name,type, age, gender)
do.noOfFin = noOfFin
do.swimSpeed = swimSpeed
do.type = type+', an aquatic animal'
do.legFin = 'fins,'
do.moveMethod = 'and swims with a top speed of'
def __str__(do):
return f"A {do.age} year-old {do.gender} {do.type} named {do.name}
has {do.noOfFin} {do.legFin} {do.moveMethod} {do.swimSpeed} km/h. "
def swim(AquaticAnimal):
print(AquaticAnimal.name+" is swimming at a top speed of "
+AquaticAnimal.swimSpeed+' km/h')
AA1 = AquaticAnimal("Bee","goby", 2, "male", "5", "23")
print(AA1)
AA1.swim()
class Mammal(AquaticAnimal,LandAnimal):
def __init__(do,name,type, age,
gender,noOfFin,swimSpeed,noOfLeg,runSpeed):
AquaticAnimal.__init__(do,name,type, age,
gender,noOfFin,swimSpeed)
LandAnimal.__init__(do,name,type, age, gender,noOfLeg,runSpeed)
do.type = type+', a mammal'
def __str__(do):
return f"A {do.age} year-old {do.gender} {do.type} named
{do.name}."
def feedMilk(mammal):
print(mammal.name+" is breastfeeding.")
M1 = Mammal("BB","Dolphin", 2, "female", "5", "0", "0", "0")
print(M1)
M1.feedMilk()
Results
At Beauty Zoo are these animalsL
A 3 year-old female lion named Rashun.
Rashun is over one years old and must be fed meat.
Rashun is sleeping.
Sudsuay is running at the top speed of 74 km/h.
A 4 year-old female lion, a land animal named Sudsuay has 4 legs, and runs
with a top speed of 74 km/h.
A 2 year-old male goby, an aquatic animal named Bee has 5 fins, and swims
with a top speed of 23 km/h.
Bee is swimming at a top speed of 23 km/h.
A 2 year-old female Dolphin, a mammal named BB.
BB is breastfeeding.
Association
Association is when a class is related to another class, such as the
driver class being associated with a car class. To create associations, use the
following Diagram:
Aggregation
Aggregation is when a class has other classes join in, and will
remain even if the joined classes no longer exist. For example, the
“Company” class has aggregated “department” classes inside. Diagram as
shown:
Figure 9-7: UML representation an aggregation relationship.
Composition
ompositions are classes composed by the classes, such as the
C
‘Cars’ class is composed of wheels, doors, roofs, seats, etc., i.e. its
components. diagram as shown:
Examples
Figure 9-9: Class diagram of animals in the zoo with an association relationship.
Example Program
class Animal:
place = 'Beauty Zoo'
def __init__(do,name,type, age, gender):
do.name = name
do.type = type
do.age = age
do.gender = gender
def __str__(do):
return f"A {do.age} year-old {do.gender} {do.type} named {do.name}."
def eat(animal):
if animal.age>=1:
print(animal.name+ ' is over one years old and must be fed meat.')
else :
print(animal.name+ ' is less than a year old and must be fed milk.')
def sleep(animal):
print(animal.name+" is sleeping.")
class Habitat():
def __init__(do, location, width, length):
do.location = location
do.width = width
do.length = length
def __str__(do):
return f"{'Located '+do.location+', the enclosure is '+str(do.width)+'
meters wide and '+str(do.length)+' meters long.'}"
def animalStay(do, animal):
print(animal+' is located '+do.location+'. The enclosure has an area of
'+str(do.width * do.length)+' meters squared.')
Habitat1 = Habitat("across the pool", 2, 6)
print(Habitat1)
A1 = Animal("Rashun","Lion", 3, "Female")
print(A1)
Habitat1.animalStay(A1.name)
Results
Located across the pool, the enclosure is 2 meters wide and 6 meters long.
A 3 year-old Female Lion named Rashun.
Rashun is located across the pool. The enclosure has an area of 12 meter
squared.
Example
diagram of a class Aggregation
Example program
class Habitat():
def __init__(do, location, width, length):
do.location = location
do.width = width
do.length = length
def __str__(do):
return f"{'Located '+do.location+', the enclosure is '+str(do.width)+'
meters wide and '+str(do.length)+' meters long.'}"
def animalStay(do, animal):
print(animal+' is located '+do.location+'. The enclosure has an area of
'+str(do.width * do.length)+' meters squared.')
class TicketOffice():
def __init__(do,location, width, length, sellerTicket):
do.location = location
do.width = width
do.length = length
do.sellerTicket = sellerTicket
def __str__(do):
return f"{'Ticket Office, staffed by '+do.sellerTicket}"
class StaffOffice():
def __init__(do,location, width, length, staffName):
do.location = location
do.width = width
do.length = length
do.staffName = staffName
def __str__(do):
return f"{'Staffed by'+do.staffName}"
class TourStore():
def __init__(do,location, width, length, seller):
do.location = location
do.width = width
do.length = length
do.seller = seller
def __str__(do):
return f"{'Staffed by'+do.seller}"
class Zoo(object):
def __init__(do, name, address,
Habitat1,Habitat2,Habitat3,Habitat4,TicketOffice,StaffOffice,TourStore):
do.name = name
do.address = address
do.Habitat1 = Habitat1
do.Habitat2 = Habitat2
do.Habitat3 = Habitat3
do.Habitat4 = Habitat4
do.TicketOffice=TicketOffice
do.StaffOffice=StaffOffice
do.TourStore=TourStore
def __str__(do):
return f"{do.name+' is located at '+do.address+'. Habitat 1 is located
'+do.Habitat1.location+'. Habitat 2 is located '+do.Habitat2.location+'.
Habitat 3 is located '+do.Habitat3.location+'. The Aquarium is located '
+do.Habitat4.location+'. The ticket office is staffed by '
+do.TicketOffice.sellerTicket+'. The staff office is staffed by '
+do.StaffOffice.staffName+'. The gift shop is staffed by '
+do.TourStore.seller}."
H1 = Habitat("across the pool", 2, 6)
H2 = Habitat("right of the entrance", 5, 6)
H3 = Habitat("right of the entrance", 5, 6)
H4 = Habitat("at the end of the pool", 2, 3)
print(H1)
T1 = TicketOffice("at the entrance", 2, 6,"Smiley Mcwelcome")
S1 = StaffOffice("end of zoo ", 2, 6,"Manny Jerial")
TS1 = TourStore("near exit door ", 3, 4,"Kassho Credit")
Z1 = Zoo("Beauty Zoo", "999, Bangkok,
Thailand",H1,H2,H3,H4,T1,S1,TS1)
print(Z1)
Results
Beauty Zoo is located at 999, Bangkok, Thailand. Habitat 1 is located
across the pool. Habitat 2 is located right of the entrance. Habitat 3 is
located right of the entrance. The Aquarium is located at the end of the
pool. The ticket office is staffed by Smiley Mcwelcome. The staff office is
staffed by Manny Jerial. The gift shop is staffed by Kassho Credit.
Example diagram of a composition
Figure 9-11: Class diagram of animals in the zoo with a composition relationship.
Example program
class Head:
def __init__(do, headSize):
do.headSize = headSize
def __str__(do):
return f"{str(do.headSize)}"
class Body:
def __init__(do, bodySize):
do.bodySize = bodySize
def __str__(do):
return f"{str(do.bodySize)}"
class Leg:
def __init__(do, legSize, position):
do.legSize = legSize
do.position = position
def __str__(do):
return f"{do.position+' '+str(do.legSize)+' cm. '}"
class LandAnimal:
def
__init__(do,headSize,bodySize,leg1Size,position1,leg2Size,position2,leg3S
ize,position3,leg4Size,position4):
do.headSize = Head(headSize)
do.bodySize = Body(bodySize)
do.leg1Size = Leg(leg1Size,position1)
do.leg2Size = Leg(leg2Size,position2)
do.leg3Size = Leg(leg3Size,position3)
do.leg4Size = Leg(leg4Size,position4)
def __str__(do):
return f"{'Head Length: '+str(do.headSize)+' cm. '+'Body Length: '
+str(do.bodySize)+' cm. '
+str(do.leg1Size)+str(do.leg2Size)+str(do.leg3Size)+str(do.leg4Size)}"
A1 = LandAnimal(80,120,60,'Front Left:',60,'Front Right:',60,'Back
Left:',60,'Back Right:')
print(A1)
print('The head is '+str(Head(A1.headSize))+' cm long.')
print('The body is '+str(Body(A1.bodySize))+' cm long.')
A2 = LandAnimal(5,8,3,'Front Left:',3,'Front Right:',0,'',0,'')
print(A2)
print('The head is '+str(Head(A2.headSize))+' cm long.')
print('The body is '+str(Body(A2.bodySize))+' cm long.')
Results
Head Length: 80 cm. Body Length: 120 cm. Front Left: 60 cm. Front Right:
60 cm. Back Left: 60 cm. Back Right: 60 cm.
The head is 80 cm long.
The body is 120 cm long.
Head Length: 5 cm. Body Length: 8 cm. Front Left: 3 cm. Front Right: 3
cm. 0 cm. 0 cm.
The head is 5 cm long.
The body is 8 cm long.
Exercises
W
hen a program is being used, there’s always a chance of
malfunction, either from users, the hardware, network, equipment or
power. This affects the operation of the program, so errors must be
pre-written as follows:
Example
while True:
try:
x = int(input("Please enter a number: "))
except ValueError:
print("Sorry, that is not a number. Please enter again...")
else :
print("We've got the numbers.")
finally :
print("Thank you very much.")
Result in the case where numbers are not entered
Please enter numbers: !
Sorry, that is not a number. Please enter again...
Thank you very much
F
ile management includes
1. Open
2. Create
3. Edit/Write
4. Delete
Open File
To open a file, use the open() function with two parameters: the
name of the file you want to open and the mode, as follows:
Mode 1: "r"– reads the specified value in the file instead of opening it. If
that file doesn’t exist, it will show an error.
Example
Create a txt file.
Type 'Test file command' and save the file name as ‘test.txt’ in the same
folder where the program is stored.
f = open("test.txt")
print(f.read())
Results
Test file command
If the file is not found
f = open("test2.txt")
print(f.read())
Results
FileNotFoundError: [Errno 2] No such file or directory: 'test2.txt'
Create
Mode 2: "a"-Appends (creates) a file.
Example
Create test2.txt file.
f = open("test2.txt","a")
A new file, test2.txt, is created.
If this file already exists, no error will be displayed.
Write File
Mode 3: "w"-Writes into a file.
Example
Write the file Sawasdee.txt
Sawasdee= open("Sawasdee.txt", "w")
Sawasdee.write("Hi, this is Thailand.\n")
Sawasdee.write("A country with delicious food,\n")
Sawasdee.write(“everyone has a smile.\n")
Sawasdee.write("A beautiful, safe place.\n")
with...as
with...as is a command that is similar to defining a variable with a
different way to code, but yields the same results.
Example 1
In case the file you want to open is in the folder
'/ExamplePythonCode/FileForPythonTest/’
f = open("/ExamplePythonCode/FileForPythonTest/Open.txt", "r")
print(f.read())
The command used to open the open.txt file is long since it is located in a
very deep folder. Therefore, to make the programmer's work easier, it can
be done by specifying it as a variable, f, which the programmer can write
using with...as.
Example 2
with open("/ExamplePythonCode/FileForPythonTest/Open.txt", "r") as The
dead one:
print(The dead one.read())
Both examples have the same effect, meaning the files can be opened in the
same way.
If the programmer wants to use a command to read each line of a file, write
the command as follows:
with open("Sawasdee2.txt") as Sawasdee3:
for line in Sawasdee3:
print(line)
Or it could be written like this:
Sawasdee= open("Sawasdee.txt")
with Sawasdee:
for line in Sawasdee:
print(line)
Results
Hi, this is Thailand.
A country with delicious food,
everyone has a smile.
A beautiful, safe place.
Create File
Mode 4: "x"-Creating a file, but if an extra file with the same name already
exists, an error will be displayed.
Example
f = open("Sawasdee.txt", "x")
Results
have file
f = open("Sawasdee.txt", "x")
Results
FileExistsError: [Errno 17] File exists: 'Sawasdee.txt'
If not there will be a file created.
Delete File
If you want to delete a file, import os and use the remove command as in
the example.
import os
os.remove("S.txt")
If the file to delete is not found, the following will be displayed:
FileNotFoundError: [Errno 2] No such file or directory: 'S.txt'
import os
os.remove("Hello3.txt")
The file named Hello3.txt will be deleted.
To create an exception, use the following:
import os
if os.path.exists("Hello3.txt"):
os.remove("Hello3.txt")
else:
print("File hello3.txt not found")
Results
The file Hello3.txt was not found.
Delete Folder
if we want to delete a folder, use the following:
import os
os.is rm("myfolder")
Results
delete folder myfolder
If this folder is not found
Results
FileNotFoundError: [Errno 2] No such file or directory: 'myfolder'
If the folder is found, it will be deleted.
JSON
JSON, short for JavaScript Object Notation, is a standard format
for representing structured data based on the JavaScript Object syntax,
typically used for sending data in web applications. (e.g. sending some data
from a server to a client so that it can be displayed on a web page or vice
versa.) Python itself has commands that can be used with JSON files, but
you must import JSON first, where specific data type in Python can be
converted to JSON as shown in the table.
Table 11-1:Python to JSON conversion table
Python JSON
dict Object
list Array
tuple Array
str String
int Number
float Number
True true
False false
None null
loads
Using the loads command to convert the person value in Python to
json, namely person2, then print to display the person2 values, and to
display only the Marriage value of person2['Marriage']
Example:
import json
person = '{"name": "Somsak", "Marriage":
true,"age":87,"Country":"Thai"}'
person2 = json.loads(person)
print( person2)
print(person2['Marriage'])
Results
{'name': 'Somsak', 'Marriage': True, 'age': 87, 'Country': 'Thai'}
True
You can also use commands to use the values in the json file, for example:
fileperson.json
{"name": "Somsak", "Marriage": true,"age":87,"Country":"Thai"
}
open
Open a json file and read the value, then create a variable that loads
the value, named data.
Example:
with open('person.json', 'r') as f:
data = json.load(f)
print(data)
Results
{'name': 'Somsak', 'Marriage': True, 'age': 87, 'Country': 'Thai'}
Human-computer interaction.
Node.js
JavaScript
Oracle
Python
HTML5
MongoDB