Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
81 views

SIC - C - P - Chapter 1. Programing Basic Concept and Starting Python - v1

Uploaded by

Amina Amina
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
81 views

SIC - C - P - Chapter 1. Programing Basic Concept and Starting Python - v1

Uploaded by

Amina Amina
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 545

Chapter Description

Orientation

<Most loved languages in 2020>


Python
Python 66.70%
C# 59.70%
JavaScript 58.30%
R 44.50%
Java 44.10%
C++ 43.40%
Ruby 42.90%
C 33.10%
Orientation

‣ Python code can be written and interpreted similarly as human’s everyday language, so it is readable and easy to
learn by beginners. Students can design the flow of the program in human language and change it to the actual
Python code very easily.
‣ Especially the syntax of Python is very simple and intuitive to write and understand, which helps new programmers
not to waste time with confusing syntax.

Python syntax

Interpreted
Orientation

‣ Python is wanted not only in educational fields but also by many developers in professional workplaces. Big
companies, including Google, Intel, eBay, Netflix, Instagram, Dropbox, and Slack, utilize Python for developing and
maintaining their applications.

‣ Google uses Python software development to


enhance its search engine capabilities.
<Major companies that use Python>
‣ Netflix uses Python to recommend movies, TV
shows, and documentaries based on a user’s history.
‣ Instagram uses Python to personalize the explore
Major companies that use Python section for users.
‣ Spotify uses Python for personalized music
recommendation to its users.
‣ Reddit uses Python for web development to simplify
the Q&A sections.
Orientation

‣ Python includes various libraries, such as pandas, NumPy, SciPy, Matplotlib, TensorFlow, and Keras, that can be
extensively used in different fields like web development, data analytics, and artificial intelligence.

‣ pandas is used for data manipulation and analysis,


<Python libraries> particularly featuring numerical tables and time series
operation.
‣ NumPy supports for large, multi-dimensional arrays and
matrices, along with a collection of high-level
mathematical functions.

Major companies that use Python ‣ TensorFlow is based on dataflow and differential
programming, which focuses on deep neural networks
for machine learning.
‣ Keras provides an interface for artificial neural networks
with a focus on enabling fast experimentation.
Orientation

‣ The 4th industrial revolution focuses on task automation, improved communication, and self-monitoring of smart
machines. Especially, machine learning and deep learning have been growing rapidly as the flower of the 4th
industrial revolution.
‣ As mentioned in the last slide, Python supports multiple libraries that engage in machine learning and deep
learning of artificial intelligence. It has been developing along with the progress of the 4 th industrial revolution,
and it plays a key role in enhancing in their rapid growth.

‣ Python also has different types of Python framework, such as Django, Flask, and FastAPI. With the utilization of
those frameworks and libraries, Python can be used in both front-end and back-end programming. It allows full
stack development, which is preferred in many job positions in related industries.
Orientation

Artificial Intelligence Data Science


& & Web Development Game Development
Machine Learning Data Visualization

Simplifying everyday tasks


through automation
Automation
Software Testing and ‣ Updating your grocery shopping list
Automate the simple Prototyping ‣ Renaming large batches of files
tasks on the computer
‣ Converting text files to spreadsheets
‣ Filling out online forms automatically and etc.
Orientation

IoT Course C&P Course AI Course

Basic Python

Algorithm for
Data Analysis
Orientation

IoT Course C&P Course AI Course

Ch 1 Understand IoT Ch 1 Python Basic Ch 1 Introduction to AI


for the 4th Industrial Revolution

Ch 2 Raspberry Pi Hardware and Ch 2 The Flower of Python Basics – Ch 2 Basic Algorithm for AI Learning
Electrical Electronics Sequence Data Type Handling

Ch 3 Python Intensive – Ch 3 Practice Processing Data


Ch 3 Git and Version Control Function and Closure
Ch 4 Probability and Statistics
Ch 4 Programming Raspberry Pi Ch 4 Algorithm I – Data Structure
in Python
Ch 5 Machine Learning Part 1
Ch 5 Linux for Network Connection Ch 5 Algorithm I I– Sort
Ch 6 Machine Learning Part 2
Ch 6 Programming IoT Network Ch 6 Algorithm – Graph and Others
Connection
Ch 7 Machine Learning Part 3
Ch 7 Preparation for Data Analysis
Ch 7 Node.js for Internet Network (Pandas Basics)
Ch 8 Deep Learning Part 1
Ch 8 Practice of Data Analysis and
Ch 8 IoT Project in Mobius Platform Data Visualization Ch 9 Deep Learning Part 2
Unit learning objective (1/3) UNIT 01
Unit learning objective (2/3) UNIT 01
Unit learning objective (3/3) UNIT 01

Computational Virtual Jupyter


thinking Environment Notebook

Sequential Naming
Annotation
Structure Conventions

Syntax
Expressions Runtime Error
Error
UNIT 01

1.1. 47% of jobs will disappear in the next 20 years due to tech innovation.
UNIT 01

1.2. The 5Cs of 21st Century Skills

Computational Thinking
UNIT 01

1.3. How Should We Prepare for Computational Thinking?

"Computational Thinking is the thought processes involved


in formulating problems and their solutions so that the
solutions are represented in a form that can be effectively
carried out by an information-processing agent.“
- Cuny, Snyder, Wing, 2010
UNIT 01

2.1. Thinking like a Computer


※ To view the video clip above, move your mouse onto video screen to appear the play button.

3 ways to make better decisions -- by thinking like a computer | Tom Griffiths


UNIT 01

2.2. The 3 Structures of Programming

Sequence Selection Iteration


UNIT 01

3.1. Create a Program that Prints Your Resume

※ To view the video clip above, move your mouse onto video screen to appear the play button.
UNIT 01

3.2. Program Planning

[1] # Self-introduction program Start


Start
Print resume preface
[2] Print preface of the resume
Print name
[3] Print name

[4] Print age Print age

[5] Print job Print job

[6] Print the current address


Print current address
[7] Print birth place
Print birthplace
[9] End
End
UNIT 01

3.3. Resume Program: Final Codes


UNIT 01

1.1. Definition and Importance of Sequence

Sequence is important in everyday life How could the changed order affect the result?

put toothpaste on toothbrush rinse toothbrush

use toothbrush to clean teeth put toothpaste on toothbrush

rinse toothbrush use toothbrush to clean teeth


UNIT 01

2.1. Using the Glossary


UNIT 01

2.2. Expression, Statement, and Program

Expression Statement Program

352
10 + 20 import time
timesleep(5)
‘Hello World!’ timesleep(5)
assemble print(‘Hello World!’) assemble
import print(‘Hello World!’)
17.2
UNIT 01

2.3. Annotation

#define the variable as a radius

#print the radius, area, and circumference of the circle


('Radius', radius)
('Area', 3.14 * radius * radius) #Apply the formula to solve for the area of a circle
('Circumference', 2.0 * 3.14 * radius) #Apply the formula to solve for the circumference of the circle

Radius 4.0
Area 50.24
Circumference 25.12
UNIT 01

2.3. Annotation

You can create a multiple-line annotations using double quotation marks.

It allows you to make multiple lines of comments.

It allows you to make multiple lines of comments.

It allows you to make multiple lines of comments.


UNIT 01

2.4. Reserved Word


Try to fully understand the basic concept before moving on to the next step.
Lack of understanding basic concepts will increase your burden in learning this
course, which may make you fail the course.
It may be difficult now, but for successful completion of this course we suggest you
to fully understand the concept and move on to the next step.
UNIT 01

Move Right,
Start Fill-In Square,
Here
Move Right,
Move Down
Fill-In Square,
Move Left,
Move Left,
Fill-In Square
Move Down,
Move Right,
Fill-In Square,
Move Right

Write the entire code and the expected output results in the note.
UNIT 01

Image 1 Image 2 Image 3 Image 4 Image 5 Image6

Move One Move One Fill-In Square


Move One Move One Square Up Square Down with Color
Square Right Square Left

Write the entire code and the expected output results in the note.
UNIT 01

1.1. Installing Anaconda


UNIT 01

1.1. Installing Anaconda


UNIT 01

1.1. Installing Anaconda


UNIT 01

1.2. Installing Jupyter Notebook


UNIT 01

1.2. Installing Jupyter Notebook


UNIT 01

2.1. Definition and Necessity of Virtual Environment

python : 3.8
python : 3.7
Install pandas

data_science python_work

Computer
UNIT 01

2.2. Creating a Virtual Environment


UNIT 01

2.2. Creating a Virtual Environment


UNIT 01

2.3. Anaconda Commands for Managing the Virtual Environment

Execution Command

See list of virtual environments conda env list

Create virtual environment conda create –n [name of a virtual environment]

conda create –clone [name of virtual environment to clone] –n [a new


Clone virtual environment
virtual environment]

Activate virtual environment conda activate [name of a virtual environment]

Deactivate virtual environment conda deactivate

Remove virtual environment conda remove --name [name of a virtual environment] --all
UNIT 01

2.3. Anaconda Commands for Managing the Virtual Environment


UNIT 01

2.3. Anaconda Commands for Managing the Virtual Environment


UNIT 01

3.1. Running the Jupyter Notebook


UNIT 01

3.1. Running the Jupyter Notebook


UNIT 01

3.1. Running the Jupyter Notebook


UNIT 01

3.2. Jupyter Notebook UI


UNIT 01

3.2. Jupyter Notebook UI


UNIT 01

3.2. Jupyter Notebook UI


UNIT 01

3.2. Jupyter Notebook UI


UNIT 01

3.2. Jupyter Notebook UI


UNIT 01

3.2. Jupyter Notebook UI


UNIT 01

4.1. The Basics


Both single quote and
print( ) code is a command that outputs values inside the ( ) double quote marks work,
but the start and end
symbol has to match.

The value between the open quotation and close quotation marks are called a string.

TIP

 Unlike other languages, Python automatically breaks a line after outputting a string through print().
UNIT 01

4.2. Printing String and Value


UNIT 01

4.3. Adding a New Line


UNIT 01

4.3. Adding a New Line


UNIT 01

4.4. The Comma(,) Additions(+), Multiplication(*) Operators


UNIT 01

4.4. The Comma(,) Additions(+), Multiplication(*) Operators

When using an addition (+) operator, you cannot combine strings and numbers. When a string and a number are
combined with an addition operator (+), TypeError occurs.
UNIT 01

4.4. The Comma(,) Additions(+), Multiplication(*) Operators

When a string and a string are combined with a multiplication operator (*), TypeError occurs.
UNIT 01

4.5. End and Split Parameters


UNIT 01

4.5. End and Split Parameters


UNIT 01

4.6. Creating a Resume


UNIT 01

5.1. Why is Pythonic Coding Important?


UNIT 01

5.2. Code lay out


UNIT 01

5.2. Code lay out


UNIT 01

5.3. Naming convention

Style Description Example


The first letter starts with a lowercase letter and uses _ (underscore) instead of spaces
Snake hello_world
between words. It’s called Snake Style because the underscores looks like snakes.
The first letter starts with a lowercase letter, and the start of the next word is
Camel capitalized instead of spacing. It’s called the Camel style because the capital letters in helloWorld
the middle looks like a camel's back.

Pascal Almost the same as the Camel style, but the first alphabet is also capitalized. HelloWorld
UNIT 01

5.3. Naming convention

1. Generally consists of English characters, numbers, and underscores (_).


2. There should be no spaces in the middle of the text.
3. The first word must start with an English letter or an under score (_).
4. Upper and lower case letters are distinguished. For example, Count and count are different identifiers.
5. There is no limit to the length of the identifier.
6. Keywords cannot be used as identifiers.
7. Identifiers starting with __(two underscores) refer to special attributes or use only as the name of specific
methods. Therefore, it is not used as the name of a general function or variable.
UNIT 01

5.3. Naming convention

Correct Identifiers Reasons

number4 Numbers can be used after starting with English characters.

Underscores can be used anywhere in the identifier, like the rest of the
my_list
characters.

__code__ The name of a specific method can start with __(two underscores).

for_loop A keyword can be used by connecting with other characters.


UNIT 01

5.3. Naming convention

Incorrect Identifiers Reasons

1st_variable Cannot be used because it starts with a number.

my list Cannot be used because there is a space.

global Python keywords cannot be used as identifiers.

ver2.9 A special character other than the underscore cannot be used.

num&co A special character other than the underscore cannot be used.


UNIT 01

6.1. Syntax Error


UNIT 01

6.2. Runtime Error


UNIT 01

1. Runtime Error and Resolution

('Enter two integers.').split()

('Check if the integers are correctly entered.')

Enter two integers. 10 2


10/2 = 5.0
UNIT 01

1. Runtime Error and Resolution

('Enter two integers.').split()

('Check if the integers are correctly entered.')

Enter two integers. 10 two


Check if the integers are correctly entered.

('Enter two integers.').split()

('Check if the integers are correctly entered.')

Enter two integers. 10 0


Check if the integers are correctly entered.
UNIT 01
UNIT 01
UNIT 01

*
***
*****
*********
*****
***
*
Unit learning objective (1/3) UNIT 02

Learning objectives

 Be able to explain the definition and the necessity of computational thinking to another learner.

 Install software programs which are required for Python programming in person when the training
environment is not set up.

 Construct a new virtual environment when python 3.x is already set up and install different versions of
Python.

 Be able to infer the order of the codes when looking at the output that only used the print function.

 Be able to distinguish between syntax error and run-time error when encountering any errors.
Unit learning objective (2/3) UNIT 02

Learning overview

 Classify the program, which a learner wants to make, into task units with everyday language and write it as
Pseudocode in the right order.
 Be able to express how to solve everyday problems in algorithm using flowchart.
 Interpret their own pseudocode and rewrite it into a flowchart.
 Explain the difference between a program and an algorithm.
 Be able to select the most efficient one among several suggested algorithms with the Big O notation.

Concepts You Will Need to Know From Previous Units

 How to run Jupyter notebook in a virtual environment


 Printing string on screen using print() function
 Three types of Python control structures: Sequential, Selection, Repetition
Unit learning objective (3/3) UNIT 02

Keywords

Pseudocode Flowchart Algorithm

Linear search Big O notation


Mission
Mission UNIT 02

1.1. Process of discovering problems and finding solutions


※ To view the video clip, put the mouse on the box above, ‣ An invention is a newly created product,
and the play button appears. Click it to watch. technology, or process to solve any problem.
‣ William Kamkwamba was born in Malawi, Africa
where famine is severe.
‣ His family had difficulty of farming and basic life
due to lack of water and electricity. To help his
family, William, a 14-year-old, invented a small
windmill with collected scrap metal through his
idea, and he could solve the water and electricity
problem that his family were suffering from.
‣ Like this, an invention is not difficult.
It begins with discovering what problems are in
the real world around us.
‣ While learning Python though this course,
you will practice the process of discovering
https://www.ted.com/talks/william_kamkwamba_how_i_harnessed_the_wind/transcript problems in our daily lives and finding solutions
to solve them.
Mission UNIT 02

1.2. William’s windmill invention process

Practical application to ‣ The left figure is the actual process that William went
Finding problems through to come up with ideas to solve the discovered
the problem
problems, and turn them into concrete inventions.
Coming up with ideas to ‣ This process is not only William but also lots of
Coming up with solutions
solve the problems scientists and inventors adopt in inventing something.
‣ This is called an invention log or engineering design
Planning for an invention process (EDP).
‣ Every step is very important, however, the most
important part is to concretely plan ideas. And continue
Making a prototype to improve the ideas through experiment, correction,
and feedback.

Experiment and ‣ Programming is the same. If someone wants to make


correction something, he/she should start by planning thoughts
and ideas in detail, rather than working directly on the
computer.
Continuous development
Improving your ideas
through repetition
Mission UNIT 02

2.1. EDP(Engineering design process)


EDP ​is a series of steps engineers and scientists follow to find a solution to a problem. Each stage consists of a process
of setting goals and constraints, creating a prototype, and continuously testing and evaluating.
Each of EDP has 5, 7, or more stages, but the most detailed steps are as shown in the image below.

Make A Model
Or Prototype
Mission UNIT 02

3.1. Represent the problem below as a flow chart diagram


The EDP process can also be applied to computer engineering and programming.
In programming, the planning stage (Develop A Design Proposal) can be expressed as pseudocode and a flowchart.

[MISSION]
Let's consider that you are traveling now.
You need to find the hotel you booked, but you get lost.
So, you are asking a passer-by for directions, and he guides you as below.

“Go straight west at this crossroads. You will see four buildings.
When you see the post office, turn right across the post office.
Go straight, and when you see an Italian restaurant, the third building is the hotel you are looking for.”

You're new to everything in this area.


To find the hotel successfully, you are going to find the hotel after creating a flowchart of the instructions
you've been told!
Mission UNIT 02

3. Mission
3.2. References for solving missions
Here are digital tools that help you to easily draw a flowchart.
There are many tools, but the ones introduced below are free and easy to use.

Lucid chart Google drawings

https://www.lucidchart.com/pages/ Search at https://chrome.google.com


Mission UNIT 02

3. Mission
3.3. A path-finding flowchart_Final Code
We are showing the final code before starting the lesson not because you have to follow it at this stage.
It is because that you can infer the process in advance by looking at the completed version of the mission solution that
you will make at the end of the lesson.

Start

Enter Arrive Repeat 3 times


Walk straight
a crossroad at the building
Go straight and
pass the building
Choose one road Is it a Arrive
from the crossroad post-office at the building No
building? Yes Check the name
No
Judge if of building
Yes
the chosen road is
Italian
westward Turn right Restaurant
Yes
Finding the hotel
Walk straight No is over
Key concept
Key concept UNIT 02

1. Algorithm
1.1. The definition of an algorithm
An algorithm is a set of instructions for doing something.
An algorithm should have a reasonable sequence of computations and tasks to solve a problem, not just a set of
commands.
We can plan for creating an algorithm, which is a procedure consisted of commands for problem-solving. The planning
process can be made up with a pseudocode and flowchart.

Algorithm

command Algorithm is a well-


defined computational
input command process that gets an output
input of some value or a
set of values, and then
command prints it as another
value or a set of values.
command It is a set of commands.

[31,41,59,26,41,58] By using Sort Algorithm [26,31,42,41,58,59]


Key concept UNIT 02

2. Algorithm representation and planning


2.1. Pseudocode
Sequence is that a computer sequentially executes the commands from codes.
Pseudocode is a representation of an algorithm using daily language. Pseudocode can be a good start for developing
algorithm when you do not have enough background knowledge about programming.
Pseudocode plays a role as a bridge for completing a flowchart and an actual code. It is often mostly used by
programmers as a basic guideline when they implement the actual code.
It's the most essential that you should clearly explain and plan what each line of codes should perform.

This program will allow the user to check the number ‣ Write a sentence that describes the purpose of the
whether it's even or odd. algorithm in the beginning.
‣ Write concisely.
If “4” ‣ Create and use rules of simple and distinguishable
print result names to be used.
“This number is even”
‣ Indentation and whitespace are key points
If “3” ‣ Express sequence structures, selection structures,
print result and repeating structures using if, for, while.
“This number is odd”
Key concept UNIT 02

2. Algorithm representation and planning


2.2. Flowchart
Flowchart expresses commands with several standardized shapes and the flow of work using arrows.
For shapes and symbols, those set by the International Organization for Standardization (ISO) are used.
It is important that you draw them from top to bottom and from left to right without overlapping each other.

Start , End Preparation Action or Process Decision


Represent the start Initialize data Arithmetic operations/ Used to branch to different
and end of a flowchart processing of a single step parts of a flowchart based on
judging a condition

Input, Output Document On-page Connector Flow Arrow


Used for input Represent printed Connect to this symbol of Represent the flow of
and output data document or report another flowchart (Junction) processing
Key concept UNIT 02

3. Algorithm efficiency
3.1. Which algorithm should we choose and use?
※ To view the video clip, put the mouse on the box above, and the play button appears. Click it to watch.

https://youtu.be/6hfOvs8pY1k

What’s an algorithm - David Malan


Key concept UNIT 02

3. Algorithm efficiency
3.2. Which method is more efficient?
Prepare seven numeric data [array] in no order but arranged side by side.
Let’s think about the efficiency of algorithm by looking at two types of algorithms that search for a specific value in a
prepared data.

When you get the desired result through an algorithm,


can you say the used algorithm is an efficient one?

input Algorithm output

41 3 6 5 9 36 23 6

Prepare 7 numbers Find the desired number 6 The desired number 6 is


through algorithm selected.
Key concept UNIT 02

3. Algorithm efficiency
3.3. Algorithm A to find the value 6
This algorithm is very simple. It checks the data one by one from the beginning until it searches the desired data.
This is called as a linear search algorithm as it searches a data sequentially.

Step 1
41 3 6 5 9 36 23

• Compare 41, the first data, with 6, the data to be found,. In this example,
• Moves one space to the right because it does not match the data to be searched. 3 times of commands to compare the
Step 2 given numbers are performed to find
the desired digit 6.
41 3 6 5 9 36 23
If the total number of data is huge or
• Compare 3, the second data, with 6, the data to be found. there is no data to find,
• moves one space to the right because it does not match the data to be searched. what will happen?
Step 3 How many times does it have to
41 3 6 5 9 36 23 compare and continue?

• Compare 6, the third data, with 6, the data to be found


• Stop the movement since it matches the data to be searched.
Key concept UNIT 02

3. Algorithm efficiency
3.4. Algorithm B to find the value 6
Before starting the algorithm B, align the data in numerical order first. 3 5 6 9 23 36 41
Compare the data at the center of the dataset with 6, and then lessen the search area into a half.
(This is called a binary search.)

Step 1
3 5 6 9 23 36 41
• Find the median value To find the desired digit,
• Compare this with 6, the data to be found. while comparing from the center,
• Since 9 is greater than 6, it infers that 6 is in the left direction from the center. the searching range of data is
Step 2 eliminated by half. When the desired
value is found, the process ends.
3 5 6
• Exclude values in unnecessary direction from the scope of the search. If the total number of data is huge or
• Find the median value again in this dataset. there is no data to find,
• Since 5 is less than 6, it infers that 6 is in the right direction from the center. what will happen?
Step 3
Think about it compared to
6 Algorithm A.
• Exclude values in unnecessary directions from the scope of the search.
• Found the desired value
Key concept UNIT 02

3. Algorithm efficiency
3.5. Let’s compare Algorithm A and B
It is proved that though an algorithm produces the desired result, it cannot be the efficient algorithm.
When learning Python, obtaining the results is important. But it is also necessary that you agonizes to find the more
efficient algorithm.

Algorithm A Linear search


1 2 3 … 99 100 If the number of data is n, n steps

• There are a hundred data. a hundred (100) a hundred of steps


• For finding the desired value, you have to
compare the data 100 times in the worst case.

Algorithm B binary search


1 2 3 … 99 100 If the number of data is n, log2n steps

• There are a hundred data. a hundred (100) log 2100 = 7 steps


• Since the searching range is lessened by half,
the number of data to be compared are reduced to
100 → 50 → 25 → 13 → 7 → 4 → 2 → the result.
• Whatever number you want, you can find results in seven
searches.
Key concept UNIT 02

4. Algorithm performance
4.1. Memory structure
There are two main ways to measure the performance of an algorithm: space complexity, which measures how much
space the computer occupies; and time complexity, which measures how quickly problems are solved.
Space complexity is a measure of how much memory a computer uses.
How is the memory used in our computer, and why do we have to measure the memory usage?

‣ Code area: The area where program codes to be


executed is stored. The CPU takes commands one
Program codes Code area
by one and processes them
‣ Data area: global variable and static variable
Global variable, allocation area. It is allocated when the program
Data area
Static variable starts and destroyed when the program ends.
‣ Heap area: Area managed by the programmer
Dynamic
Heap area Determine area
allocation area ‣ Stack area: The area where local variables and
size by runtime
parameters related to function calls are stored.
Local variable, Determine by It is destroyed when the function call completes
Stack area compile time
Parameter
Key concept UNIT 02

4. Algorithm performance
4.2. Space Complexity
The memory of our computers has limited resources. So the algorithm occupying less space is more efficient in terms
of space complexity.

Memory Area of Memory Area of Compare the total amount of each area.
Algorithm A Algorithm B

Program codes Program codes

Global variable, Global variable,


Static variable Static variable

Dynamic Dynamic
allocation area allocation area
Algorithm B,
which occupies less memory space,
Local variable, Local variable, is more efficient
Parameter Parameter in terms of space complexity.
Key concept UNIT 02

4. Algorithm performance
4.3. Time Complexity in Big O
Big-O notation is a mathematical representation of the algorithm performance.
The speed of the algorithm can be affected by the computer performance. Therefore, we need to compare the
algorithm’s performance by expressing the work steps with mathematical notations, rather than by evaluating it with
the actual time consumed.
Compared to spatial complexity, which is difficult to measure, time complexity is useful when evaluating algorithm
performance.

Big
O(n) The counts of
Alphabet O Algorithmic operation

# Big O means to mark what is important.


Key concept UNIT 02

4. Algorithm performance
4.4. Let's write and compare linear search and binary search in Big O.
We already know that binary search has fewer task steps than linear search.
Let’s compare the binary search and the linear search again with Big O notation
All algorithms we will learn, as well as linear search and binary search, can be expressed the computational steps as
the Big O notation to compare and analyze the efficient algorithms.
If you do not understand how to display the number of operations in a binary search in log, study by yourself using the
link below.

Consider it takes 1 millisecond to check one data Linear search Binary search
The number Binary
Linear search
algorithmic operation

algorithmic operation
of data search O(n)
100
Count of

Count of
100 7 milliseconds
milliseconds
14 O(log n)
10.000 10 seconds
milliseconds
32
109 11 day
milliseconds Number of data elements to process Number of data elements to process

https://www.khanacademy.org/math/algebra2/x2ec2f6f830c9fb89:logs/x2ec2f6f830c9fb89:log-intro/v/logarithms
Key concept UNIT 02

4. Algorithm performance
4.5. Let's compare other algorithms by noting them as Big O.
In this course, we will be learning different types of algorithms. Similar to linear search and binary search,
the number of operations of the algorithms can be also notated with Big O depending on the number of data.
It is possible to identify high-efficiency algorithms as shown in the image below with Big O notation

Big - O Complexity Chart


O(2^n) TERRIBLE Better
operations

O(n^2)
BAD O(log n) Log time: binary search
O(n!)

FAIR O(n) linear time: linear search


GOOD O(n2): Selection sort
AMAZING O(n* log n): Quick sort

O(log n), O(1)


elements
Source : https://medium.com/swlh/programming-pieces-big-o-notation-b42cfcd88132
Key concept UNIT 02

One more step


Binary code
※ To view the video clip, put the mouse on the box above, and the play button appears. Click it to watch.

https://youtu.be/wgbV6DLVezo
Paper coding
Try to fully understand the basic concept before moving on to the next step.
Lack of understanding basic concepts will increase your burden in learning this
course, which may make you fail the course.
It may be difficult now, but for successful completion of this course we suggest you
to fully understand the concept and move on to the next step.
UNIT 02
UNIT 02
UNIT 02

Express the way of finding the hotel in pseudocode using the pseudocode commands given below.
Write everything else in everyday language except the commands below.
Pay attention to indentation when using commands.

“Go straight west at this crossroads. You will see four buildings.
When you see the post office, turn right across the post office.
Go straight, and when you see an Italian restaurant, the third building is the hotel you are looking for.”

Commands to use
• Input : read, obtain, get
• output: print, show, display
• Calculation: compute, calculate, determine
• Iteration: for, while
• Decision-making according to conditions: if-then-else
• Conditional iteration: repeat-until
• Correct, wrong: true, false

Write the entire code and the expected output results in the note.
Let’s code
Let’s code UNIT 02

1. Three execution structures of Python that can be applied to


everyday life
The three structures (sequence, selection, and iteration structure) of the program learned in Unit 1 are useful not only
in coding but also in real life.

Case of Daily Life 3 Types of Programming Structure

“Go straight west at this Sequence Selection Iteration


crossroads. You will see four
buildings.
When you see the post office, Applied in
turn right along the post office. Algorithm
Go straight, and when you see an
Italian restaurant, the third
building from the restaurant is the
hotel you are looking for.”
Let’s code UNIT 02

2.1. Start Directions and find West Directions


‣ We will start to find a way to the hotel. To do this, you should enter
the crossroad first. [Sequence]
Start
‣ Before going west at the crossroad, check the roads one by one and
determine whether each one is in the west direction. If it is
Enter
westward, walk straight. If not, check the next road. [Selection]
a crossroad

Choose one road


from the crossroad
No

Judge the
westward

Yes

Walk straight
Let’s code UNIT 02

2. Draw directions as a flowchart


2.2. Find a post office building
‣ Enter westward at the crossroad and keep going straight.
Go straight and you will arrive at the first building.
[Sequence]
Arrive
at the building ‣ Judge whether the first building is a post office. If it is a
post office, turn right along the post office. If not, go
straight again and check the next building. [Selection]
Is it a
post-office
building?

Yes

Turn right

Walk straight No
Let’s code UNIT 02

2. Draw directions as a flowchart


2.3. Find an Italian Restaurant
‣ After passing the post office building, turn right and keep
going straight. Go straight and you will arrive at the first
building. [Sequence]
Walk straight
‣ Judge whether it is an Italian restaurant from the first
building. If it is an Italian restaurant, start looking for
Arrive hotel. If not, go straight again and check if the next
No
at the building building is an Italian restaurant. [Selection]
Yes

Italian
Turn right Restaurant
Let’s code UNIT 02

2. Draw directions as a flowchart


2.4. Find the accommodation and end directions
‣ Once you've found an Italian restaurant, you'll start
looking for hotel. [Sequence]
Repeat 3 times
‣ The third building is the one that you’re looking for. So,
Go straight and repeat the process of going straight and passing the
pass the building building three times. [Iteration]
‣ When you arrive at the third building, check the name of
Yes the building to see if it is the correct one, and then finish
Check the name
of building the search. [Sequence]

Italian
Restaurant

Finding the hotel


is over
Let’s code UNIT 02

One more step


1. Introduction of Python learning references
There are good learning references to study Python by yourself. If you want to learn more about Python, visit the
websites below.
Python Software Foundation

‣ A non-profit foundation responsible for the


development and distribution of Python.
‣ Be able to download the latest version of Python for
free.
‣ Provide Tutorials and documents for learning Python.
‣ Introduce the latest news and events.
‣ Provide some successful examples of great Python
projects.

https://python.org/
Let’s code UNIT 02

One more step


1. Introduction of Python learning references
Python Software Foundation

‣ Be able to learn the basics of Python in the


Python Tutorial page.

https://docs.python.org/3/tutorial/index.html
Let’s code UNIT 02

One more step


1. Introduction of Python learning references
Python Software Foundation

‣ The Python documentation page provides


detailed documentation about Python.

https://docs.python.org/3/
Let’s code UNIT 02

One more step


1. Introduction of Python learning references
W3Schools

‣ How can we find out the materials that are


helpful for applying Python more extensively?
‣ At W3Schools, you can learn various
programming languages ​with Python.
‣ In particular, you can directly run Python code
examples in a web environment.

https://www.w3schools.com
Let’s code UNIT 02

One more step


1. Introduction of Python learning references
Stack Overflow

‣ While writing a program, you will encounter


many errors and problems that are difficult to
solve. How to solve these problems?
‣ Stack Overflow is the world's most popular
information sharing website for developers.
‣ Search for “reverse list element in python” on
this website. There will be many questions and
discussions related to the list you will learn
later.

https://stackoverflow.com/
Pair programming
Pair programming UNIT 02
Pair programming UNIT 02
Pair programming UNIT 02

Write a flowchart factorizes 18, 39, 63, 126, 792


Unit learning objective (1/3) UNIT 03
Unit learning objective (2/3) UNIT 03

Learning overview

 Perform math operations including arithmetic operation, power, etc. using numeric data types.
 Find out data types of objects and learn how operators work depending on data types.
 Make an output using string data types.
Unit learning objective (3/3) UNIT 03

Numeric Data Arithmetic


Data Types
Types Operations

Strings String Indexing


UNIT 03

1. Real world problem


1.1. Observing the Shadow of a Black Hole
UNIT 03

1. Real world problem


1.2. Circumference and Area Formula of the Circle

Circumference of
Diameter the circle = 2𝝅𝒓

Radius (𝑟) Area of the circle


= 𝝅𝒓𝟐
UNIT 03

2. Solution
2.1. Python contributed greatly to the shadow observation of black holes.
UNIT 03

2. Solution
2.2. Python to solve the global climate crisis
UNIT 03

3. Mission
3.1. Print the circumference and area of the circle
In this mission, get an input of circle’s radius.
Calculate circumference and area of the circle using operators we will learn in this unit.
Print calculated circumference and area of the circle on the screen.
Put various numbers like 4, 5, 6, 10, 20, 33 for the radius.
UNIT 03

3. Mission
3.2. How printing the circumference and area of the circle works

(‘Enter the radius :’))

(‘Radius of the circle’, radius)


(‘Area of the circle’, circum)
(‘Circumference of the circle’, area)

Enter the radius : 4.0


Radius of the circle 4.0
Area of the circle 50.24
Circumference of the circle 25.12
UNIT 03

3. Mission
3.3. Programming plan
Pseudocode Flow chart

Start
[1] Start

[2] Define value of PI as 3.14 Define PI = 3.14

[3] Take the radius value input Take radius value input

[4] Calculate circumference using the radius input value


Calculate circumference

[5] Calculate area using the radius input value


Calculate area
[6] Print the circumference and area on the screen
Print the circumference
[7] End and area.

End
UNIT 03

3. Mission
3.4. Printing the circumference and area of the circle: final code

(‘Enter the radius :’))

(‘Radius of the circle’, radius)


(‘Area of the circle’, circum)
(‘Circumference of the circle’, area)
UNIT 03

1. Numeric Data Types, Arithmetic and Division


1.1. Computation using numerical information
In programming, operations using numerical information and then using the data frequently occur.
For example, information such as a person's height and weight is expressed as numerical values such as 177cm
and 58kg.

Ex Addition operations of the numbers 100 and 20


can be performed by 100 + 20.
UNIT 03

1. Numeric Data Types, Arithmetic and Division


1.1. Computation using numerical information
Let’s learn the terms for arithmetic operation. Data values or variables subject to the operation are called operands.
The subject of the operation is called the operator. Take an example of an operation of 100 + 200.

100 20

Operand Operator Operand


UNIT 03

1. Numeric Data Types, Arithmetic and Division


1.2. Operators
The table below explains the operator of Python and the operation of the operator.

Operator Meaning Action


+ Addition Add the left operand and the right operand.
- Subtraction Subtract the right operand from the left operand.
* Multiplication Multiply the right operand from the left operand.
Divide the left operand into the right operand. Python's division basically returns
/ Division
the real number value.
Floor Unlike /, the result of division is used to discard the decimal point or less and obtain
//
Division(quotient) only the integer part.
It is read as a modulo operator and has nothing to do with the percentage that
% Remainder
means ratio. Finds the remainder of the division.
Multiply the left operand to the right operand. In the case of **0.5, a square root
** Power
operation is performed.
UNIT 03

1. Numeric Data Types, Arithmetic and Division


1.3. Example code using operator
Perform an operation using numerical data types. The operation may be performed using numerical data and operator
+, -, *, /, //, %.

# Find addition of numerical value of 100 and 20

# Find multiplication of numerical value of 100 and 20

# Find subtraction of numerical value of 100 and 20

# Divide numerical value of 100 with 20

# Divide numerical value of 100 with 20 and find quotient

# Divide numerical value of 100 with 20 and find quotient


UNIT 03

2. Object Data Types, Operator Priorities, and Data Type Conversion


2.1. Classification of data types
In Python, the distinction of data types is very important.
Characters and numbers have the same form, but their properties can be very different.
Ex The number 10 can be calculated. However, the letter "10" is impossible to calculate.

Depending on the data type, the available operators are different. In the following case, a grammar error occurs
because the string "10" is divided by 2.

TypeError

String 10 divided by number 2

# String 10 divided by number 2


UNIT 03

2. Object Data Types, Operator Priorities, and Data Type Conversion


2.1. Classification of data types
In Python, the operator applies differently depending on the data type.
The result of the multiplication (*) operation of the numbers 100 and 2 is 200.
However, the result of the multiplication (*) operation of the letters '100' and 2 is '100100'. In other words, the result of
the multiplication (*) operation of the letter ‘Hello’ and 2 is 'HelloHello', but the multiplication operation on the letter is
different from the multiplication operation on the numerical value.

# Find multiplication of numerical value 100 and 2

# Find multiplication of string ‘Hello’ and 2

# Find multiplication of string ‘100’ and 2


UNIT 03

2. Object Data Types, Operator Priorities, and Data Type Conversion


2.2. Basic data types in Python
The basic data types and examples of Python, which are widely used, are as follows.

Data Types Example

Integers(int) …, -3, -2, -1, 0, 1, 2, 3, ...

Real Number(float) 3.14, 4.28, 0.01, 123.432

String(str) 'Hello World', '123', "Hi"

Bool(bool) True, False


UNIT 03

2. Object Data Types, Operator Priorities, and Data Type Conversion


2.2. Basic data types in Python
Here are the important data structure of Python and types of variables. These will be used in coding.

Number Boolean String List Tuple Dictionary

int ex : ex : ‘hello’ ex : ex : ex :
True, False ‘100’ [10, 20, 30] (10, 20, 30) { ‘name’ : ‘David’,
ex : 10, 200 ‘age’ : 23,
‘height’ : 56.5 }

float
ex : 3.14

complex
ex : 4 + 3j
UNIT 03

2. Object Data Types, Operator Priorities, and Data Type Conversion


2.3. How to distinguish data types
The terms referring to numerical values, functions, and classes, which are components of the Python program, is
object.
The role of the operator differs depending on whether the object's data type is integer or string.
Type function returns the type of an object. Let's check the data type using the code below.

# Let you know data type of 100

# Let you know data type of 100 Numeric data type of 100 and 100.0 are different
from each other.

# Let you know data type of 100 Write complex number in form of x + y j.

# Complex number data type in the form of real + imaginary numbers like 10 + 3j
UNIT 03

2. Object Data Types, Operator Priorities, and Data Type Conversion


2.4. Precedence of operators
If the addition and multiplication operators appear in one sentence, the multiplication operation is performed first.
When parentheses appear in a sentence, the operators in parentheses are treated first.
The calculation results in the sentence vary according to the operator processing order.

# Multiplication is calculated first.

# Operator in parentheses is calculated first.


UNIT 03

2. Object Data Types, Operator Priorities, and Data Type Conversion


2.5. Operator precedence chart
Let’s look at Python operators and precedence. These are the contents to be learned in this lecture.

Operator Explanation
() parenthesis operator
** power operator
~,+,- monadic operator
* , / , % , // multiplication, division, remainder operator
+,- addition, subtraction
>> , << bitwise movement operator
The higher the table,
the higher the priority. & bitwise AND operator
^,| bitwise XOR operator, bit OR operator
<= , < , > , >= comparison operator
== , != equal operator
= , %= , /= , //= , -= , += , *= , **= assignment operator, complex assignment operator
is , is not identity operator
in , not in membership test operator
not , or , and logical operator
UNIT 03

2. Object Data Types, Operator Priorities, and Data Type Conversion


2.6. Data type conversion
Python data can be calculated by converting its data type. The string '10' can be int-type converted to int('10').
Therefore, int('10')/2 is executed without error.
In order to change the number 10 from the Python data to the string '10', str (10) is used. This converted string can be
written with the string as an addition operation.

# Convert string ‘10’ into integer and divide by 2.

# Convert number 10 into string and use + operator


UNIT 03
UNIT 03

3. String Application
3.1. Take a look at string
In Python, the string str is very suitable for displaying information in software.
All srt files can be converted to texts. However, as it is a text, it is impossible to apply arithmetic calculation.

Ex The user's name, ID, password, etc. may be expressed as a string.

Python's string is a form in which each letter is connected.


Addition and multiplication operations are possible for Python's strings.

String

T h i s i s a s t r i n g !

Character
UNIT 03

3. String Application
3.2. String operator +, *
Let's look at the operations + and * available in the string. The + operation of the string connects the two strings.
The * operation of the string must be an integer. That is, the string is generated by repeating the integer n.

# String can be added to strings.

# Generates string of ‘Python’ repeated 10 times

#Generates string of ‘*’ repeated 50 times

#String ‘100’ repeats 10 times

Focus The * operation of the string must be an integer. Otherwise, an error will occur.

TypeError
UNIT 03

TypeError

Addition of number and string causes an error.

"10" looks like a number, but since it is a character in the quotation m


ark, an error such as the above occurs.
Paper coding
Try to fully understand the basic concept before moving on to the next step.
Lack of understanding basic concepts will increase your burden in learning this
course, which may make you fail the course.
It may be difficult now, but for successful completion of this course we suggest you
to fully understand the concept and move on to the next step.
UNIT 03

Condition for
Execution

Time

Write the entire code and the expected output results in the note.
UNIT 03

Condition for
Execution

Time

Write the entire code and the expected output results in the note.
UNIT 03

1. Numeric Data Types, Arithmetic and Division


1.1. Arithmetic operation
UNIT 03

1. Numeric Data Types, Arithmetic and Division


1.1. Arithmetic operation
Find out arithmetic calculation through coding.

Line 1
• Calculate addition

Line 2
• Calculate subtraction
UNIT 03

1. Numeric Data Types, Arithmetic and Division


1.1. Arithmetic operation

Line 3
• Calculate multiplication
Line 4
• Floor Division(quotient): it returns 1, which is the quotient of dividing 5 by 3.
UNIT 03

1. Numeric Data Types, Arithmetic and Division


1.2. Power, remainder

Line 1 ~ 2
• 1: Power, 210 is performed to return 1024.
• 2: It is called modulo. It returns the remainder of 9 divided by 5 which is 4.
UNIT 03

1. Numeric Data Types, Arithmetic and Division


1.3. Mixed operation

Line 1 ~ 2
• 1: Number operations have the same precedence as general arithmetic operations. In other words,
multiplication and division are performed before addition.
• 2: If there is a parenthesis, it is calculated first.
UNIT 03

1. Numeric Data Types, Arithmetic and Division


1.4. Complex number operation
# Addition of complex numbers

2 # Subtraction of complex numbers

3 # Multiplication of complex numbers

4 # Division of complex numbers

Line 1 ~ 4
• Addition, subtraction, multiplication, and division of complex numbers
UNIT 03

2. Object Data Types, Operator Priorities, and Data Type Conversion


2.1. Identifying and converting data types
Identifying and converting a certain value of data type is a very important issue.

int(“10”) # Convert string “10” to integer 10

Focus The data type is critical because the operator to be used varies depending on the data type.
집중
UNIT 03

2. Object Data Types, Operator Priorities, and Data Type Conversion


2.1. Identifying and converting data types
Find out data types using type built-in functions

Line 1
• When a number (integer) is an input, it is marked as int.
Line 2
• When a string is an input, it is marked as str(string).
UNIT 03

2. Object Data Types, Operator Priorities, and Data Type Conversion


2.1. Identifying and converting data types
Find out data types using type built-in functions

Line 3
• When a number (real number) with decimal points is an input, it is marked as float.
UNIT 03

# Cell output is int

# Cell output is <class ‘int’>


UNIT 03

2. Object Data Types, Operator Priorities, and Data Type Conversion


2.2. How to convert a data type

Line 1 ~ 2
• 1: Use the int function to replace letters with numbers.
• 2: Since the string "50" has been changed to an integer by int ("50"), +20 operation is performed.
UNIT 03

2. Object Data Types, Operator Priorities, and Data Type Conversion


2.2. How to convert a data type

Line 3 ~ 4
• 3: To replace numbers with letters, use the str function.
• 4: Use the float function to replace the letter with a real number.
UNIT 03

3. Strings and Operators


3.1. Addition and Multiplication Operators of String
The string may use operators such as addition and multiplication. Subtraction and division operators cannot be used.

Line 1
• String cannot be subtracted, but it can be added. Two strings can be added together to connect.
UNIT 03

3. Strings and Operators


3.1. Addition and Multiplication Operators of String
Find out the addition and multiplication operators of strings.

Line 2
• When a string is multiplied by an integer, the string repeats. Here, 'repeat' is repeated 10 times.
• However, division and subtraction do not work.
UNIT 03

3. Strings and Operators


3.2. Single and Double Quotation Marks
When printing a string, the same result is obtained whether using single quotes such as 'Hello Python!!' or double
quotes such as “Hello Python!!”.

Line 1 ~ 2
• The strings "~~" and "~~" show the same output result.
UNIT 03

3. Strings and Operators


3.3. Using comma
When a string is to be an output, string and numerical value is printed using a comma.

Line 1 ~ 2
• String and numerical values were printed using commas.
• The comma automatically adds a space when outputting.
UNIT 03

3. Strings and Operators


3.4. Escape sequence
Escape sequence: \" or \" may be used to output double or small quotes on the screen.

Line 1 ~ 2
• String should be enclosed in double or double quotes.
• Therefore, it is difficult to indicate quotation marks. In this case, you can use \" or \".
• An escape sequence refers to a special character used to control a computer, and since a double quote or a
single quote is defined for defining a string, it is output using the control character \' or \' to output it.
UNIT 03

3. Strings and Operators


3.4. Escape sequence
Escape sequence: \n is used to change lines.

Line 1
• <Inverse Slash+Character> is used to display special characters such as line change. \n is a line-switching
character, and \t is a tap character.
UNIT 03

3. Strings and Operators


3.4. Escape sequence
Escape sequence: \t is used when a tap character is to be input.

Line 1
• When entering a tap character in the middle of a sentence, enter \t at the corresponding location.
UNIT 03

3. Strings and Operators


3.4. Escape sequence
Escape sequence: \t is used when a tap character is to be input.

Line 1
• When entering a tap character in the start of a sentence, enter \t as a first output character.
UNIT 03

3. Strings and Operators


3.5. String indexing
String indexing: String indexing may be used to obtain only some of the long strings. Use large brackets [] and
numbers.

Line 1
• String indexing starts from 0.
• That is, when zero is indexed, h, which is the first letter of "hello", is indexed.
Line 2
• When 2 is used as an index in string indexing, you can see that the third letter l is indexed.
UNIT 03

3. Strings and Operators


3.6. Negative string indexing
String indexing: String indexing may be used to obtain only some of the long strings. Use large brackets [] and
numbers.

Line 1
• Python supports negative indexing, and when indexing -1, the last character is indexed.
UNIT 03

3. Strings and Operators


3.6. Negative string indexing
String indexing: String indexing may be used to obtain only some of the long strings. It will be covered in detail later.

Line 1
• Python supports negative indexing, and when indexing -5, the very first character is indexed.
UNIT 03

3. Strings and Operators


3.6. Negative string indexing
Pay attention to the range of indexing.

Line 1
• The string, 'hello’ has 5 characters. Therefore indexing range is from 0 to 4.
caution: index that is out of the range prints error.
UNIT 03
UNIT 03
UNIT 03

Output Example
Unit learning objective (1/3) UNIT 04
Unit learning objective (2/3) UNIT 04
Unit learning objective (3/3) UNIT 04

Reserved Assignment
Variable
Keywords Operator

Compound Arithmetic
Assignment Operator Operator
UNIT 04

1.1. Social issue of obesity

‣ Its precision, however, is questionable as the body fat percentage is measured without professional equipment.
‣ What’s more, the BMI standard is set by the insurance industry and not by the doctors or scientists.
‣ The BMI’s origin comes from 1895, as Metropolitan (now MetLife), reportedly made a height to weight chart with the
records of their client’s height, age, and weight.
UNIT 04

1.2. What is the BMI?


UNIT 04

1.3. WHO BMI Standard Chart


UNIT 04

2.1. What is a BMI CALCULATOR?


UNIT 04

2.2. How the BMI CALCULATOR works

("Enter name: ")


("Enter height(cm): ")

("Enter weight(kg): ")

"'s BMI is", bmi.")

Enter name” David


Enter height(cm): 170
Enter weight(kg): 70
David’s BMI is 24.221453287197235.
UNIT 04

2.3. Programming plan


Pseudocode Flowchart
Start
[1] Start
name = input()
[2] Enter Name

[3] Enter Height (cm) height_cm = input()

[4] Convert the unit of height from (cm) to (m) height_m = height_cm / 100

[5] Enter Weight (kg)


weight = input()
[6] Calculate for BMI
BMI = weight / (height_m ** 2)
[7] Print the result on monitor
Print the result on monitor
[8] End

End
UNIT 04

2.4. BMI CALCULATOR final code

("Enter name: ")


("Enter height(cm): ")

("Enter weight(kg): ")

"'s BMI is", bmi.")


UNIT 04

1.1. What is a variable

During programming, a single mistake in multiple value conversions can result in an error.
The use of variables can simplify this process.

New
Value

Value

‣ Variables are a key concept in programming.


‣ Variables are used to store certain values
within the computer.

The value inside the box can be changed constantly. It is best to understand this value as data.
This data can hold a single value, such as weight = 78.7, and it can also hold one or more values like
person = (’David’, 78.7).
UNIT 04

1.2. Grammar of variable declarations

Line 1, 2
• When the code is executed, a variable with the name “weight” is created in the memory and the value 78.7 is stored.
• In the variable “person”, the values (‘David’, 78.7) are stored. (These types of data are called Tuples).
• The ‘=’ in the code above does not mean ‘equal’, but ‘to save the value on the right with the name (weight) on the left.’
This operator ‘=’ is called an assignment operator.
UNIT 04

1.2. Grammar of variable declarations


Focus Assigning and recalling values in variables minimizes errors and makes editing programs much easier.

('Radius of Circle', radius)


('Area of Circle', 3.14 * radius * radius)
('Circumference of Circle', 2.0 * 3.14 * radius)

Radius of Circle 4.0


Area of Circle 50.24
Circumference of Circle 25.12
UNIT 04

1.2. Grammar of variable declarations

‣ Identifiers must be written with the following rules.


UNIT 04

1.3. Variable declarations and Identifiers

#Identifier to differentiate the width of the rectangle from other data


#Identifier to differentiate the height of the rectangle from other data

Line 1, 2
• Using the “width” and “height” identifiers, we can differentiate the width and height of the rectangle
from other data.
UNIT 04

1.4. Python Keywords

Python’s Built-In Keywords which cannot be used as identifiers

False class return is finally None

if for lambda continue True def

from while nonlocal and del global

not with as elif try or

yield assert else import pass break

except in raise
UNIT 04

1.4. Python Keywords

SyntaxError
UNIT 04

1.5. Tips for Python Keywords


TIP

# Search for Python Keywords


UNIT 04

It’s more comprehensible to name weight and height as “weight” and ”height”, rather than x1 and x2.
UNIT 04

Memory space

Provide storage space


in memory

Main Memory Memory space

Assign name to memory


space

Main Memory Memory space


5.0

radius = Assigning value of variable to 5.0


UNIT 04

1.6. String
UNIT 04

1.6. String

The data in String Data Types are formed out of text.


s1
H e l l o W o r l d !
UNIT 04

1.6. String
UNIT 04

1.7. Python Data Type

Data Type

‣ A Data Type is a type of data that can be processed in programming languages.


‣ Basic Data Types include Booleans, Numbers (Integers, Real Numbers, Complex Numbers), Strings, Lists,
Tuples, Sets, and Dictionaries.
‣ The type() function allows one to check the data type of an object.
UNIT 04

1.7. Python Data Type


UNIT 04

Static typing Dynamic typing

- Examines data types at compilation - Each type of data does not need specification,
- Each type of data needs to be specified resulting in simple codes.
- Languages: C, C++, C#, JAVA, Objective-C, PASCAL - May result in data type errors during execution
etc. - Languages: Python, Basic, Ruby, PHP, JavaScript etc.
UNIT 04

1.8. Assignment operator in Python

Take a look at this expression ‘result = 100 +200’.


This expression means that we assign the value on the right to the variable on the left.

300

100 200

The ‘=‘ sign in the code ‘RESULT = 100+200’ does not mean ‘equal’. It means ‘to store the value on the right
of the = operator in the variable result on the left of =.
This ‘= ‘ operator is called the assignment operator.
UNIT 04

2.1. Python simultaneous assignment


Focus As shown in the expression x, y = 100, 200, it is possible to assign multiple variables to values in one line
simultaneously. This is called simultaneous assignment.
UNIT 04

2.2. Python multiple assignment

Line 1
• 200 is assigned to num1, num2, and num3. The order of assignment starts from the right as shown
below.

1
2 3
200
num3 num2 num1

The order of assignment is as shown above.


UNIT 04

2.3. Equal sign in Python

The equal sign does not mean that two values are equal.
UNIT 04

3.1. A variety of compound Assignment Operators in Python

Compound Assignment Operators


Operator Description Example

+= Combination of the Addition Operator and the Simple Assignment Operator i+=10

-= Combination of the Subtraction Operator and the Simple Assignment Operator i-=10

*= Combination of the Multiplication Operator and the Simple Assignment Operator i*=10

/= Combination of the Division Operator and the Simple Assignment Operator i/=10

^= Combination of the Bitwise XOR(^) Operator and the Simple Assignment Operator i^=10

%= Combination of the Modulo Operator and the Simple Assignment Operator i%=10
UNIT 04

3.1. A variety of compound Assignment Operators in Python


Focus It’s important to know Compound Assignment Operators.
You may not be able to read and understand someone else’s code if you do not know any of the Compound
Assignment Operators.
UNIT 04

4.1. Arithmetic operators in Python

Proper numerical expressions can increase calculation efficiency and code simplification.

In an expression such as a = 10 + 1, the 10+1 on the right side of the equal sign is the evaluation value. This
value is calculated and assigned to a. Such arithmetic operated by the Arithmetic Operator and assigned
to a variable is very common.

a = 10+1
11

a = 10+1 = 11
UNIT 04

4.2. How do arithmetic operators work?

Operator Meaning Operation

+ Addition Add the left operand and the right operand

- Subtraction Subtract the right operand from the left operand

* Multiplication Multiply the left operand and the right operand

Divide the left operand by the right operand


/ Real Division
Division in Python will return real values by default

Unlike the /, the Integer Division is used to discard the decimal point
// Integer Division(Quotient)
of the quotient and only obtain the integer

Read as Modulo Operator. Irrelevant of percentage or ratio. Returns


% Remainder/Modulo
the remainders of division.

** Exponentiation Multiply the left operand to the power of the right operand
UNIT 04

4.2. How do arithmetic operators work?

Operator Sign Example Value Result

Addition + 7+4 11

Subtraction - 7–4 3

Multiplication * 7*4 28

Real Division / 7/4 1.75


Integer Division
// 7 // 4 1
(Quotient)
Modulo % 7%4 3

Exponentiation ** 7 ** 2 49
UNIT 04

4.2. How do arithmetic operators work?


Focus Let’s take a look at what data type values each variable receives and how it is calculated using that variable.
The following code converts the input value into a float data type. Int(input(‘…’) is used when converting into
an integer type.

("Enter weight in kg: "))


("Enter height in m: "))

("Your BMI=", bmi)

Enter weight in kg: 70


Enter height in m: 1.75
Your BMI= 22.857142857142858
UNIT 04

4.3. input function of Python and arithmetic operators

※ Won is the Korea currency.

("Money Paid : "))


("Price of Item : "))

("Amount of Change : ", change)

("Pieces of 500 won coins: ", coin500s)


("Pieces of 100 won coins: ", coin100s)
Money Paid: 5000
Price of Item: 300
Amount of Change: 4700
Pieces of 500 won coins :9
Pieces of 100 won coins: 2

Line 1-2
• Receive the amount of money and price from the user and convert them into the int type.
• After that, the problem can be solved by integer operation.
UNIT 04

4.3. input function of Python and arithmetic operators

("Money Paid : "))


("Price of Item : "))

("Amount of Change : ", change)

("Pieces of 500 won coins: ", coin500s)


("Pieces of 100 won coins: ", coin100s)
Money Paid: 5000
Price of Item: 300
Amount of Change: 4700
Pieces of 500 won coins :9
Pieces of 100 won coins: 2

Line 4-8
• The value for change is money – price.
• In coin500s, the change is divided by 500 and then stored.
UNIT 04

4.3. input function of Python and arithmetic operators

("Money Paid : "))


("Price of Item : "))

("Amount of Change : ", change)

("Pieces of 500 won coins: ", coin500s)


("Pieces of 100 won coins: ", coin100s)
Money Paid: 5000
Price of Item: 300
Amount of Change: 4700
Pieces of 500 won coins :9
Pieces of 100 won coins: 2

Line 4-8
• Put the remainder of the change divided by 500 in change.
• In coin100s, change is divided by 100 then stored.
UNIT 04

4.4. Caution for using arithmetic operators


Using the wrong equation will result in an error.
Try to fully understand the basic concept before moving on to the next step.
Lack of understanding basic concepts will increase your burden in learning this
course, which may make you fail the course.
It may be difficult now, but for successful completion of this course we suggest you
to fully understand the concept and move on to the next step.
UNIT 04

Conditions
for Execution

Time

Write the entire code and the expected output results in the note.
UNIT 04

Conditions
for Execution

Time

The Pythagorean
Theorem

Write the entire code and the expected output results in the note.
UNIT 04

1.1. Using input function

("Enter Name: ")


("Hello", name)
("Welcome to the World of Python Programming.")
UNIT 04

1.1. Using input function

("Enter Name: ")


("Hello", name.)
("Welcome to the World of Python Programming.")

Enter Name: David


Hello, David.
Welcome to the World of Python Programming.
UNIT 04

1.2. Receiving Integers From Users

‣ In the addition program learned earlier, the result of 100+200 was always printed.
‣ It will be a more useful program to input two integers, add them, and then print out the results.

("Enter the first integer: "))


("Enter the second integer: "))

("The sum of," x, "and" y, "is", s)

Enter the first integer: 300


Enter the second integer: 400
The sum of 300 and 400 is 700

‣ The input() function is used to input integers. However, the input() function always returns the input in the form of
a string. Therefore, the string “300” is returned.
‣ In order to convert the string “300” into an integer 300, the return vale of the input() function must be enclosed in
int(). The int() function converts the string into an integer.
UNIT 04

1.2. Receiving Integers From Users

Watch Out For the ValueError

#If the characters “hundred” are entered, the int() function fails to convert it into an integer and will print an error.
("Enter the first integer: "))
("Enter the second integer: "))

("The sum of," x, "and" y, "is", s)

Enter the first integer: hundred

ValueError Traceback (most recent call last)


<ipython-input-2-611617428447> in <module>
#If the characters “hundred” are entered, the int() function fails to convert it into an integer and will print an error.
x = int(input("Enter the first integer: "))
y = int(input("Enter the second integer: "))
s = x + y
print("The sum of," x, "and" y, "is", s)

ValueError: invalid literal for int() with base 10: 'hundred'


UNIT 04

("Enter the first integer: ")


('Input Data Type: ', type(x))

Enter the first integer: 100


Input Data Type: <class 'str'>

# Let’s check whether x is only a number.

('Input Data Type: ', type(x))

(‘x is not a number type.')

Input Data Type: <class ‘int'>


UNIT 04

2.1. Using variables for efficient programming

'David
Doe'
radius = 4.0
name = input(‘input your name ’)
UNIT 04

2.1. Using variables for efficient programming

'David
Doe'
UNIT 04

2.1. Using variables for efficient programming

('Radius of Circle', radius)


('Area of Circle', 3.14 * radius * radius)
('Circumference of Circle', 2.0 * 3.14 * radius)

Radius of Circle 4.0


Area of Circle 50.24
Circumference of Circle 25.12
UNIT 04

2.2. Variable and data type

‣ Each variable must secure sufficient space in memory to represent its value.
‣ In order to determine the amount of space needed and read/write values in that space, the data type must be
determined. There is no need, however, to specify the type as Python determines the most suitable type on its own.
UNIT 04

2.3. Caution for TypeError when using variables

TypeError
UNIT 04
UNIT 04
UNIT 04

Example Enter the radius of a circle: 11


Result Circumference of a circle= 69.115024, Area of a circle= 280.132632

‣ Circumference of a circle: 2 * radius * PI


‣ Area(Surface) of a circle: PI * radius * radius
‣ Study the area and circumference of a circle before moving forward.
UNIT 04

Example
Result
Unit learning objective (1/3) UNIT 05
Unit learning objective (2/3) UNIT 05
Unit learning objective (3/3) UNIT 05

Boolean Comparison Logical


Data Types Operator Operator
UNIT 05

1.1. Origin of leap year

February February

28 vs.
29
UNIT 05

1.2. Rules of Leap Years for the Leap Year Calculator


UNIT 05

1.3. What is a Leap Year Calculator?


UNIT 05

1.4. Leap year and Gregorian calendar


UNIT 05

2.1. How the Leap Year Calculator Works

("Enter the year: "))

Enter the year: 2021


False
UNIT 05

2.2. Programming plan

Pseudocode Flowchart

[1] Start Start

[2] Enter the year years = input()


[3] Use the leap year formula to determine whether it is
true or false. The formula is (year % 4 ==0 and year % (year % 4 ==0 and year % 100 != 0)
100 != 0) or year % 400 == 0 or year % 400 == 0

[4] If any of them is false, it will print False. Print the result on monitor

[5] End End


UNIT 05

2.3. Leap year calculation final code

("Enter the year: "))


UNIT 05

1.1. Comparison operator

Comparison Operator takes the result of the comparison operation of numerical data, such as “greater than” or
“less than,” and returns it as True or False.
UNIT 05

1.1. Comparison operator

('Result of 10 > 5: ', 10 > 5)


('Result of 5 < 1: ', 5 > 1)
('Result of 5 == 5: ', 5 == 5)
('Result of 5 != 5: ', 5 != 5)
("Result of 'a' > 'b': ", 'a' > 'b')

Result of 10 > 5: True


Result of 5 < 1: False
Result of 5 == 5: True
Result of 5 != 5: False
Result of 'a' > 'b‘: False
UNIT 05

1.2. Boolean data type


UNIT 05

‣ First, the number 0, when converted into a Boolean type, becomes False. All the other numbers except 0, when
converted into a Boolean type, become True.
‣ White spaces such as ‘ ‘ are returned as False in Boolean. All other characters besides the white space are returned
as True.
‣ None is a keyword that means there is no value.
‣ [ ] is an object called a list. If there is no value in this object, it is returned as False.
UNIT 05

1.3. Description about comparison operators

== If two operands have the same value, return True a == b is False

!= If two operands have different values, return True a != b is True

> If the left operand is greater than the right operand, return True a > b is False

< If the left operand is less than the right operand, return True a < b is True

>= If the left operand is greater than or equal to the right operand, return True a >= b is False

<= If the left operand is less than or equal to the right operand, return True a <= b is True
UNIT 05

1.4. Code examples of comparison operators


Focus The returned values are Boolean values when comparison operators have been applied.
UNIT 05

1.4. Code examples of comparison operators

('Enter the integer: '))


('Is the integer even?', n % 2 == 0)
Enter the integer: 60
Is the integer even? True

Line 2
• If the remainder divided by 2 is 0, return True; if not, return False.
UNIT 05

1.5. String and comparison operators

Line 1-2
• The first line returns True because the two strings are completely equal.
• The second line returns False because the two strings are not equal.
UNIT 05

1.5. String and comparison operators

Lines 3-4
• The third line returns False because the two strings match completely.
• The fourth line returns True because the two strings do not match.
UNIT 05

1.6. Difference between == and is

Line 3-4
• The third line uses the == operator to check to see whether the two values are equal. The two values are equal,
so True is returned.
• The fourth line asks whether the two objects are the same. Since a is an integer while b is a real number, the
two objects are not the same. In other words, they are stored in different memories, and therefore, False is
returned.
UNIT 05
UNIT 05

('n is between 0 and 200.')

n = 100
n is between 0 and 200.
UNIT 05

1.7. Caution when using comparison operators


An error can occur when the order of operators is changed.
UNIT 05

2.1. Logical operators : and, or, not

Logical Operators determine logical expressions and return True or False as results.

x and y x or y not x

False False False False False False False True

False True False False True True True False

True False False True False True

True True True True True True

x x
x and y x or y x not x
y y

This figure above is a symbol for logical gates widely used in electric engineering and computers science.
Each is a symbol that means and, or, and not, respectively.
UNIT 05

2.1. Logical operators : and, or, not

x and y If any one of x or y is False, then it is False. It is True only when all of them are True.

x or y If any one of x or y is True, then it is True. It is False only when all of them are False.

not x If x is True, it is False. If x is False, it is True.

Focus When logical operators are applied, the results are returned in Boolean types.
UNIT 05

2.1. Logical operators : and, or, not

('Enter an Integer: '))

('Is the input an even integer between 0 and 100?', result)

Enter an Integer: 99
Is the input an even integer between 0 and 100? False

Line 2
• num is greater than 0 but less than 100, so the first and second equations return True.
• In the third equation, num has a remainder of 1, so 1==0 is returned as False.
• The and logical operator returns True when all values are True; therefore, it returns False.
UNIT 05

2.2. Comparison of ‘and’ to ‘or’

When using the logical operator “and”, the output value is affected by a False input. It returns True if both
statements are true.
If any of the switches is OFF, then the bulb is off (False). and
Input
OFF ON Output
A B
A B True True True
True False False
False True False
False False False
UNIT 05

2.2. Comparison of ‘and’ to ‘or’

When using the logical operator “or”, the output value is affected by a True input. It returns True if one of the
statements is true.
If any of the switches is ON, then the bulb is on (True) or

ON
Input
Output
A A B
True True True
OFF True False True
B False True True
False False False
Try to fully understand the basic concept before moving on to the next step.
Lack of understanding basic concepts will increase your burden in learning this
course, which may make you fail the course.
It may be difficult now, but for successful completion of this course we suggest you
to fully understand the concept and move on to the next step.
UNIT 05

Enter an Integer : 20
Conditions Is the integer odd?: : False
for Execution
Enter an Integer : 21
Is the integer odd?: True

Time

Write the entire code and the expected output results in the note.
UNIT 05

Conditions Enter an integer: 12


for Execution
Is the input an even integer between 0 and 100? False

Time

Write the entire code and the expected output results in the note.
UNIT 05

1.1. AND, OR, NOT return true/false values


UNIT 05

1.1. AND, OR, NOT return true/false values

# 10 is less than 20, so 10 > 20 is False


# 10 is less than 20, so 10 < 20 is True
# 9 is not 0, so it is True
# -1 too is not 0, so it is True
# 0 is the only number value that is False
# None means there is no value, so it is False
# White space is a string, so it is False
# It holds string values, so it is True
UNIT 05

1.2. bool function returns true/false values


UNIT 05

1.3. logical operators return true/false values

Logical operators in Python


UNIT 05

1.4. Truth table

x and y x or y not x

False False False False


False True
False True False True

True False
UNIT 05

Symbol Truth Table


B A Q
A 0 0 0
Q
B
0 1 0
A B 1 0 0
+6 Q
1 1 1
B A Q
A
Q 0 0 0
B
0 1 1
A
1 0 1
B Q
1 1 1
UNIT 05

2.1. Precedence of Python Operators

𝑥+𝑦×𝑧 (𝑥 + 𝑦) × 𝑧
① ①

② ②
UNIT 05

2.2. Operator precedence table

** Exponentiation Operator
~,+,- Unary Operator
* , / , % , // Multiplication, Division, Modulo Operator
+, - Addition, Subtraction
>> , << Bitwise Operator
& Bitwise AND Operator
^,| Bitwise XOR, Bitwise OR Operator
<= , < , > , >= Comparison Operator
== , != Equality Operator
= , %= , /= , //= , -= , += , *= , **= Assignment Operator, Compound Assignment Operator
is , is not Identity Operator
in , not in Containment Operator
not , or , and Logical Operator

‣ The higher the position of the operator on the table, the higher its precedence
UNIT 05

2.3. Code examples of operator precedence

("Enter the First Equation: "))


("Enter the Second Equation: "))
("Enter the Third Equation: "))

("Average =", avg)

Enter the First Equation: 10


Enter the Second Equation: 20
Enter the Third Equation: 30
Average = 20.0

Line 5
• If we code x + y + z /3, then it will calculate z/3 first. Therefore, we need to add it in parentheses first, such as (x
+ y + z) /3
• Just like the formula used in math class, the values in parentheses have a higher precedence.
UNIT 05
UNIT 05
UNIT 05

Example Enter a 3-digit integer: 321


Result True

‣ Hint: You must be familiar with the // operator. If not, please go back and review it.
UNIT 05

Example Enter an integer: 125


Result True
Unit learning objective (1/3) UNIT 06
Unit learning objective (2/3) UNIT 06
Unit learning objective (3/3) UNIT 06

Sequential Conditional if
Statement Statement Statement

Boolean Conditional
Data Type Expression
UNIT 06

1.1. What is lottery?


UNIT 06

1.2 Lottery simulation with 3 integers


UNIT 06

1.3. History of lottery


UNIT 06

1.4. Various lottery systems


UNIT 06

1.5. Lottery number recommendation system website

1 2 Select country
Access the website
https://www.random
.org/quick-pick/

The site that predicts


lottery numbers.
UNIT 06

1.5. Lottery number recommendation system website

4 Shows any number recommended by this system.


3 Select type of the lottery
UNIT 06

2.1. How the lottery machine works

('Enter a three-digit lottery number : ').split()

# If one of the numbers match the winning number


#Increase n

# If n is 3, three numbers matched


('You won the lottery!')

Enter a three-digit lottery number :


You won the lottery!
UNIT 06

2.2. Mechanism of automatic lottery machine

('Enter a three-digit lottery number : ').split()

# If one of the numbers match the winning number


#Increase n

# If n is 3, three numbers matched


('You won the lottery!')

Enter a three-digit lottery number : 1, 2, 9


UNIT 06

2.3. Programming Plan


Start

[1] Start initialize n1=2, n2=3, n3=9

[2] Generate three numbers, 2, 3, 9. a, b, c = input()

[3] Reset with n = 0. if a == n1 or a == n2 or


a == n3:
[4] Receive input for three numbers a, b, c.
n += 1
[5] if a matches one of 2, 3, 9, then {
if b == n1 or b == n2 or
[6] Add 1 to n } b == n3:

[4] if b matches one of 2, 3, 9 then { n += 1

[8] Add 1 to n } if c == n1 or c == n2 or
c == n3:
[9] if c matches one of 2, 3, 9 then {
n += 1
[10] Add 1 to n }
if n == 3
[11] if n is 3, print ‘You won the lottery!’
print ‘You won the lottery’
[12] End
End
UNIT 06

2.4. Automatic lottery machine final code

('Enter a three-digit lottery number : ').split()

# If one of the numbers match the winning number


#Increase n

# If n is 3, three numbers matched


('You won the lottery!')
UNIT 06

1.1 Conditional statements that have different flows depending on the


conditions
UNIT 06

1.2. Basic control structures of a program

‣ Sequence - a structure in which commands are executed sequentially.


‣ Selection - a structure in which one of several instructions is selected and executed.
‣ Iteration - a structure in which the same command is executed repeatedly.

순차구조
Sequence 선택구조
Selection 반복구조
Iteration

거짓
False 거짓
False


True 참
True
UNIT 06

1.2. Basic control structures

‣ The Sequence can be considered as a road through


which a car goes straight as shown in Figure 1.
‣ The Selection is an intersection where a car selects
one of the two roads and drives, as shown in Figure 2.
‣ The iteration as shown in Figure 3, can be said to be a
roundabout where the vehicle rotates and travels.
This structure can iterate a statement multiple
times.

<Figure 1> < Figure 2> < Figure 3>


UNIT 06

1.3. Sequential statements

# 100 is printed
# 100 is added to num and 200 is printed
# 100 is added again to num and 300 is printed

100
num = 100 num + 100

200
num = num + 100 num + 100

300
num = num + 100 num

A structure in which commands are executed sequentially


UNIT 06

1.4. Sequential statements and various flow statements

‣ Conditional statement : if statement, if-else statement, if-elif-else statement


‣ Loop statement : for statement, while statement
‣ Commands that change the flow of a loop statement : break, continue
UNIT 06

1.5. Why we need a selection structure

‣ At some stages of the program, there are more than one paths to proceed, among which we have to select one.
‣ If there is no selection structure, the program will always repeat the same action. If the program always does the
same thing, it will always reach a fixed conclusion.
UNIT 06

1.6. Flow of conditional statement

How can we choose to run only one of several executable statements? Let's express this in a flowchart.

A figure showing such flow of


tasks is called a branch.
True False
Conditional
Statement

Executable Executable
statement 1 statement 2

• <Executable Statement 1> or <Executable Statement 2> is executed according to specific conditions.
• Conditions are determined by <Conditional Statement>. The conditional statement must have a True or False value.
UNIT 06

1.7. If statement and related terms that are executed in specific circumstances

Situation 1: print "youth discount" if the age is under 20.


Situation 2: print "goal achieved" if step count over 1,000.

‣ Implementing this code requires an expression that determines whether the condition is satisfied or not.
‣ This is called a conditional expression. And this conditional expression is evaluated in Boolean type, which contains
True or False values.
‣ The relational operator from the previous chapter is used to compare two operands, and the result of the relational
operator is shown in True or False value. Thus, it can be used in conditional expressions.
UNIT 06

1.8. if statement syntax

if keyword Conditional statement colon

if ` :

indent block executed when a condition is true

Situation 1 : Situation 2 : ‣ (Situation 1) - In the conditional sentence that appears


print "youth discount" if print "goal achieved" if before the colon (:), print ('youth discount') is executed
the age is under 20 step count(walk_count) is
only when the age is less than 20 years old using
over 1,000.
< operator.
‣ (Situation 2) - In the conditional sentence, use the >=
if age < 20 : if walk_count >= 1000 : operator to execute a code, print ('goal achievement'),
print(‘youth discount') print(‘goal achieved') when the walk_count reaches 1,000 or more.
UNIT 06

1.9. if statement example code

# if age is 18
# result of age < 20 is True
('youth discount')
youth discount

‣ When the age value is 18, the conditional statement of age <20 becomes True,
so 'youth discount' is printed on the screen.
‣ When the age value is 20 or more, no output is printed.
False
age < 20

True

print(‘youth discount’)
UNIT 06

1.9. if statement example code


Example of converting to a different flow according to the value of the age variable

18 24

age age

False False
age < 20 age < 20

True True
print(‘youth print(‘youth
discount’) discount’)

# if age is 18 # if age is 24
# result of age < 20 is True # result of age < 20 is False
('youth discount') ('youth discount')
youth discount
UNIT 06

1.10. Block of if statement


Conditional statement and block

‣ Learn the necessity of indentation and the term block.


‣ The code below prints an error.

('youth discount')

('youth discount')

‣ A chunk of code that can be executed when a condition is true is called a block.
‣ The conditional block of a conditional statement must be indented. Otherwise, an error occurs as above.
UNIT 06

1.11. Indentation
Focus Python is a programming language in which indentation is significant. Depending on the indentation, the
same code produces different results. Let's take a closer look at the output from indented codes from 1 to 5.

‣ [Indentation code 1] If the conditions of age <20 is satisfied

('youth discount')
('Welcome')
youth discount
Welcome
‣ [Indentation code 2] If the conditions of age <20 is not satisfied

('youth discount')
('Welcome')
Welcome
UNIT 06

1.11. Indentation
‣ [Indentation code 3] If the condition ‘age <20’ is satisfied

('age', age)
('youth welcome')
('youth discount')

Age 18
youth welcome
youth discount

Line 3-5
• Since age is 18, age <20 is True and Line 3-5 are printed.
UNIT 06

1.11. Indentation
‣ [Indentation code 4] If the condition age <20 is not satisfied
24
('age', age)
('youth welcome')
('youth discount')

No output

Line 3-5
• Since the age is 24, age <20 is False and Line 3-5 are not printed.
UNIT 06

Wrong Indentation

('age', age)
('youth welcome')
('youth discount')

('youth welcome')
UNIT 06

('youth discount')

youth discount
t

('youth discount')
youth discount
UNIT 06

2.1. Code to verify if a number is a multiple of 3

('Enter an integer: ')) # Change input value to integer type

'is a multiple of 3.')


Enter an integer : 6
6 is a multiple of 3.

Line 2
• If the number is divided by 3 and the remainder is all 0, line 3 is executed (If the value of module 3 is 0, it's a
multiple of 3)
• In this way, it is possible to determine whether the number is a multiple of 3.
UNIT 06

2.2. Code to verify if a number is a multiple of 3 and 5

('Enter an integer: '))

'is a multiple of 3 and 5.')

Enter an integer : 15
15 is a multiple of 3 and 5.

Line 2, 5
• If the remainder is zero when the number is divided by 3, and the remainder is zero when divided by 5, line 3 is
executed.
• In this way, it is possible to determine whether the number is a multiple of 3 as well as 5.
UNIT 06

2.3. == operator

('ID matches.')

Enter your id: david


ID matches.

Line 2, 5
• If the string input is 'david', the two strings s and my_id match, and Line 5 is executed. When another string is
given, Line 5 is not executed.
UNIT 06

3.1. Even-number discrimination scenario

("Enter an integer : "))

"is an even number.")

Enter an integer : 50
n = 50
50 is an even number.

Line 3
• Checks if the remainder is 0 when the input n is divided by 2. If the input value is 50, the equation is True, so
line 4 is executed.
UNIT 06

3.2. Scenario verifying if two strings match

('Two strings match.')

('Two strings are different.')

Two strings are different.

Line 3
• Runs Line 4 block if the two strings are identical. In this case, it is not printed since the values of str1 and str2
are different.
UNIT 06

3.2. Scenario verifying if two strings match

('Two strings match.')

('Two strings are different.')

Two strings are different.

Line 5
• If the values of the two strings are different, Line 6 block is executed. In this case, it is printed because the
values of str1 and str2 are different.
UNIT 06

4.1. Role of pass statement

('Even number')

Even number

Line 5
• It leaves a block empty to complete the functionality later.
UNIT 06

4.1. Role of pass statement

Line 4
• func function does not do anything because there is no code inside the func() function.
UNIT 06

4.2. pass statement’s role


pass statement plays an important role.

‣ Although it does not have a functionality, the pass statement plays a role as a placeholder.
‣ Therefore, if the pass statement is omitted inside the function in the above sentence, an error occurs.
UNIT 06

def func_name(x1, x2, ... ) : t def func_name(x1, x2, ... ) :


code1 pass
code2
… A function with no body constructed
return n1[, n2,…]

The general form of a function


Try to fully understand the basic concept before moving on to the next step.
Lack of understanding basic concepts will increase your burden in learning this
course, which may make you fail the course.
It may be difficult now, but for successful completion of this course we suggest you
to fully understand the concept and move on to the next step.
UNIT 06

Enter game score : 1500


game_score = 1500
You are a master.
Example Output or
Enter game score : 100
game_score = 100

Time

Write the entire code and the expected output results in the note.
UNIT 06

Enter integer:
x = 50
50 is a natural number.
Example Output
or
Enter integer:
x = -10

Time

Write the entire code and the expected output results in the note.
UNIT 06

1.1. If statements that are executed when certain conditions are satisfied

("x is greater than 1.")

x is greater than 1.

‣ Check the function of the if statement with an actual code. Put 100 in the variable x and write the if statement as
above. In this case, since the conditional expression x>1 returns True, the following execution is run.
‣ Therefore, 'x is greater than 1' is printed on the screen. Here, the line below :(colon) must be indented.
UNIT 06

1.2. Relational operator =, ==


Focus Assignment operator = and relational operator == are different operators.

‣ This part is mentioned repeatedly, because beginners often make these mistakes. The = operator is an operation that
puts the value of right to the variable on the left. The == operator returns True or False depending on whether the
left and right values are identical or not.
UNIT 06

1.3. Indentation in Python

‣ How can we print that one is accepted and qualified for a scholarship if the score is 90 or higher? In this case,
sentences can be grouped by using indentations as shown below.
‣ If the value of score is 90 or higher, two sentences calling print() are executed in the code below. Note that these
sentences have the same number of spaces. All of these belong to the same block.

Block: a group of sentences.

if score >= 90 :
print(“You are accepted.”)
print(“You are qualified for a scholarship.”)
UNIT 06

1.3. Indentation in Python

("Enter the score: "))


# if the condition is true, block indent is all executed
("Congratulations.")
("You are accepted.")
("You are qualified for a scholarship.")

Enter the score: 95


Congratulations.
You are accepted.
You are qualified for a scholarship.

Line 2-5
• Line 3, 4 and 5 are executed because the score is given as 95.
UNIT 06

1.3. Indentation in Python

IndentationError

("Enter the score: "))


# Caution : if indentation is different an error occurs
("Congratulations.")
("You are accepted.")
("You are qualified for a scholarship.")

("You are accepted.")

Line 3-5
• Error occurs because the numbers of indented spaces are different.
UNIT 06

2.1. split method

The split uses space as the default value. So, each value is inserted using the space as a separator.
In this way, a character that divides a string into one or more individual strings is called a separator.
UNIT 06

2.2. input function and split method

('Enter three integers divided by space: ')


('Input: ', str1)
('Input separated by split() method: ', str1.split())

Enter three integers separated by space: 10 20 30 separated by spaces


Input: 10 20 30
Input separated by split() method: ['10', '20', '30']

('Enter three integers separated by ,: ')


('Input: ', str1)
('Input separated by split() method: ', str1.split(','))

Enter three integers separated by ,: 10 20 30 separated by commas


Input: 10,20,30
Input separated by split() method: ['10', '20', '30']

‣ Make a list of string using string received by split function.


‣ After that, the elements in this list can be converted to an integer type.
UNIT 06

2.3. How to process input values with split and int functions

('Enter three integers separated by ,: ').split(',')

Enter three integers separated by ,:

Enter three integers separated by ,:

('Enter three integers separated by ,: ').split(',')

Enter three integers separated by ,: 5,6,7


5 6 7
UNIT 06
UNIT 06
UNIT 06

Output example
Enter age: 16
Youth
Enter age: 33
Adult
Enter age: 5
Kid
UNIT 06

Output example
Enter age: 20
Enter height in cm: 180
You can enter.
Unit learning objective (1/3) UNIT 07
Unit learning objective (2/3) UNIT 07
Unit learning objective (3/3) UNIT 07

if - else if-else-elif

Double Conditional Random


Statement Numbers
UNIT 07

1.1. The scale of the global game market


UNIT 07

1.2. FIFA Online 4


UNIT 07

1.3. Penalty shootout rules


UNIT 07

1.4. Additional reference for penalty shootout


UNIT 07

2.1. Process of penalty shootout game

# randomly generates numbers among 1,2,3

"Left"

"Middle"

"Right"

("Which side will you attack?(left, middle, right) : ")

("Offense failed.")

("Congrats!! Offense succeeded.")


('computer defense position :', computer_choice)

Which side will you attack?(left, middle, right) : right


Congrats! You made it.
computer defense position : left
UNIT 07

2.2. Programming plan


Pseudocode Flowchart

[1] Start Start

[2] Receive random input. if computer_choice = random()

[3] User enters one of the three inputs. user_choice = input

[4] Check if the direction of the keeper and the direction of the
if computer_choice
ball are identical. == user_choice

[5] if identical, print ‘Attack failed’


print(‘Attack failed’)
[6] if different, print ‘Offense succeeded.’
print(‘You made it’)
[7] End
End
UNIT 07

2.3. Penalty shootout game final code

# randomly generates numbers among 1,2,3

"Left"

"Middle"

"Right"

("Which side will you attack?(left, middle, right) : ")

("Offense failed.")

("Congrats!! Offense succeeded.")


('computer defense position :', computer_choice)
UNIT 07

1.1. else statement which is executed when the condition is false

‣ Code as follows in Python.

('Accepted')
('Also receive a scholarship')

('Not accepted.')
UNIT 07

1.2. if statement without else statement

A function to print "It's morning" before 12pm, and "It's afternoon" after 12pm.

10

False hour
('It is morning.') hour < 12
True
('It is afternoon.')
print(‘It is morning.’)
It is morning.

False
hour>= 12
True
print(‘It is afternoon.’)
UNIT 07

1.3. if – else statement

‣ It can't be morning and afternoon at the same time. This relationship is called an exclusive relationship.
‣ The if-else statement is a command statement that can be used such exclusive relationships.
‣ Expressing an exclusive relationship with an if-else simplifies the flow chart as well.

('It is morning.') 10

('It is afternoon.') hour

It is morning.
True False
hour < 12

print(‘It is morning.’) print(‘It is afternoon’)


UNIT 07

1.4. Comparing flowchart of if-else and if

‣ The left is much clearer. 10

hour

10
False
hour < 12
hour
True
print(‘It is morning.’)
True False
hour < 12

False
print(‘It is morning.’) print(‘It is afternoon’) hour>= 12

True
print(‘It is afternoon.’)
UNIT 07

1.5. if-else statement to determine odd/even numbers

'is an even number.')

'is an odd number.')

10 is and even number

Line 2, 4
• If num is divided by 2 and the remainder is 0, the lower Line 3 block is executed if the remainder is 0.
• Otherwise, Line 5 block under else is executed.
UNIT 07

1.6. Writing if-else statement inside if-else statement

True
num >= 0 Inner if block

False True
num == 0

False

print(”Negative.") print(”Positive. ") print(”It is 0.")


UNIT 07

1.6. Writing if-else statement inside if-else statement

‣ We need to be able to resolve various situations with coding.


‣ Suppose a case in which a user receives an integer, determines whether it is positive, zero, or negative and prints the
result on a screen.
("Enter an integer: "))
# make sure to indent the block
# check specific conditions inside the block
("It is 0.")

("It is positive.")

("It is negative.")

Enter an integer: -20


It is negative.
‣ As such, you can solve problems by inserting an if-else statement inside an if-else statement.
UNIT 07

1.7. Using nested if – else statement to discriminate even/odd numbers

'is negative.')

'is not negative.')

'is an even number.')

'is an odd number.')


100 is not negative.
100 is even number.

Line 2, 4
• Since num is greater than 0, the block right below is not executed, but the else statement of Line 4 is executed.
UNIT 07

1.7. Using double if – else statement to discriminate even/odd numbers

'is negative.')

'is not negative.')

'is an even number.')

'is an odd number.')

100 is not negative.


100 is an even number.

Line 5~7
• After printing 'It is not negative.' using the print function, divide num by 2 once more to compare whether the
remainder value is 0.
• Since 100%2 is 0, the if statement is executed and the program is terminated.
UNIT 07

1.8. Flow control in various cases

'is negative.')

'is not negative.')

'is an even number.')

'is an odd number.')

-100 is negative.

‣ In this code, if-else is used twice. The if-else statement on the outside is called the outer if-else statement, and the
if-else statement on the inside is called the inner if-else statement. Closely examine the code.
‣ The if-else conditional statement of Line 2 and 4 is an outer if-else statement. The if statement of Line 2 is executed
only when the value of num is less than 0, i.e., negative.
UNIT 07

1.8. Flow control in various cases

'is negative.')

'is not negative.')

'is an even number.')

'is an odd number.')

-100 is negative.

‣ The else statement of Line 4 is executed only when the value of num is not negative.
‣ Line 6 ~ 9 are an if-else statement inside the else statement and is called the inner if-else statement.
‣ The if statement of Line 6 is executed only when the variable num has no remainder after division by 2, that is, if it is
an even number.
‣ Let's look at Line 8. This else block is executed when it is odd.
‣ Therefore, if the value of the variable num is changed to -100, it is executed as above.
UNIT 07

2.1. How to continuously examine other conditions when the conditions are
false

True
num > 0 print(”It is positive.")

False
True
num == 0 print(”It is 0.")

False

print(”It is negative.")
UNIT 07

2.2. Code example that prints positive, negative, and 0 after receiving integer
as an input

("Enter an integer: "))

("It is positive.")

("It is 0.")

("It is negative.")

Enter an integer: 6
It is positive.
Enter an integer: -5
It is negative.
Enter an integer: 0
It is 0.
UNIT 07

2.3. Reason to use nested conditional statement

Score Grade
90 ~ 100 A
80 to Less than 90 B
70 to Less than 80 C
60 to Less than 70 D
Below 60 F
UNIT 07

2.4. Grade Generator example A: Code using multiple if statements


('Enter score : '))
# If 90 or above, 'A'
# If under 90, 80 or above, 'B'
# If under 80, 70 or above, 'C'

# If under 70, 60 or above, 'D'


#If under 60, 'F'
('Your grade is: ', grade)

Enter score : 88
Your grade is: B

‣ Grade B for 88 points is properly printed.


‣ However, this code has become more complex and difficult to read than the previous if statement.
‣ Even if there is an incorrect conditional expression inside each conditional expression, the error is hard to identify.
‣ The possibility of errors increases because you need to identify the meaning of each if statement.
‣ To solve this problem, apply the if-else statement as shown below.
UNIT 07

2.5. Grade generator example B : Grade generator code using if-else


statement
('Enter score : '))
# If 90 or above, 'A'

# If under 90, 80 or above, 'B'

# If under 80, 70 or above, 'C'

# If under 70, 60 or above, 'D'

#If under 60, 'F'


('Your grade is: ', grade)

Enter score : 88
Your grade is: B

‣ Grade B for 88 points is properly printed.


‣ The likelihood of errors is reduced.
‣ Readability is still poor because if-else can only represent two conditions.
UNIT 07

2.5. Grade generator example B : Grade generator code using if-else


statement
('Enter score : '))
# If 90 or above, 'A'

# If under 90, 80 or above, 'B'

# If under 80, 70 or above, 'C'

# If under 70, 60 or above, 'D'

#If under 60, 'F'


('Your grade is: ', grade)

Enter score : 88
Your grade is: B

‣ There are too many indentations.


‣ For multiple conditions, what could be a simpler way?
UNIT 07

2.6. Comparing if-elif statement and elif statement

Code using if-else Code using if-elif

‣ Both codes perform the same task.


‣ The code on the right is indented less and the number of lines is reduced. Thus the code is easier to read and
understand.
UNIT 07

2.7. Grade generator example C: if-elif-else statement execution flowchart

True
score>=90 grade = ‘A’

False
True
score>=80 grade = ‘B’

False
True
score>=70 grade = ‘C’

False
True
score>=60 grade = ‘D’

False

grade = ‘F’
UNIT 07

2.8. Grade generator example C: grade generator code using if-elif-else


statement
('Enter score : '))
# If 90 or above, 'A'
# If not 'A', 'B' if 80 or above

# If not 'B', 'C' if 70 or above

# If not 'C', 'D' if 60 or above


# Otherwise, 'F'

('Your grade is: ', grade)

Enter score : 88
Your grade is: B

‣ Grade B for 88 points was properly printed.


‣ Compared with the examples A and B, the chance of an error is smaller because example C used the if-elif-else
statement.
‣ Also the code is easy to understand because the condition is clear.
UNIT 07

2.8. Grade generator example C: grade generator code using if-elif-else


statement
88

score

True
When the value of the score score>=90 grade = ‘A’
variable is 88, it has the
False
following execution flow. True
score>=80 grade = ‘B’
False
True
score>=70 grade = ‘C’

False
True
score>=60 grade = ‘D’
False
grade = ‘F’
UNIT 07

2.8. Grade generator example C: grade generator code using if-elif-else


statement

88 ‣ First, the program executes the statement if score >=90: to


score determine whether the score value is greater than 90.
‣ Since the result of the comparison is False, the statement
True elf score>=80: is performed to determine whether the
score>=90 grade = ‘A’
score value is greater than 80.
False
True ‣ Now that this result is True, the grade = 'B' sentence is
score>=80 grade = ‘B’ executed, and the execution of all elif-else statements
False below are skipped.
True
score>=70 grade = ‘C’ ‣ Therefore, the program finally prints "your grade is : B".
False
True
score>=60 grade = ‘D’
False
grade = ‘F’
UNIT 07

2.9. Diverse and complex real-life problems


Focus Programmers must deal with more complex problems than this.
To impose more sophisticated conditions, you can combine comparison operators and logical operators.
Python has the following comparison operators and logical operators, all of which return Boolean values (True,
False).
Some are examples of multiple operators combined.

Comparison operator Explanation


== Returns True if two operands have identical value.
!= Returns True if the values of the two operands are different.
> Returns True if the left operand is greater than the right operand.
< Returns True if the left operand is less than the right operand.
>= Returns True if the left operand is greater than or equal to the right operand.
<= Returns True if the left operand is less than or equal to the right operand.

Logical operator Meaning


x and y If one of x or y is False, it is False. It is only True if it all are True.
x or y If either x or y is True, it is True, and False only if all are False.
not x If x is true, it is False, and if x is false, it is True.
UNIT 07

2.10. Example of a complex conditional expression

# if b is changed to 13, it does not meet the first conditional statement


# first conditional statement
('Both are positive.')
# second conditional statement
('At least one is positive.')

Both are positive.


At least one is positive.

‣ The above code that generates results with two conditions when a = 10 and b = 14.
‣ The if statement in this code prints outputs by using logical operators and and or.
‣ In this code, (a% 2==0) is True and (b% 2==0) is True. Therefore, both print statements of lines 3 and 4 are printed.
UNIT 07

2.10. Example of a complex conditional expression

# if b is changed to 13, it does not meet the first conditional statement


# first conditional statement
('Both are positive.')
# second conditional statement
('More than one is positive.')

More than one is positive.

‣ The above code that generates results with two conditions when a = 10 and b = 14.
‣ The if statement in this code prints outputs by using logical operators and and or.
‣ Here, since b is 13, (b% 2 == 0) is False.
‣ Therefore, (a% 2 == 0) and (b% 2 == 0) are False, so 'Both numbers are even.' is not printed.
‣ On the other hand, since (a% 2==0) is True, (a% 2==0) or (b% 2==0) is True.
UNIT 07

('Enter the year: '))

'is a leap year?',

Enter the year : 2021


2021 is a leap year? False
UNIT 07

3.1. Application exercise

This is David’s fruit shop.


1: Apple( price : 5000 won)
2: Grape( price : 6000 won)
3: Melon( price : 8000 won)
4: Orange( price : 2000 won)

Enter item number (between 1~4) >> 2


Enter number of item(between 1~10) >> 2
Fruit selected : grape
Price : 6000
Quantity: 2
Total price is 12000 won.
Insert money please(ex: 15000) >>> 20000
20000 won received. Your change is 8000 won.
UNIT 07

3.1. Application exercise

('This is David’s fruit shop.')


('1: Apple( price : 5000 won)')
('2: Grape( price : 6000 won)')
('3: Melon( price : 8000 won)')
('4: Orange( price : 2000 won)')

(('Enter item number(between 1~4) >> ')))


(('Enter number of items(between 1~10) >> ')))
UNIT 07

3.1. Application example

'Apple'

'Grape'

'Melon'

'Orange'

('Fruit selected :', fruit)


('Price :', price)
('Quantity :', count)
('Total price is', price * count, 'won.')

('Insert money please(ex: 15000) >>>'))

('Not enough money.')

(money, 'won received. Your change is', change, 'won.')


UNIT 07

3.2. Key code commentary of the application example

‣ The central code of this program is as follows.


‣ If the order number is 1, the fruit is 'apple' and the price is 5000. If not, the code processes another condition
verification through the if-elif statement.
‣ In such way, the if-elif-else statement simplifies the code.

'Apple'

'Grape'

'Melon'

'Orange'
Try to fully understand the basic concept before moving on to the next step.
Lack of understanding basic concepts will increase your burden in learning this
course, which may make you fail the course.
It may be difficult now, but for successful completion of this course we suggest you
to fully understand the concept and move on to the next step.
UNIT 07

Enter the alphabet : k


Example Output
K is a consonant

Time

Write the entire code and the expected output results in the note.
UNIT 07

Write two integers: 30 3


Example Output 30 is a multiple of 3

Time

Write the entire code and the expected output results in the note.
UNIT 07

1.1. Program for ID verification

id :

Log in to Account
UNIT 07

1.2. The program resolution code for ID verification.

("Enter the ID: ")

("Welcome.")

("ID not found.")


Enter the ID: ilovepython
Welcome.

‣ Take a string input using the input function. Next, the relational operator == checks whether the input string
identical to 'ilovepython'. If the result of the relational operator is True, print 'Welcome’.
UNIT 07

Enter ID:
Enter your ID:
Enter Password:
Welcome.
Password

Log in to Account
UNIT 07

1.3. Program to verify ID and password

("Enter ID: ")


("Enter Password: ")

("Welcome.")

("ID not found.")

("The password is wrong.")

Enter ID: ilovepython


Enter password: mypass1234
Welcome.

Line 2~3
• Receive ID and password from the user.
UNIT 07

1.3. Program to verify ID and password

("Enter ID: ")


("Enter Password: ")

("Welcome.")

("ID not found.")

("The password is wrong.")

Enter ID: ilovepython


Enter password: mypass1234
Welcome.

Line 5~6
• Compare whether the string input by the user both match my_id and password. Since we used the and
operator, the block below is not executed if either one is wrong.
• If the fifth line is True, 'Welcome' is printed.
UNIT 07

1.3. Program to verify ID and password

("Enter ID: ")


("Enter Password: ")

("Welcome.")

("ID not found.")

("The password is wrong.")

Enter ID: ilovepython


Enter password: mypass1234
Welcome.

Line 7~8
• If the if statement on the fifth line is false, checks if my_id is different from string1 (user input value) in the elif
statement.
• If different, 'ID not found' is printed.
UNIT 07

1.3. Program to verify ID and password

("Enter ID: ")


("Enter Password: ")

("Welcome.")

("ID not found.")

("The password is wrong.")

Enter ID: ilovepython


Enter password: mypass1234
Welcome.

Line 9~10
• If both if and elif statements in Line 5 and Line 7 are false, the print statement of the last else statement is
executed.
UNIT 07

2.1. Code example of random number generation

# call the random module

Line 1
• In order to use the function randint which produces random numbers between 1 and 100, the random number
module must be imported using an import statement.
UNIT 07

2.2. Coin tossing game using a random function


UNIT 07

2.2. Coin tossing game using a random function

‣ This is a test code for making a coin tossing game with a random function.
‣ Run several times. 0 or 1 will be printed.
UNIT 07

2.2. Coin tossing game using a random function

("Start coin tossing game. ")

("Front.")

("Back.")
("Game finished.")

Start coin tossing game.


Front.
Game finished.

Line 4
• The function called randrange(2) is a function that returns 0 or 1 through a random number generator.
UNIT 07
UNIT 07
UNIT 07

Output example
1) Addition 2) Subtraction 3) Multiplication 4) Division
Enter the desired number of operation : 1
Enter two numbers for operation.
10
20
10 + 20 = 30

If inserted incorrectly
1) Addition 2) Subtraction 3) Multiplication 4) Division
Enter the desired number of operation : 5
Entered an incorrect number.
UNIT 07

Output example
y
Enter x,y coordinates: -5 6
In the second quadrant

2 quadrant 1 quadrant

3 quadrant 4 quadrant
UNIT 07

Output example
Welcome to yummy restaurant. Here is the menu.
- Burger(enter b)
- Chicken(enter c)
- Pizza(enter p)
Choose a menu (enter b,c,p) : b
You chose pizza.

‣ This needs complex conditional expressions. Combine the logical operators and the conditional statements
carefully.
Unit learning objective (1/3) UNIT 08
Unit learning objective (2/3) UNIT 08
Unit learning objective (3/3) UNIT 08

for in

iteration range
UNIT 08

1.1. Obesity is the cause of various diseases and increases the burden of
medical expenses in society as a whole
UNIT 08

1.2. How to prevent obesity


UNIT 08

2.1. What is Food Combination?


UNIT 08

2.2. Additional Information for Food Combination


UNIT 08

3.1. How to make Delicious Food Combinations


UNIT 08

3.2. Delicious Food Combinations operation process


["Rye bread", "Wheat", "White"]
["Meatball", "Sausage", "Chicken breast"]
["Lettuce", "Tomato", "Cucumber"]
["Mayonnaise", "Honey Mustard", "Chili"]

('Possible combinations of David’s sandwich shop')

Possible combinations of David’s sandwich shop


Rye bread + Meatball + Lettuce + Mayonnaise
Rye bread + Meatball + Lettuce + Honey Mustard
Rye bread + Meatball + Lettuce + Chili
Rye bread + Meatball + Tomato + Mayonnaise
Rye bread + Meatball + Tomato + Honey Mustard
Rye bread + Meatball + Tomato + Chili
Rye bread + Meatball + Cucumber + Mayonnaise
Rye bread + Meatball + Cucumber + Honey Mustard
UNIT 08

3.3. Programming Plan

Start
[1] Start
breads = [‘Rye bread’, ‘Wheat’,
‘White] meats = [ ] ….
[2] Define list-type data containing food ingredients.

for b in breads
[3] the number of elements in for b in bread list :

[4] the number of elements in for m in meats list : for m in meats

[5] the number of elements in for v in vegis list : for v in vegis

[6] the number of elements in for s in sauces list :


for s in sauces

[7] print b + m + v + s.
print b + m + v + s
[8] end
End
UNIT 08

3.4. Delicious Food Combinations final code


["Rye bread", "Wheat", "White"]
["Meatball", "Sausage", "Chicken breast"]
["Lettuce", "Tomato", "Cucumber"]
["Mayonnaise", "Honey Mustard", "Chili"]

('Possible combinations of David’s sandwich shop')


UNIT 08

1.1. Necessity of iterated statements

Welcome!
UNIT 08

1.1. Necessity of iterated statements

‣ Write print function 5 times to print 5 times repeatedly without using loop statements.
‣ Consider repeating this task 1000 times.
‣ This is inefficient.
UNIT 08

1.1. Necessity of iterated statements

‣ Of course, for only few repetitions, you may "copy and paste" as above.
‣ But can you repeat it 100 times?
‣ In this case, you can write a simple code by using the for statement.
‣ loop statements are important control statements that handle inconvenient repetitive tasks.
UNIT 08

1.2. Basics of range and loop statement syntax

variable range function

for n in range(5) :
for block that will be
executed repeatedly
UNIT 08

1.3. for statement example

‣ To repeat the above code 10 times, put 10 inside the parentheses range ().
‣ This simple code executes a huge amount of tasks, and code modification and maintenance becomes easier.
‣ To repeat 100 times : change to range(100).
UNIT 08

1.4. loop control variable

‣ Variables used for loop statements are generally assigned with alphabets i, j, k, l, ...
‣ These variables are called loop control variables in C or Java.
UNIT 08

Anonymization of loop control variables


‣ Since the newly assigned variable i in the above loop statement is a loop variable that is not used in the
execution statement, you can anonymized the variable by substituting it with an underscore (_) as follows.
UNIT 08

2.1. Structure of range

Value that stops generation.


This value is excluded from generation.

Value that starts generation The size of the value that changes in one increment.

range(start = 0, stop, step = 1)


UNIT 08

Arguments of a range function cannot be real numbers.


‣ A range function cannot have a real number arguments. However, a function called arrange() in the numpy
module (which will be dealt later) can take real numbers for start, step and stop values.

TypeError
UNIT 08

2.2. About range


UNIT 08

2.2. About range

range(5)

0 1 2 3 4 5

returned array

Start value Stop value


(Stop value not returned)
UNIT 08

2.2. About range

range(0, 5, 2)
range

0 1 2 3 4 5

step value = 2 step value = 2


start value stop value
UNIT 08

2.3. Problem solving using for in range

('Sum of numbers from 1 to 10: ', s)

Sum of numbers from 1 to 10: 55


UNIT 08

i s Iterate or Computing process of s


Iteration
value value not (Initial s is 0)
1st 1 1 Iterate 0+1
2nd 2 3 Iterate 0+1+2
3rd 3 6 Iterate 0+1+2+3
4th 4 10 Iterate 0+1+2+3+4
5th 5 15 Iterate 0+1+2+3+4+5
6th 6 21 Iterate 0+1+2+3+4+5+6
7th 7 28 Iterate 0+1+2+3+4+5+6+7
8th 8 36 Iterate 0+1+2+3+4+5+6+7+8

9th 9 45 Iterate 0+1+2+3+4+5+6+7+8+9

Stop
10th 10 55 0+1+2+3+4+5+6+7+8+9+10
Iterating
UNIT 08

2.4. Overlap of sum() function and variable name sum

‣ The sum() function calculates the sum of the elements in the list. Thus, a sum of numbers from 1 to 10, 55 is printed.
UNIT 08

Overlapping use of sum() function and variable name

Since the sum function has already been used as the


name of a variable, it cannot be called afterwards.

('The sum of numbers from 1 to 10: ', sum)

The sum of numbers from 1 to 10 : 55

('The sum of numbers from 1 to 10: ', sum)

‣ If a variable sum is used inside the code as shown above, it may be confused with the Python built-in function sum().
‣ An error occurs when a variable called sum = 0 and a function called sum (numbers) are called within the same
module.
‣ Therefore, it is recommended to use s or total as the name of the variable, so that it does not overlap with the sum()
function.
UNIT 08

2.5. Computing factorial

('Enter a number: '))

Enter a number :
5! = 120
UNIT 08

Python and limitations in integer expressions


‣ If we change the value of n in the code above to 50, it prints an enormous number of the following.
‣ 50! = 30414093201713378043612608166064768844377641568960512000000000000.
‣ In programming languages such as C and Java, integers larger than a certain size cannot be expressed
because the integer size is set to 4 byte types. For example, Java's long-type integer ranges from -
9223372036854775808 to 9223372036854775807. However in Python, there is no limitation in integer
expression. This is another big advantage of Python.
UNIT 08

3.1. Object with order

variable List to be visited

for n in numbers :
for block to be iterated

11 through 66 are assigned to n consecutively

n 11 22 33 44 55 66
numbers list
UNIT 08

3.1. Object with order

# different values are printed each time


UNIT 08

3.2. Cumulative addition code example

('Sum of list items : ', s)


Sum of list items : 150

‣ This is a program to find the sum of integer item values in the list using the cumulative addition functionality.
UNIT 08

3.2. Cumulative addition code example

('Sum of list items : ', sum(numbers))


Sum of list items : 150

‣ The sum of the list elements can be easily calculated using the built-in function sum() without using the for
statement.
UNIT 08

3.3. Converting string data type to list data type

‣ The string data type 'Hello' becomes a list of individual alphabet characters.
UNIT 08

3.4. How to use string data type in for loops

‣ You can convert the string 'Hello' into a list of character elements by applying the list function.
‣ Place the string after the for in expression. This will separate the string into individual characters, enabling the loop
to visit each character.
‣ Insert the end =‘ ‘ argument inside the print function. It prints another line without changing the line after printing
ch.
UNIT 08

Various options of the print function


Do the following to put characters that are not spaces between values. sep is derived from the word
separator.

The keyword argument end specifies a string to be printed after the output value. In the code below, one space was
printed using "end=" after "My name is". If you enter something else a string, that string is printed instead of a
space.
Try to fully understand the basic concept before moving on to the next step.
Lack of understanding basic concepts will increase your burden in learning this
course, which may make you fail the course.
It may be difficult now, but for successful completion of this course we suggest you
to fully understand the concept and move on to the next step.
UNIT 08

V
J-Hope
RM
Example Output Jungkook
Jin
Jimin
Suga

Time

Write the entire code and the expected output results in the note.
UNIT 08

Example Output Sum of integers from 1 to 100 : 5050

Time

Write the entire code and the expected output results in the note.
UNIT 08

Example Output Sum of even numbers from 1 to 100 : 2550

Time

Write the entire code and the expected output results in the note.
UNIT 08

Example Output Sum of odd numbers from 1 to 100 : 2500

Time

Write the entire code and the expected output results in the note.
UNIT 08

1.1. for statement execution structure

for statement
False
Are there items in for .. in
sequence?
True

Execute a command or command block

example
for i in range(5):
print(‘welcome’)

‣ Therefore, the sentence is iterated until the task of returning numbers from 0 to 4 is completed.
UNIT 08

Loop
‣ In programming, iteration is often referred to as a loop, which means a round ring like a snare. Because when a
program iterates, it goes back to the previous step, resembling a circle. Iteration without exiting this loop is
called an infinite loop.
UNIT 08

1.2. Use for loop for iteration of controlled number of times

Not enough flag,


One flag please one more round

print(‘Welcome’)
Take the flag

Five
flags!
Circle five Exit
times and exit
Enters for statement Can pass when you
have five flags

General flow of loop execution using for loop statements.


UNIT 08

1.2. Use for loop for iteration of controlled number of times

# There must be : at the end


("Welcome.") # Must indent

Welcome.
Welcome.
Welcome.
Welcome.
Welcome.
UNIT 08

1.3. for statement indentation

# There must be : at the end


("Welcome.") # Must indent

Welcome.
Welcome.
Welcome.
Welcome.
Welcome.

‣ In the first iteration, the value of the variable i becomes 1, the first number of the list, and the print(...) sentence is
executed.
‣ In the second iteration, the value of the variable i becomes 2, the second number in the list, and the print(...)
sentence is executed.
‣ In the third iteration, the value of the variable i becomes 3, the third number of the list, and the print (...) sentence is
executed.
UNIT 08

1.3. for statement indentation

# There must be : at the end


("Welcome.") # Must indent

Welcome.
Welcome.
Welcome.
Welcome.
Welcome.

‣ In the fourth iteration, the value of the variable i becomes 4, the fourth number of the list, and the print (...) sentence
is executed.
‣ In the fifth iteration, the value of the variable i becomes 5, the fifth number in the list, and the print (...) sentence is
executed.
UNIT 08

1.4. Sequence object that follows for – in

‣ An object that can have multiple items such as a list or a string is called a sequence object.
‣ In the previous slide, the value of the variable i was not used at all.
‣ This time, assign the items of the sequence object to the variable i inside the loop statement. Then, use the print
function to print the value of i.

# place the list after in and : after the list


# print values of i
UNIT 08

1.4. Sequence object that follows for – in

# : is necessary at the end


# print i values
UNIT 08

1.5. Range function that comes with the for statement

for i in range(5) :

0 1 2 3 4
for loop

i
control variable range(5)
UNIT 08

1.5. Range function that comes with the for statement

('Welcome to')
("Python corporation!")

Welcome to
Python corporation!
Welcome to
Python corporation!
Welcome to
Python corporation!
Welcome to
Python corporation!
Welcome to
Python corporation!
UNIT 08

1.6. Characteristics of the range function


UNIT 08

Values returned by a range function are of range type.


‣ Python's range function returns range-type data type.
‣ range-type data type generates and returns consecutive values for each call. / Therefore, it is mainly used with
for statements.
UNIT 08

1.6. Characteristics of the range function

‣ The range function can generate more diverse integer sequences utilizing multiple arguments, and its general
format is as follows.
‣ If you call with the format range (start, stop, step), integers from start to (stop-1) are generated with step intervals.
‣ The for loop is iterated as many times as the number of this sequence.
‣ Here, start and step may be omitted, in which case the start is 0 and the step is 1.
‣ However, the loop is executed only when the stop value is specified.

value that ends generation, but this


stop is excluded from generation The size of the value that
increases each time If start and step are not specified,
Start value of generation they are treated as 0 and 1,
respectively.
range(start = 0, stop, step = 1) The value that must be specified is
stop.
UNIT 08

1.7. range function examples

# if you assign end = " ", it enumerates with spaces in between instead of changing lines.

To print odd numbers between 1 and 10, assign 2 to the step value.
UNIT 08

1.7. range function examples


UNIT 08

range(n) is identical to range(0, n, 1).


‣ One is prone to think that range(10) function generates integers from 1 to 10. The number of iterations are 10.
However, the integers produced are from 0 to 9. This has been a long-standing debate in computing.
‣ Starting from 0 has now become a trend. Anyhow, range(10) iterates 10 times and generates integers from 0 to
9. To print integers from 1 to 10, use range(1, 11).
UNIT 08

2.1. format function code example

# formatting integer value

# formatting integer value

# formatting real number value

# formatting real number value

‣ ‘{}’.format(100) executes formatting function which prints 100.


‣ ‘{:5d}’.format(100), ‘{:5d}’.format(10) creates 5 spaces to print 100 and 10.
‣ ‘{:6.2f}’.format(3.14), creates 6 spaces and prints 2 digits below the decimal point in order to print the number 3.14.
UNIT 08
UNIT 08
UNIT 08

Output Example

Enter n : 5
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
21 22 23 24 25
Unit learning objective (1/3) UNIT 09
Unit learning objective (2/3) UNIT 09
Unit learning objective (3/3) UNIT 09

random import
while
command

break, continue double loop


UNIT 09

1.1. Metaverse fever, meta universe


UNIT 09

1.2. Snail trapped in a well


UNIT 09

1.3. Snail in a Well reference video

How many
days to get out?
UNIT 09

2.1. Snail in a Well


UNIT 09

3.1. How Snail in a Well works


# Current position of snail
# date
# distance it goes up a day : in meters
# distance it goes down while sleep : in meters
# Distance goal : in meters
# position of the snail on the first day
'Snail’s position :', current_pos, 'meters')
# repeat if snail hasn’t reached the distance goal
# goes down again
# next day
# distance it went up
('day :' ,days, 'snail’s position :', current_pos, 'meters')

('It took {} days to get out of the well.'.format(days))

day : 1 Snail’s position : 7 meters


day : 2 Snail’s position : 9 meters
day : 3 Snail’s position : 11 meters
day : 4 Snail’s position : 13 meters
day : 5 Snail’s position : 15 meters
day : 6 Snail’s position : 17 meters
day : 7 Snail’s position : 19 meters
day : 8 Snail’s position : 21 meters
day : 9 Snail’s position : 23 meters
day : 10 Snail’s position : 25 meters
day : 11 Snail’s position : 27 meters
day : 12 Snail’s position : 29 meters
day : 13 Snail’s position : 31 meters

It took 13 days to get out of the well.


UNIT 09

3.2. Programming Plan

Start
[1] Start
current_pos = 0 , days = 1 ....
[2] Initialize the location, date, target location, daily travel
distance, etc. of snail.
if current_pos <=
[3] while If the snail's position is smaller than the target destination
position

[4] goes down while sleep current_pos -= move_down

[5] Next day. Increase the day every time


days += 1
[6] Goes up again..

end while current_pos += move_up

[7] Print the day it took to escape. print(days)

[8] End
End
UNIT 09

3.3. Snail in a Well final code


# Current position of snail
# date
# distance it goes up a day : in meters
# distance it goes down while sleep : in meters
# Distance goal : in meters
# position of the snail on the first day

'Snail’s position :', current_pos, 'meters')


# repeat if snail hasn’t reached the distance goal
# goes down again
# next day
# distance it went up
('day :' ,days, 'snail’s position :', current_pos, 'meters')

('It took {} days to get out of the well.'.format(days))


UNIT 09

1.1. What is while statement?

‣ It is in form of while [Conditional expression] : .


‣ If write as while True : , it goes into infinite loop.
UNIT 09

1.1. What is while statement?

‣ Initialize i to zero.
While statement ‣ The while statement prints 'Welcome' and increases the i value by 1 if
False the condition of i < 5 is true.
Is the condition of
while statement True? ‣ Since the initial i value is 0, this iteration will also be performed five
True times.

Execute an command or
command block.

Example
i=0
while i < 5:
print(‘Welcome’)
i=i+1
UNIT 09

1.2. Syntax of while statement

Form Example

i = 0 # Set initial value


set initial value
while i<5 : # conditional expression
while conditional statement :
print('Welcome to everyone!!')
code block to be excuted
i += 1

‣ Despite it is loop statement, it is very similar to the if statement.


‣ If the conditional expression is true, it repeats and executes the code.
UNIT 09

1.2. Syntax of while statement


# initial value
# block is executed when loop’s condition is true

‣ Increase i by 1 from 0 and repeat the code inside while only if it is less than 5.
UNIT 09

1.3. A program to find the sum of values up to the input value

('Enter a number to sum up to :'))

('Sum of 1 to {} is {}'.format(n, s))

Enter a number to sum up to : 5


Sum of 1 to 5 is 15

‣ The above code receives 5 as an input and calculates and prints the sum of integers from 1 to 5.
‣ In this way, if the number of iterations is clear, it is better to use the for statement because the code of the while
statement becomes longer.
‣ So when should we use the while statement?
UNIT 09

1.4. Comparing while statement and for statement

for

('Sum of 1 to 10:'.s)

while

('Sum of 1 to {} is {}'.format(n, s))

‣ The while statement is more suitable when the performance condition is clear, although the number of iteration is
not known exactly.
‣ If the number of repetitions is clear, the for statement is appropriate.
UNIT 09

1.5. while loop and input condition

['scissors', 'rock', 'paper']:


('Choose among scissors, rock, paper> ')
('Chosen value:', selected)
Choose among scissors, rock, paper> no
Choose among scissors, rock, paper> why
Choose among scissors, rock, paper> paper
Chosen value: paper

‣ In the case of such a code, it is difficult to solve the problem with for statement.
‣ While is suitable for repeated statements that are executed only when the desired value is entered.
UNIT 09

['scissors', 'rock', 'paper']:


('Choose among scissors, rock, paper> ')
('Chosen value:', selected)

Choose among scissors, rock, paper>


UNIT 09

1.5. while loop and input condition

('Enter a number to sum up to :'))

('Sum of 1 to {} is {}'.format(n, s))

Enter a number to sum up to : -10


Sum of 1 to -10 is 0

‣ This code has a logical error.


‣ It would be better to limit the range of input values to positive integers. In this case, it is more appropriate to use a
while statement that is repeatedly executed according to the conditions than a for statement.
UNIT 09

1.5. while loop and input condition

# input() repeated until positive value is entered


('Enter a positive number to sum up to :'))

('Sum of 1 to {} is {}'.format(n, s))

Enter a positive number to sum up to : -1


Enter a positive number to sum up to : 0
Enter a positive number to sum up to : 7
Sum of 1 to 7 is 28

Line 2
• The key is to receive re-input if the condition n < = 0 is satisfied. If -1 or 0 is entered, the input is repeatedly
requested.
UNIT 09

2.1. random module

‣ Python has many modules made by several organizations and developers, and we can effectively develop software
using them.
‣ The module developed in this way is provided with a Python installation file under the name of a standard library.
When bringing in a pre-made module, write the module name with "import", and when using it, mark a dot (.) in the
module name and call the components in the module.

import module name1 [, module name2, ...]


UNIT 09

2.2. Details of the features of the random module.

import [module name] as [abbreviation]

function tasks
random() It generates a real number between 0 and 1. (not including 1)
randrange() Returns an integer within the specified range.
randint(a, b) Returns a random integer N between a <=N <=b.
shuffle(seq) Randomly mix elements from a given seq list.
choice(seq) Select any element in the seq sequence.
sample() Randomly select a specified number of elements.
UNIT 09

2.3. Functions included in random module


# import command that calls inner module and abbreviation of random module, rd
# Returns a random real
# Returns a random real
# Returns an integer greater than or equal to 1 and less than 7.
# Returns a multiple of 2 of integers greater than or equal to 0 and less than 10.
# Returns an arbitrary integer greater than or equal to 1 and less than
or equal to 10 (including10).

‣ random(): Returns a real number greater than or equal to 0 and less than 1, and returns a different real number each
time it is used.
‣ range 1 and 7 : returns an integer greater than or equal to 1 and less than 7.
‣ range (0, 10, 2) : Returns a multiple of 2 of integers greater than or equal to 0 and less than 10.
‣ randint (1, 10) : returns an arbitrary integer greater than or equal to 1 and less than or equal to 10 (including 1 and
10).
UNIT 09

2.3. Functions included in random module

‣ shuffle() : Randomly mixes elements of the sequence and returns them.


‣ choice(): Extract any element from the sequence that enters the factor.
‣ sample() : Randomly returns the element. At this time, the number of elements to be returned can be added as a
factor.
UNIT 09

2.3. Functions included in random module


# returns integers from 1 to 10
# randomly mix elements of list

‣ shuffle() returns the sequence in a different order each time.


UNIT 09

2.4. sample function

('Arbitrary integer between 1 to 10 :', b)

Arbitrary integer between 1 to 10 : [2, 5, 10]

Line 3 ~ 4
• 3:a is assigned with list with elements 1 to 10.
• 4: Samples three arbitrary integers using the sample function and put them in b.
UNIT 09

3.1. Keyword that controls loop statement

‣ To end the loop: break


‣ To skip the remaining execution parts within the iteration loop and continue to execute the loop : continue
‣ continue does not end the loop.
UNIT 09

3.2. Flowchart of break

False
Condition

True
Statement

break

Statement

Flowchart of break
UNIT 09

3.3. break statement example

# function of executing only when it is consonant

# end the loop if it is vowel

‣ break if it is a vowel, otherwise print using print.


‣ When the break is activated, the loop is stopped without executing the rest of the loop.
UNIT 09

3.4. Flowchart of continue

False
Condition

True
Statement

continue

Statement
UNIT 09

3.5. continue statement example

# function of executing only when it is consonant

# skip the execution below if it is vowel

‣ When you write continue, it does not execute the rest of the code below.
‣ In other words, it returns to the beginning of the loop without executing the sixth line's print statement.
UNIT 09

3.6. Risk of break and continue flow control


UNIT 09

4.1. Double loop

# outer for loop


#inner for loop

# executes inner loop and change line


UNIT 09

4.2. Structure of double loop

for i in range(2, 10):


for j in range(1, 10):
Outer loop Inner loop
print('{}*{}={:2d}'.format(i, j, i*j), end=' ')
print()

‣ The double for loop has an inner loop and an outer loop.
‣ {} in the print statement is a placeholder that specifies a place for output, the content covered by Unit 8.
UNIT 09

4.3. Execution of double loop


When i = 2 When i = 3 When i = 4 ... When i = 9
j=1:2*1 j=1:3*1 j=1:4*1 ... j=1:9*1
j=2:2*2 j=2:3*2 j=2:4*2 ... j=2:9*2
j=3:2*3 j=3:3*3 j=3:4*3 ... j=3:9*3
j=4:2*4 j=4:3*4 j=4:4*4 ... j=4:9*4
j=5:2*5 j=5:3*5 j=5:4*5 ... j=5:9*5
j=6:2*6 j=6:3*6 j=6:4*6 ... j=6:9*6
j=7:2*7 j=7:3*7 j=7:4*7 ... j=7:9*7
j=8:2*8 j=8:3*8 j=8:4*8 ... j=8:9*8
j=9:2*9 j=9:3*9 j=9:4*9 ... j=9:9*9
Try to fully understand the basic concept before moving on to the next step.
Lack of understanding basic concepts will increase your burden in learning this
course, which may make you fail the course.
It may be difficult now, but for successful completion of this course we suggest you
to fully understand the concept and move on to the next step.
UNIT 09

Example Output

Time

Write the entire code and the expected output results in the note.
UNIT 09

Example Output

Time

Write the entire code and the expected output results in the note.
UNIT 09

1.1. while statement that is repeatedly executed according to the conditions

print(‘Welcome’) One more turn since


Let’s see if it it is not finished
is finished

It is finished!
Circle around if the I’ll pass through
Enter while A
construction is still going on
statement
Opens when
construction ends

The general flow of loop statement using while loop


UNIT 09

1.1. while statement that is repeatedly executed according to the conditions

Block to be repeated infinitely

The condition is True, the while


statement repeats forever
This code is a structure that repeats
infinitely.
while True : print(‘Repeat') However, if the conditions are met
print(‘Repeat this also') during repetition, the operation of
Conditional expression if conditional expression : the subblock is executed.
to decide whether to There's a break sentence in the block
enter the sub-block break below. Then you can get away from
this repetition.

Sub block
UNIT 09

1.1. while statement that is repeatedly executed according to the conditions

("Is the construction completed?");


"Yes" :

("Escaped successfully.")
Is the construction completed? No
Is the construction completed? Yes
Escaped successfully.
UNIT 09

1.2. while statement that is repeatedly executed according to the conditions


example

("Enter the password: ")


("** Login success **")
Enter the password: aaaa
Enter the password: pythonisfun
** Login success **
UNIT 09

1.3. Use while for a certain number of repetitions

# s is variable that contains values accumulated and added, reset it as 0

# add count value to s each time


# increase count value by 1 every time
("Sum is", s)

Sum is 55
UNIT 09

1.4. Calculate the sum of the numbers input by the user

('Enter the number: '))

('Continue?(yes/no): ')
('Sum is : ',

Enter a number: 5
Continue?(yes/no): yes
Enter a number: 6
Continue?(yes/no): no
Sum is : 11

Line 2~3
• Let answer be initialized to the string yes.
• Line 3: while condition is true, so the block right below is executed.
UNIT 09

1.4. Calculate the sum of the numbers input by the user

('Enter the number: '))

('Continue?(yes/no): ')
('Sum is : ',

Enter a number: 5
Continue?(yes/no): yes
Enter a number: 6
Continue?(yes/no): no
Sum is : 11

Line 4~6
• A number is assigned in the number variable.
• Add the value to the total by accumulating it.
• When the value 'yes' is added to the answer variable, the loop repeats, and when 'no' is entered, the loop exits.
UNIT 09
UNIT 09
UNIT 09

Output Example
Enter an integer: 135
135 is not a palindrome number

Enter an integer: 3443


135 is a palindrome number
UNIT 09

Output Example
Guess a number between 1 to 100
Enter a number: 50
Lower!
Enter a number: 40
Higher!
Enter a number: 51
Higher!
Enter a number: 45
Lower!
Enter a number: 4
Congratulations. Total try = 5

You might also like