SIC - C - P - Chapter 1. Programing Basic Concept and Starting Python - v1
SIC - C - P - Chapter 1. Programing Basic Concept and Starting Python - v1
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.
‣ 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.
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
Basic Python
Algorithm for
Data Analysis
Orientation
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
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
Computational Thinking
UNIT 01
※ To view the video clip above, move your mouse onto video screen to appear the play button.
UNIT 01
Sequence is important in everyday life How could the changed order affect the result?
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
Radius 4.0
Area 50.24
Circumference 25.12
UNIT 01
2.3. Annotation
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
Write the entire code and the expected output results in the note.
UNIT 01
python : 3.8
python : 3.7
Install pandas
data_science python_work
Computer
UNIT 01
Execution Command
Remove virtual environment conda remove --name [name of a virtual environment] --all
UNIT 01
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
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
When a string and a string are combined with a multiplication operator (*), TypeError occurs.
UNIT 01
Pascal Almost the same as the Camel style, but the first alphabet is also capitalized. HelloWorld
UNIT 01
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).
*
***
*****
*********
*****
***
*
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.
Keywords
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.
Make A Model
Or Prototype
Mission UNIT 02
[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.”
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.
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
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
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
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
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.
41 3 6 5 9 36 23 6
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?
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.
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?
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
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
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
O(n^2)
BAD O(log n) Log time: binary search
O(n!)
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
Judge the
westward
Yes
Walk straight
Let’s code UNIT 02
Yes
Turn right
Walk straight No
Let’s code UNIT 02
Italian
Turn right Restaurant
Let’s code UNIT 02
Italian
Restaurant
https://python.org/
Let’s code UNIT 02
https://docs.python.org/3/tutorial/index.html
Let’s code UNIT 02
https://docs.python.org/3/
Let’s code UNIT 02
https://www.w3schools.com
Let’s code UNIT 02
https://stackoverflow.com/
Pair programming
Pair programming UNIT 02
Pair programming UNIT 02
Pair programming UNIT 02
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
Circumference of
Diameter the circle = 2𝝅𝒓
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
3. Mission
3.3. Programming plan
Pseudocode Flow chart
Start
[1] Start
[3] Take the radius value input Take radius value input
End
UNIT 03
3. Mission
3.4. Printing the circumference and area of the circle: final code
100 20
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
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
# 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
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
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.
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.
Focus The * operation of the string must be an integer. Otherwise, an error will occur.
TypeError
UNIT 03
TypeError
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
Line 1
• Calculate addition
Line 2
• Calculate subtraction
UNIT 03
Line 3
• Calculate multiplication
Line 4
• Floor Division(quotient): it returns 1, which is the quotient of dividing 5 by 3.
UNIT 03
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
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
Line 1 ~ 4
• Addition, subtraction, multiplication, and division of complex numbers
UNIT 03
Focus The data type is critical because the operator to be used varies depending on the data type.
집중
UNIT 03
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
Line 3
• When a number (real number) with decimal points is an input, it is marked as float.
UNIT 03
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
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
Line 1
• String cannot be subtracted, but it can be added. Two strings can be added together to connect.
UNIT 03
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
Line 1 ~ 2
• The strings "~~" and "~~" show the same output result.
UNIT 03
Line 1 ~ 2
• String and numerical values were printed using commas.
• The comma automatically adds a space when outputting.
UNIT 03
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
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
Line 1
• When entering a tap character in the middle of a sentence, enter \t at the corresponding location.
UNIT 03
Line 1
• When entering a tap character in the start of a sentence, enter \t as a first output character.
UNIT 03
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
Line 1
• Python supports negative indexing, and when indexing -1, the last character is indexed.
UNIT 03
Line 1
• Python supports negative indexing, and when indexing -5, the very first character is indexed.
UNIT 03
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
‣ 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
[4] Convert the unit of height from (cm) to (m) height_m = height_cm / 100
End
UNIT 04
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
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
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
Line 1, 2
• Using the “width” and “height” identifiers, we can differentiate the width and height of the rectangle
from other data.
UNIT 04
except in raise
UNIT 04
SyntaxError
UNIT 04
It’s more comprehensible to name weight and height as “weight” and ”height”, rather than x1 and x2.
UNIT 04
Memory space
1.6. String
UNIT 04
1.6. String
1.6. String
UNIT 04
Data Type
- 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
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
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 equal sign does not mean that two values are equal.
UNIT 04
+= 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
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
Unlike the /, the Integer Division is used to discard the decimal point
// Integer Division(Quotient)
of the quotient and only obtain the integer
** Exponentiation Multiply the left operand to the power of the right operand
UNIT 04
Addition + 7+4 11
Subtraction - 7–4 3
Multiplication * 7*4 28
Exponentiation ** 7 ** 2 49
UNIT 04
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
Line 4-8
• The value for change is money – price.
• In coin500s, the change is divided by 500 and then stored.
UNIT 04
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
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
‣ 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.
‣ 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
#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: "))
'David
Doe'
radius = 4.0
name = input(‘input your name ’)
UNIT 04
'David
Doe'
UNIT 04
‣ 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
TypeError
UNIT 04
UNIT 04
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
February February
28 vs.
29
UNIT 05
Pseudocode Flowchart
[4] If any of them is false, it will print False. Print the result on monitor
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
‣ 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
> 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
Line 2
• If the remainder divided by 2 is 0, return True; if not, return False.
UNIT 05
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
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
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 = 100
n is between 0 and 200.
UNIT 05
Logical Operators determine logical expressions and return True or False as results.
x and y x or y not x
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
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.
Focus When logical operators are applied, the results are returned in Boolean types.
UNIT 05
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
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
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
Time
Write the entire code and the expected output results in the note.
UNIT 05
x and y x or y not x
True False
UNIT 05
𝑥+𝑦×𝑧 (𝑥 + 𝑦) × 𝑧
① ①
② ②
UNIT 05
** 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
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
‣ Hint: You must be familiar with the // operator. If not, please go back and review it.
UNIT 05
Sequential Conditional if
Statement Statement Statement
Boolean Conditional
Data Type Expression
UNIT 06
1 2 Select country
Access the website
https://www.random
.org/quick-pick/
[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
순차구조
Sequence 선택구조
Selection 반복구조
Iteration
거짓
False 거짓
False
참
True 참
True
UNIT 06
# 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
‣ 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
How can we choose to run only one of several executable statements? Let's express this in a flowchart.
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
‣ 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
if ` :
# 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
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
('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.
('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
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
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.')
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
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
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
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
('Even number')
Even number
Line 5
• It leaves a block empty to complete the functionality later.
UNIT 06
Line 4
• func function does not do anything because there is no code inside the func() function.
UNIT 06
‣ 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
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.
‣ 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
‣ 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
‣ 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.
if score >= 90 :
print(“You are accepted.”)
print(“You are qualified for a scholarship.”)
UNIT 06
Line 2-5
• Line 3, 4 and 5 are executed because the score is given as 95.
UNIT 06
IndentationError
Line 3-5
• Error occurs because the numbers of indented spaces are different.
UNIT 06
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.3. How to process input values with split and int functions
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
"Left"
"Middle"
"Right"
("Offense failed.")
[4] Check if the direction of the keeper and the direction of the
if computer_choice
ball are identical. == user_choice
"Left"
"Middle"
"Right"
("Offense failed.")
('Accepted')
('Also receive a scholarship')
('Not accepted.')
UNIT 07
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
‣ 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 morning.
True False
hour < 12
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
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
True
num >= 0 Inner if block
False True
num == 0
False
("It is positive.")
("It is negative.")
'is negative.')
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
'is negative.')
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
'is negative.')
-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
'is negative.')
-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
("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
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
Enter score : 88
Your grade is: B
Enter score : 88
Your grade is: B
Enter score : 88
Your grade is: B
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
Enter score : 88
Your grade is: B
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
‣ 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
‣ 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
'Apple'
'Grape'
'Melon'
'Orange'
'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
Time
Write the entire code and the expected output results in the note.
UNIT 07
Time
Write the entire code and the expected output results in the note.
UNIT 07
id :
Log in to Account
UNIT 07
("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
("Welcome.")
Line 2~3
• Receive ID and password from the user.
UNIT 07
("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
("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
("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
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
‣ 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
("Front.")
("Back.")
("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
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 :
[7] print b + m + v + s.
print b + m + v + s
[8] end
End
UNIT 08
Welcome!
UNIT 08
‣ 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
‣ 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
for n in range(5) :
for block that will be
executed repeatedly
UNIT 08
‣ 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
‣ 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
Value that starts generation The size of the value that changes in one increment.
TypeError
UNIT 08
range(5)
0 1 2 3 4 5
returned array
range(0, 5, 2)
range
0 1 2 3 4 5
Stop
10th 10 55 0+1+2+3+4+5+6+7+8+9+10
Iterating
UNIT 08
‣ 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
‣ 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
Enter a number :
5! = 120
UNIT 08
for n in numbers :
for block to be iterated
n 11 22 33 44 55 66
numbers list
UNIT 08
‣ This is a program to find the sum of integer item values in the list using the cumulative addition functionality.
UNIT 08
‣ The sum of the list elements can be easily calculated using the built-in function sum() without using the for
statement.
UNIT 08
‣ The string data type 'Hello' becomes a list of individual alphabet characters.
UNIT 08
‣ 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
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
Time
Write the entire code and the expected output results in the note.
UNIT 08
Time
Write the entire code and the expected output results in the note.
UNIT 08
Time
Write the entire code and the expected output results in the note.
UNIT 08
for statement
False
Are there items in for .. in
sequence?
True
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
print(‘Welcome’)
Take the flag
Five
flags!
Circle five Exit
times and exit
Enters for statement Can pass when you
have five flags
Welcome.
Welcome.
Welcome.
Welcome.
Welcome.
UNIT 08
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
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
‣ 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.
for i in range(5) :
0 1 2 3 4
for loop
i
control variable range(5)
UNIT 08
('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
‣ 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.
# 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
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
How many
days to get out?
UNIT 09
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
[8] End
End
UNIT 09
‣ 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
Form Example
‣ Increase i by 1 from 0 and repeat the code inside while only if it is less than 5.
UNIT 09
‣ 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
for
('Sum of 1 to 10:'.s)
while
‣ 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
‣ 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
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
‣ 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.
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
‣ 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
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
False
Condition
True
Statement
break
Statement
Flowchart of break
UNIT 09
False
Condition
True
Statement
continue
Statement
UNIT 09
‣ 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
‣ 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
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
It is finished!
Circle around if the I’ll pass through
Enter while A
construction is still going on
statement
Opens when
construction ends
Sub block
UNIT 09
("Escaped successfully.")
Is the construction completed? No
Is the construction completed? Yes
Escaped successfully.
UNIT 09
Sum is 55
UNIT 09
('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
('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
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