Module 3 - 2nd Edition
Module 3 - 2nd Edition
Module 3 - 2nd Edition
ALGORITHM &
PROGRAMMING
By :
D E P A R T M E N T O F I N D U S T R I A L E N G I N E E R I N G
I N S T I T U T T E K N O L O G I T E L K O M S U R A B A Y A
Copyright © 2019 Lab Works: Algorithm & Programming
Publisher:
Institut Teknologi Telkom Surabaya
Gayungan PTT 17-19
Surabaya, 60234
Indonesia
Phone:
E-mail:lppm@ittelkom-sby.ac.id
Website:http://ie.ittelkom-sby.ac.id
By:
Wahyu Andy Prastyabudi
Lab-work Module i
Lab-work Module ii
Preface
Steve Jobs
This book instructs you to practice, applying what you have got from the class,
and establish your coding skills. By several trivial exercises into increasingly diffi-
cult problems, bit by bit you will learn how to think, solve the given problems and
implement them into the code.
Do Not Copy-Paste!
Type each of these exercises in this workbook manually. Do not cheat yourself
by copy-paste them. The point of these exercise is to train your hands, your
brain, and your consciousness in reading and writing code. Thus, you will get
used to code.
Read the instructions in every exercise and assignment problem carefully. Try
your best to accomplish each mission. The assignment will be used as if a visa to get
in the lab work meeting. The entry shall not be granted if you can not submit the
given assignment.
By the end of the book, you will have provision to begin learning more complex
problem that you might get in other courses. Should you have any queries or ideas to
improve this document, please let me know.
Wahyu Andy P.
<wahyu.andy@ittelkom-sby.ac.id>
Industrial Engineering
ITTelkom Surabaya
Preface iii
Contents vii
1 Introduction 1
1.3 Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Flowchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Pseudocode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.6 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7 Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2 Python Primer 13
2.3 Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.3.2 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.3.3 Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.5 Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.1 Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.1.1 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.2 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.2.1 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.3.2 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.3.3 String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.3.5 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.4 Assignment 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.5.1 Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.5.2 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.6.1 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.7 Assignment 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
5 Looping 45
6 Function 47
7 Array 49
8 Multidimensional Array 51
Lab-work Module vi
9 Searching 53
10 Sorting 55
11 Recursion 57
References 59
This lab works is a companion of the same title course, Algorithm and Program-
ming. This course is composed to introduce the students to computer programming,
herein we used Python. The course’s syllabus comprises programming techniques and
Python basics. Python is chosen as its robustness and simplicity compare to other
programming languages.
On the other hand, this course will be a provision to the student in attending
courses at the following semester, such as Operation Research, Computer Simulation
and Information System Analysis and Design. Moreover, the knowledge about pro-
gramming language especially Python will be useful at work and may give added value
to the student. Whereas the demand of graduate with a reliable programming skill
and data processing is increasing as the growth of digital industry.
1. Be able to define logical steps in problem solving into algorithm scheme (e.g.
flowchart, pseudo-code)
3. Be able to implement the algorithm scheme into computer program by their own
with full of responsibility
4. Be able to demonstrate the the assignment result computer program by your own
or in groups with full of responsibility
Lab-work Module 2
Table 1.2: Flowchart symbols continued
1.3 Algorithm
There are many problems solved by algorithms. A well known search engine,
such as Google, employs sophisticated algorithm to retrieve a precise information or
data as requested by the user. An e-commerce sites are also strongly build with set
of algorithms to run their business. A manufacture often employs a linear program-
ming approach to allocate scarce resources in the most beneficial way. A port that
applies automatic guided vehicle (AGV) must implement a certain algorithm so called
dispatching rules to manage those vehicles.
1.4 Flowchart
Lab-work Module 3
Figure 1.1: You can watch a short video explaining about the algorithm at Youtube
1. Once you go to http://draw.io, you will be shown the following figure that ask
you to choose one of three options to save the diagrams: Google Drive, OneDrive,
Device. You may choose “Device” to save the diagram on your own computer.
Lab-work Module 4
2.
Then choose “Create New Diagram” afterwards. You may choose Open
Existing Diagram if you have one already.
3.
Lab-work Module 5
5. To start drawing, simply drag-drop an available shape into the drawing area or
click it. Click the shape to change its properties shown on the right side. Double
click the shape if you wish to add any text inside.
6. To draw an arrow, aim your pointer to the shape then it will show four arrows
direction. Click one of them clone a shape or draw an arrow headed to another
shape.
Lab-work Module 6
7. To change arrow properties just simply click it. If you wish to add a label double
click onto it. Drawing flowchart on other applications will be somewhat similar
in someways.
1.5 Pseudocode
Lab-work Module 7
Figure 1.2: Sample of pseudocode
1.6 Exercise
1. Draw again the flowchart as shown in Figure 1.3a and Figure 1.3b using Ms.
Visio or online tool Draw.io.
Lab-work Module 8
4. Draw your own simple process dealing with a specific problem.
1 repeat
2 OUTPUT ’What is the best subject you take?’;
3 INPUT user inputs the best subject they take;
4 STORE the user’s input in the answer variable;
5 if answer = ’Computer Science’ then
6 OUTPUT ’Of course it is!’;
7 else
8 OUTPUT ’Try again!’;
9 end
10 until answer = ’Computer Science’;
Algorithm 1: Pseudocode to find the best subject
1.7 Assignment
5. find the average grade of five subjects then decide if a student could pass whenever
the grade is more than 50 and fail otherwise.
1. Write the report in A4 paper size using 12pt Times New Roman font-face, normal
margin, and 1.3 spacing.
2. Write the pseudocode in a box or one cell table with 10pt Sans font-face.
(a) Cover
(b) Contents
(c) Introduction
(d) Theoretical Background
Lab-work Module 9
(a) Flowchart 1
(b) Flowchart 2
Lab-work Module 10
(e) Assignment & Methods
(f) Results & Discussion
(g) Conclusion
(h) References
Submit the report both in hard and soft copy by the next week prior to lab
work. You may submit the report in online class room.
Lab-work Module 11
Lab-work Module 12
Module 2: Python Primer
Figure 2.1 shows how the Python works which is quite similar to Java. Typically
a program involves a series of commands typed in a plain text file known as source
code or a script. Every programming language has their own convention for naming
the source code as well as in Python in which the file name has suffix .py (e.g. test.py).
Python Interpreter
Byte
code
Library modules
Python has been widely used in many fields, from computer science to industrial
applications. Python is one of the top 10 popular programming languages. Moreover,
as a general, multipurpose and high level programming languages, Python can be used
to develop desktop applications and web applications. Bellow are number of reason
why you should prefer to use Python than other language.
Simple syntax Python’s syntax is easy to learn, so both non-programmers and pro-
grammers can start programming right away.
Readable and maintainable Indeed, with the easy syntax you can write more read-
able code and at the same time the code quality will enhance the ease of main-
tenance jobs.
Free and cross platform Python is both free and open-source. You shall easily find
robust open source frameworks or tools to support the development. It also runs
on all major operating systems like Microsoft Windows, Linux, and Mac OS X.
2.3 Setup
Python available either in Mac, Windows, and Linux system. In this section,
yet has no code to deal with. However, you are required to setup your own computer
by installing Python 3 including the code editor. You shall find the latest release
of Python in https://www.python.org/downloads. Choose the version that suit your
machine (OS).
After finishing the setup, you should be able to see the Python version installed.
Open your terminal or command line then type py. Afterwards, the following Figure 2.2
should be appeared on your screen. If you use another OS, then the information will
be slightly different.
Lab-work Module 14
Figure 2.2: Showing Python version via terminal
• https://docs.python.org/3/using/mac.html
• https://docs.python-guide.org/starting/install3/osx
2.3.2 Windows
• https://docs.python.org/3/using/windows.html
• https://docs.python-guide.org/starting/install3/win
2.3.3 Linux
• https://docs.python.org/3/using/unix.html
• https://docs.python-guide.org/starting/install3/linux
Basically, you can write Python code using any simple text editor. However, using a
more powerful editor may make your life a bit easier. Pick the right editor that suit you.
In the beginning, you are suggested to use a simple text editor such as Notepad++ or
Visual Code. Since you are required to run the program via a command line. Moreover,
using a simple text editor will train you to remember Python syntax and boost your
programming skills.
Lab-work Module 15
Figure 2.3: Visual Studio Code
Atom
PyCharm
Lab-work Module 16
Figure 2.4: Atom code editor
Online Editor
• https://repl.it
• https://www.codechef.com/ide
Lab-work Module 17
2.5 Assignment
Make a report that explain the installation steps of both Python and the code
editor (pick one except the online editor). Don’t forget to enclosed the screen shots of
each steps and explain them. The lab work report shall adhere the following format:
1. Write the report in A4 paper size using 12pt Times New Roman font-face, normal
margin, and 1.3 spacing.
(a) Cover
(b) Contents
(c) Introduction
(d) Theoretical Background
(e) Assignment & Methods
(f) Results & Discussion
(g) Conclusion
(h) References
Submit the report both in hard and soft copy by the next week prior to lab
work. You may submit the report in online class room.
Lab-work Module 18
Module 3: First Code
Martin Fowler
Open your text editor then type the following code. As you finished save into
file name ex1.py.
ex1.py
1 print("Hello World!")
2 print("Welcome to the Algorithm and Programming Course")
3 print("I like typing this.")
4 print("This is fun.")
5 print('Yay! Printing.')
6 print("I'd much rather you 'not'.")
7 print('I "said" do not touch this.')
python first_code.py
If you did it right, then you should see the following output as shown in Fig-
ure 3.1. If not, then you have done something wrong. Don’t blame your computer!
If you encounter an error, don’t panic! You will make many mistakes later on. The
$ python ex/ex1.py
File "ex/ex1.py", line 3
print("I like typing this.)
^
SyntaxError: EOL while scanning string literal
Remember!
Spend a good amount of time to explore the feature of text editor. It is worth
to practice and wont with your working environment. Unless you wish to get
hardship on the exercise afterwards.
If you face any issues regarding your code, you may consult to stackoverflow.com.
It provides QnA about coding and allows you to get feedback regarding your problems.
Type another code bellow and see what you get after executing it.
ex2.py
1 print("Are you sure this blue is the same as the \
2 blue over there? This wall’s like the \
3 bottom of a pool, its \
4 color I mean.\n")
Lab-work Module 20
5 print("\tI need a darker two-piece this summer, \
6 the kind with elastic at the waist so it actually fits. \
7 \nI can’t find her hands. ....")
8 print("\t'BY MARY SZYBIST'")
3.1 Basics
3.1.1 Exercise
1. Open again ex1.py file. Put \t and \n in any place inside the print bracket.
What did it do? Find out what those characters do.
2. Put a #(hash) character at the beginning of the line. What did it do? Find out
what those characters do.
3. Make your script in one line only. What happened when it’s run?
Lab-work Module 21
3.2 Comments
Code sometimes can not express in detail what is the purpose of each line or
each block. Thus, programming language offers so called “comments” to tell what
something does in your own language. They also can be used to disable parts of your
program once you don’t need it.
ex3.py
1 # A comment, this is so you can read your program later.
2 # Anything after the # is ignored by python.
3
4 print("I could have code like this.") # and the comment after is ignored
5
6 # You can also use a comment to "disable" or comment out a piece of code:
7 # print "This won't run."
8
9 print("This will run.")
10
11
12 a, b, c, d = 5, 3.2, "Hello", False
13 x = y = z = "same"
14
15 print(a,b,c,d, x, y, z)
The code above (ex2.py) shows how to use comments in Python that is by
putting #(hash) character at the beginning of the line. Anything behind the # char-
acter will be ignored in compilation. Comments will make your code more readable.
Below are various purpose of comments:
2. Code description
3. Algorithmic description
Lab-work Module 22
5. Metadata: the name of the creator of the original version, current maintainer of
the program, data when the first version was created, etc.
6. Debugging
7. Automatic documentation generation
8. Stress relief
Comment may span multiple lines as well. To do so, you can use # multiple
times. Another means to handle this issue is by using a delimiter (“””). For practice,
type and run the following code.
ex4.py
1 """
2 This would be a multiline comment
3 So you can easily read your program later.
4 Anything after the # is ignored by python.
5 """
6
7 print("I could have code like this.") # and the comment after is ignored
8
9 """
10 You can also use a comment to "disable" or comment out a piece of code:
11 print("This won't run.")
12 """
13
14 print("This will run.")
3.2.1 Exercise
1. Rewrite the ex3.py and ex4.py code and run it. What do you see?
2. Put # inside print command. Why does it not get ignored?
3. Add more space in front of the code at line number 4! What do you see when
you running the code?
Variable is nothing more than a name to store data or value by reserving a memory
location. In other words, it’s like a box where you can store any object and you can
Lab-work Module 23
open or even change its content whenever you need it. Python is an object oriented
language but not statically typed. Compared to strongly-typed language like C, C++,
or Java where every variable has to be declared and bind to a particular data type,
Python is more flexible. The variable declaration, in Python, occurs once you assigning
a value to a variable by using the equal sign (=).
For instance:
Herein, we have created three variables each of which store different value. You
may replace the value any time you want.
Initially, the value of variable name was “John”, later it changed to “Julie”. In
the same way for the rest variables age and weight.
PI = 3.14
GRAVITY = 9.8
As you can see above, each variable and constant may have various type of value.
This raw data given to the variable or constant is often called as literal. Figure 3.2
depicts the different of variable and literal. In general there five types of literal in
Python i.e. Numeric, String, Boolean, Collection, and Special. Numeric literals consist
of 3 different types i.e. Integer, Float, and Complex. A string literal is a sequence of
characters surrounded by quotes (single, double, or triple quotes). Boolean literals
can have these two values: True or False. While Collection literals may consists of
List, Tuple, and Dictionary. The Special literal i.e. None is similar to Null in other
language, such as Java.
1. Python keywords (see Table 3.1) are not allowed as identifier names!
Lab-work Module 24
Figure 3.2: Variable vs Literal
2. Create a name that has a meaning and makes sense e.g. age makes more sense
than a.
5. Use capital letters where possible to declare a constant. For example: PI, SCALE.
ex5.py
1 purpose = None
2 cars = 100
3 space_in_a_car = 4.0
4 drivers = 30
5 passengers = 90
6 destination = "Yogyakarta"
7 time = "06:00 PM"
8 purpose = "travelling"
9 empty = None
10
11 print("There are", cars, "cars available for", purpose)
12 print("There are only", drivers, "drivers available.")
13 print("The available space is ", space_in_a_car, "in each car.")
14 print("We have", passengers, "to carpool today.")
15 print("We need to transport them to", destination, "by", time)
Try to rewrite the code ex5.py and do not copy paste them. In line 1-9, we
declared variables with a variety of data types. Then, at line 12-16 showing how to
combine variables in the print function. You should see the following output (see
Figure 3.3) when running the code.
You may also assign multiple values to multiple variables. Or even assign the
same value to multiple variables at once.
Lab-work Module 25
Figure 3.3: ex3.py output
When you print out those variables print(a,b,c,d,x,y,z), the results will be
as follows:
3.3.2 Exercise
1. In ex5.py, add a new variable to obtain the total space in car, then print out
the result. Hints: use algebraic operator!
3. Rewrite the code sample of assigning multiple values to multiple variables and
assigning the same value to multiple variables. Print out each of them!
3.3.3 String
So far we have been using String, but yet do not know what they do. As a sequence
of characters, each character has an index corresponds to its position (see Figure 3.4).
This allows you to access each character by its index.
String Operation
You may concatenate two or more strings by means of + operator. The string
can also be repeated for given number of times with * operator. To check whether a
Lab-work Module 26
character belongs to a string, you can use in or not in operator. Type and execute
the following code.
ex6.py
1 first_name = "Rose"
2 last_name = "Berry "
3
4 # operation in string
5 print(first_name+" "+last_name)
6 print(last_name * 2)
7
In the previous section, you have been learning how to define variable and how to
combine it with string in print function (see ex5.py). From now on, we will learn
another way to format string. Supposed you have two variables one to store a string
and other to hold a number. You can’t simply concatenate those two with + operator.
Try to execute the following code.
You will get a type-error as both variables are different in data types. In Python,
we use a % character to format variable in the string. Moreover, we can also utilize
format() function to deal with string formatting. During the formatting, the % char-
acter often tailed with particular type of format e.g. %s, %r, %d for string, raw, and
decimal format respectively. If you want to format multiple variable, just simply put
them inside () separated by comma. Table 3.2 shows types of number formatting.
Write down the following code (ex7.py) and comprehend how each line works.
Lab-work Module 27
Table 3.2: Number formatting types
Type Meaning
d Decimal integer
c Corresponding Unicode character
b Binary format
o Octal format
x Hexadecimal format (lower case)
X Hexadecimal format (upper case)
n Same as ’d’. Except it uses current locale setting for number separator
e Exponential notation. (lowercase e)
E Exponential notation (uppercase E)
f Displays fixed point number (Default: 6)
F Same as ’f’. Except displays ’inf’ as ’INF’ and ’nan’ as ’NAN’
g General format. Rounds number to p significant digits. (Default precision: 6)
G Same as ’g’. Except switches to ’E’ if the number is large.
% Percentage. Multiples by 100 and puts % at the end.
ex7.py
1 state_1 = "There are %d types of people." % 10
2 binary = "binary"
3 do_not = "don't"
4 state_2 = "Those who know %s and those who %s." % (binary, do_not)
5
6 print(state_1)
7 print(state_2)
8
15 print(joke_evaluation % hilarious)
16
17 temp = 10.23578
18 print("Today is freezing. The temperature is %2.3f"% temp,
19 chr(176), "C and so windy.")
Lab-work Module 28
Figure 3.6: Formatting by keyword arguments
ex8.py
1 info = "The number of students are {0}"
2 students = 16
3 concat = info.format(students)
4
5 print(concat)
6
7 # default arguments
8 print("Hello {}, your balance is {}.".format("Adam", 230.2346))
9
10 # positional arguments
11 print("Hello {0}, your balance is {1:3.2f}.".format("Adam", 230.2346))
12
13 # keyword arguments
14 print("Hello {name}, your balance is {blc}.".format(name="Adam", blc=230.2346))
15
16 # mixed arguments
17 print("Hello {0}, your balance is {blc}.".format("Adam", blc=230.2346))
However, both formatting ways aforementioned are not great enough. Why is
that so? As if you start using multiple parameters and longer strings, your code will
quickly become much less easily readable. Consequently, this kind of formatting isn’t
great because it is verbose and leads to errors. See the following example:
ex8-1.py
1 first_name = "Eric"
2 last_name = "Idle"
3 age = 74
4 profession = "comedian"
5 affiliation = "Monty Python"
6 print("Hello, %s %s. You are %s. You are a %s. You were a member of %s."
7 % (first_name, last_name, age, profession, affiliation))
8
Lab-work Module 29
9 print(("Hello, {first_name} {last_name}. You are {age}. " +
10 "You are a {profession}. You were a member of {affiliation}.") \
11 .format(first_name=first_name, last_name=last_name, age=age, \
12 profession=profession, affiliation=affiliation))
f-Strings
Also called ”formatted string literals”, is the string formatting feature intro-
duced since Python 3.6 which offers better way to interpolating variables into a string.
Moreover, this approach stands out for the speed as well compared to the prior ways.
f-strings are string literals that have an f at the beginning and curly braces containing
expressions that will be replaced with their values. The expressions are evaluated at
runtime and then formatted using the __format__ protocol. As always, the Python
docs are your friend when you want to learn more. See the example use of f-String at
code ex8-2.py.
ex8-2.py
1 name = "Eric"
2 age = 19
3 print(f"Hello, {name}. You are {age}.")
4
5 # another example
6 n = 20
7 m = 25
8 prod = n * m
9 print(f'The product of {n} and {m} is {prod}')
10
11 # using capital letter F is also permitted
12 print(F"Hello, {name}. You are {age}.")
13
14 # Arbitrary Expressions
15 print(f"{2 * 37}")
16
17 # Using a function inside
18 print(f"{name.lower()} is funny.")
19
20 # multi line expression of f-string
21 affiliation = "ITTelkom Surabaya"
22 message = (
23 f"Hi {name}. "
24 f"You are a {age}. "
25 f"You were in {affiliation}."
26 )
27
28 print(message)
Sometimes we need to ignore some characters while printing a string. For ex-
ample, we want to print out \ backslash or quote inside a string. If you simply put
those characters, you might get an error. Try to execute the following code and see
what you get!
Lab-work Module 30
Table 3.3: Escape Sequence in Python
You might get this error message SyntaxError: invalid syntax which means
that your code contains an invalid symbols or syntax. To print a quote inside a string,
there are two ways: 1) Surround the most outside string with " double-quote, 2) Use
an escape character \' as shown in Table 3.3 to flank the quoted character.
3.3.5 Exercise
1. Write a comment to explain each line of the code ex7.py and ex8.py
2. Write a simple print() function to make use of every type of number formatting
(Table 3.2) with old style formatting (%)
Lab-work Module 31
3.4 Assignment 1
2. Make four variables to store String, integer, floating, and boolean respectively
each of which are assigned with any corresponding value. Then print them with
old style formatting (%), format() function, and f-string.
6 operation_r~ate = 78%
7 operator: = "Steve"
8
9 print(container_1[6] + " container operated by " + operator +
10 " contains {0}".format(container_1))
11
12 print("The operation rate of {name} = {rate}".format(
13 name=operator rate = operation_rate)
14
15 print("Two stack of containers have ", container_2+"oranges")
16
17 print(container_3 * 3)
1. Write the report in A4 paper size using 12pt Times New Roman font-face, normal
margin, and 1.3 spacing.
(a) Cover
Lab-work Module 32
(b) Contents
(c) Introduction
(d) Theoretical Background
(e) Assignment & Methods
(f) Results & Discussion
(g) Conclusion
(h) References
Submit the report both in hard and soft copy by the next week prior to lab
work. You may submit the report in online class room.
In this section, we will elucidate how Python deals with numbers, math, and
logical operators. As mentioned in section 3.3, basically there are two literal types for
numbers i.e. integer and floating. When dealing with numerical stuff, it is common to
use set of operators for calculation. Notice the following code (ex9.py) and figure out
how does the operator work.
ex9.py
1 print("I will now count my chickens:")
2
3 hens = 25 + 30 / 6
4 print("Hens", hens)
5 print("Roosters", 100 - 25 * 3 % 4)
6
7 print("Now I will count the eggs:")
8
9 print( 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
10
11 print("Is it true that 3 + 2 < 5 - 7?")
12
13 print(3 + 2 < 5 - 7)
14
15 sum = 3 + 2
16 print("What is 3 + 2? %d" %sum)
17
18 print("How about some more.")
19
20 print("Is it greater?", 5 > -2)
21 print("Is it greater or equal?", 5 >= -2)
22 print("Is it less or equal?", 5 <= -2)
Lab-work Module 33
What you should see
3.5.1 Operator
Operators are special symbols that often used in a logical or arithmetic computation.
Table 3.4 shows a list of arithmetic operators. Rewrite the ex10.py code and execute
it to see what’s the output and how those operators work.
ex10.py
1 # integer variables
2 x = 8
3 y = 5
4
5 # float variables
6 z = 11.21932
7
8 # float constant
9 PI = 3.14
10
11 print('x + y = {0} + {1} = {2}'.format(x, y, x+y))
12 print('x - y = {0} - {1} = {2} \n'.format(x, y, x-y))
13
14 print('x * y = {0} * {1} = {2}'.format(x, y, x*y))
15 print('x / y = {0} / {1} = {2} \n'.format(x, y, x/y))
16
17 print('x // y = {0} // {1} = {2}'.format(x, y, x//y))
18 print('z // x = {0} // {1} = {2} \n'.format(z, x, z//x))
19
Table 3.5 defines the logical operators used in Python. These operators are
mostly employed to evaluate boolean values. This feature will be much useful when
constructing boolean expression in particular to test a certain condition. Table 3.6 and
Lab-work Module 34
Table 3.4: Arithmetic Operators
Operator Description
not unary negation
and conditional and
or conditional or
Table 3.7 are the truth tables that can aid you to comprehend how logical operator
works. Rewrite and run the ex11.py code!
ex11.py
1 A = True
2 B = False
3
4 print("A and B = {0} and {1} = {2}".format(A, B, A and B))
5 print("A or B = {0} or {1} = {2} \n".format(A, B, A or B))
6
A B A and B A or B
True True True True
True False False True
False True False True
False False False False
Lab-work Module 35
Table 3.7: Truth Table for not Logical Operators
A not A
True False
False True
Operator Description
is same identity
is not different identity
== equivalent
!= not equivalent
programming situations, the equivalence tests == and != are the appropriate operators
whereas using is and is not should be reserved for situations in which it is necessary
to detect true aliasing.
ex12.py
1 #equality and comparison operators
2 x = 5
3 y = 5.0
4 z = "5"
5 a_string = "Python"
6 b_string = "python"
7
8 print("x is y --> {0} is {1} = {2}".format(x, y, x is y))
9 print("x == y --> {0} == {1} = {2}".format(x, y, x == y))
10 print("x == z --> {0} == {1} = {2}".format(x, z, x == z))
11 print("y == z --> {0} == {1} = {2}".format(y, z, y == z))
12 print("y is z --> {0} is {1} = {2}\n".format(y, z, y is z))
13
14 #string comparison
15 print("a_string == b_string --> {0} == {1} = {2}".format(a_string, b_string,
16 a_string == b_string))
17 print("a_string is b_string --> {0} is {1} = {2}".format(a_string, b_string,
18 a_string is b_string))
Operator Description
< less than
<= less than or equal to
> greater than
>= greater than or equal to
Lab-work Module 36
Figure 3.8: ex10.py output
Operator Description
~ bitwise complement (prefix unary operator)
& bitwise and
| bitwise or
^ bitwise exclusive or (XOR)
<< shift bits left, filling in with zeros
>> shift bits right, filling in with sign bit
Beforehand, binary operator mostly used for comparison purpose. On the other
hand, there are also bit-shift operators i.e. << and >>. These operators work by shifting
a number of digit to the left (<<) or right (>>) then fill the remaining bit with zeros. As
an example, 37 << 3 means a shifting 37, in binary representation, to the left 3 digits.
Assumed that an integer has 8 bits instead of 32. So the binary representation of 37
is 00100101. First, remove the 3 digits from the left most bit that is 001. Then shift
the remaining digits to the left. Finally, fill the remaining 3 digit at the right most
with the zeros. Figure 3.10 depicts these operations. So, the output of this operation,
37 << 3, is 100101000 or 296 in decimal. We need to add an extra digit 1 at the
left most bit whenever the left most bit is 0. This operation is somewhat similar to
37 × (23 ) = 37 × 8 = 296.
Lab-work Module 37
(a) and operator
(b) or operator
(a) Remove 3 digits from the left (b) Fill 3 empty digits
Lab-work Module 38
Table 3.11: Assignment Operators
The right-shift operator generally works in the same manner in the opposite
direction. By shifting the digits to the right and filling the remaining digits with zeros.
As an instance, 60 >> 2 is similar to 60/(22 ) = 60/4 = 15. Figure 3.11 shows the
operations of right-shift.
Assignment operators as shown in Table 3.11 are used to assign values to vari-
ables. Python supports an extended assignment to simplify the expression. For exam-
ple, a syntax x += 5 is a shorthand of the more verbose expression x = x + 5.
3.5.2 Exercise
For exercise, rewrite the code ex13.py and add a comment to each line explaining what
it does.
ex13.py
1 number_1 = 37
2 number_2 = 23
3
4 # and or bitwise
5 and_number = number_1 & number_2
6 print("{} & {} = {:b} & {:b}".format(number_1, number_2, number_1, number_2))
7 print("{:b} = {}\n".format(and_number, and_number))
8
Lab-work Module 39
17 print("37 << 3")
18 print("{:b} << {:b} = {:b}".format(37, 4, left_shift))
19 print(left_shift)
20
21 print("\n60 >> 2")
22 print("{:b} >> {:b} = {:b}".format(60, 2, right_shift))
23 print(right_shift)
24
25 # extended assignment
26 print("\nextended assignment")
27 grade = 85
28 grade += 5
29
30 print(grade)
31
32 grade //= 5
33 print(grade)
34
35 grade /= 2 + 3 * 4 - 5
36 print(grade)
37
38 grade *= (1 + 4.78) % 9.75
39 print(grade)
In the previous sections we have learned how to set an output using print()
function. Herein, we will study on taking a simple input from the user. Python 3 offers
a convenient way to get a user’s input by means of input() function. Execute the
code ex14.py below.
ex14.py
1 name = input("Enter your name! ")
2 age = input("Enter your age! ")
3
4 print("Hi %s! You are %s years old" %(name, age))
5
6 books = int(input("How many books do you want to buy? "))
7 prince = 27500
8 total_price = books * prince
9
10 print("Total price = Rp {}".format(total_price))
11 print(list(range(10, 0, -1)))
At line 1-2 and line 6 shows how to use input() function. These will prompt
you an input. See line 8, what output do you expect from this expression? And what
finally do you get when running the code? As you can see that every input has a
string data type. Thus, it needs to be converted to a particular type e.g. number.
Lab-work Module 40
We use the predefined functions like int(), float(), str(), etc to perform explicit
type conversion. Afterwards, we will learn how to handle input and output from file
on another module.
3.6.1 Exercise
For exercise, fix the code ex14.py above so that you can get the valid total price that
is Rp82,500.
3.7 Assignment 2
1. Check out the naming of the following variables. Determine whether those ex-
pressions are correct or wrong and give reasonable arguments!
(a) price_2
(b) 10stock
(c) pet%name
(d) _colour
(e) place,birthdate
2. Run the following mathematical expression in Python, then put the output screen
shot!
(a) 7 × 5
(b) 7 × 5 − 3
(c) 25 + 3
(d) 19%3//2.4
(e) 19%(3//2.4)
3. Explain about operator precedence in Python and give some code example!
4. Make a code to reverse an input string. The length of the input string is fixed to
10. The program output supposed to be like this:
Lab-work Module 41
Enter your body fat = 0.45
Enter your body weight = 62
Your BMR is 1106.56 cal/day
1. Write the report in A4 paper size using 12pt Times New Roman font-face, normal
margin, and 1.3 spacing.
(a) Cover
(b) Contents
(c) Introduction
(d) Theoretical Background
(e) Assignment & Methods
(f) Results & Discussion
(g) Conclusion
(h) References
Submit the report both in hard and soft copy by the next week prior to lab
work. You may submit the report in online class room.
Lab-work Module 42
Module 4: Sequential and Branching