Samsung If Statement and Loops
Samsung If Statement and Loops
2.1. How the lottery machine works 2.4. Automatic lottery machine final code
('Enter a three-digit lottery number : ').split() ('Enter a three-digit lottery number : ').split()
# If one of the numbers match the winning number # If one of the numbers match the winning number
#Increase n #Increase n
2.3. Programming Plan 1.1 Conditional statements that have different flows depending on the
conditions
Start
[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 1
16 /09 /2024
1.2. Basic control structures of a program 1.4. Sequential statements and various flow statements
Sequence
순 차구조 선Selection
택구조 Iteration
반 복구조
False
거 짓 거False
짓
True
참 True
참
‣ 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.
‣ 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.
How can we choose to run only one of several executable statements? Let's express this in a flowchart.
300 • <Executable Statement 1> or <Executable Statement 2> is executed according to specific conditions.
num = num + 100 • Conditions are determined by <Conditional Statement>. The conditional statement must have a True or False value.
num
1.7. If statement and related terms that are executed in specific circumstances 1.9. if statement example code
Example of converting to a different flow according to the value of the age variable
18 24
Situation 1: print "youth discount" if the age is under 20. age
age
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. False False
age < 20 age < 20
‣ This is called a conditional expression. And this conditional expression is evaluated in Boolean type, which contains
True or False values. True True
print(‘youth print(‘youth
‣ The relational operator from the previous chapter is used to compare two operands, and the result of the relational
discount’) discount’)
operator is shown in True or False value. Thus, it can be used in conditional expressions.
# 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
if keyword Conditional statement colon ‣ Learn the necessity of indentation and the term block.
‣ The code below prints an error.
if ` :
('youth discount')
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 ‣ A chunk of code that can be executed when a condition is true is called a block.
over 1,000.
< operator.
‣ The conditional block of a conditional statement must be indented. Otherwise, an error occurs as above.
‣ (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.
3
16 /09 /2024
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
('youth discount')
youth discount
t
Line 3-5
• Since age is 18, age <20 is True and Line 3-5 are printed.
('youth discount')
youth discount
Enter an integer : 15
15 is a multiple of 3 and 5.
('youth welcome')
4
16 /09 /2024
3.2. Scenario verifying if two strings match 4.1. Role of pass statement
Line 4
Line 3 • func function does not do anything because there is no code inside the func() function.
• 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.
5
16 /09 /2024
Time
‣ 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.
Write the entire code and the expected output results in the note.
Enter integer:
x = 50
50 is a natural number.
Example Output
or
Enter integer:
x = -10
Write the entire code and the expected output results in the note.
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.
6
16 /09 /2024
1.1. If statements that are executed when certain conditions are satisfied 1.3. Indentation in Python
‣ Therefore, 'x is greater than 1' is printed on the screen. Here, the line below :(colon) must be indented. 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.
‣ 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 IndentationError
left and right values are identical or not.
("Enter the score: "))
# Caution : if indentation is different an error occurs
("Congratulations.")
("You are accepted.")
("You are qualified for a scholarship.")
Line 3-5
• Error occurs because the numbers of indented spaces are different.
‣ 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.
The split uses space as the default value. So, each value is inserted using the space as a separator.
Block: a group of sentences. In this way, a character that divides a string into one or more individual strings is called a separator.
if score >= 90 :
print(“You are accepted.”)
print(“You are qualified for a scholarship.”)
7
16 /09 /2024
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
8
16 /09 /2024
Output example
Enter age: 20
Enter height in cm: 180
You can enter.
if - else if-else-elif
9
16 /09 /2024
1.1. The scale of the global game market 1.4. Additional reference for penalty shootout
"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
10
16 /09 /2024
2.3. Penalty shootout game final code 1.2. if statement without else statement
"Middle"
"Right" 10
("Which side will you attack?(left, middle, right) : ") False hour
('It is morning.') hour < 12
("Offense failed.")
True
('It is afternoon.')
("Congrats!! Offense succeeded.") print(‘It is morning.’)
('computer defense position :', computer_choice)
It is morning.
False
hour>= 12
True
print(‘It is afternoon.’)
‣ 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
1.1. else statement which is executed when the condition is false 1.4. Comparing flowchart of if-else and if
False
print(‘It is morning.’) print(‘It is afternoon’) hour>= 12
True
print(‘It is afternoon.’)
11
16 /09 /2024
1.5. if-else statement to determine odd/even numbers 1.7. Using nested if – else statement to discriminate even/odd numbers
1.6. Writing if-else statement inside if-else statement 1.7. Using double if – else statement to discriminate even/odd numbers
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.
1.6. Writing if-else statement inside if-else statement 1.8. Flow control in various cases
12
16 /09 /2024
1.8. Flow control in various cases 2.3. Reason to use nested conditional statement
'is negative.')
‣ 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.
2.1. How to continuously examine other conditions when the conditions are 2.4. Grade Generator example A: Code using multiple if statements
false ('Enter score : '))
# If 90 or above, 'A'
# If under 90, 80 or above, 'B'
# If under 80, 70 or above, 'C'
2.2. Code example that prints positive, negative, and 0 after receiving integer 2.5. Grade generator example B : Grade generator code using if-else
as an input statement
('Enter score : '))
# If 90 or above, 'A'
("Enter an integer: "))
("It is negative.")
# If under 70, 60 or above, 'D'
Enter an integer: 6
It is positive. #If under 60, 'F'
Enter an integer: -5 ('Your grade is: ', grade)
It is negative.
Enter score : 88
Enter an integer: 0 Your grade is: B
It is 0.
‣ 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.
13
16 /09 /2024
2.5. Grade generator example B : Grade generator code using if-else 2.8. Grade generator example C: grade generator code using if-elif-else
statement statement
('Enter score : ')) ('Enter score : '))
# If 90 or above, 'A' # If 90 or above, 'A'
# If not 'A', 'B' if 80 or above
# If under 90, 80 or above, 'B'
# If not 'B', 'C' if 70 or above
# If under 80, 70 or above, 'C' # If not 'C', 'D' if 60 or above
# Otherwise, 'F'
# If under 70, 60 or above, 'D'
('Your grade is: ', grade)
#If under 60, 'F'
Enter score : 88
('Your grade is: ', grade) Your grade is: B
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
‣ There are too many indentations. statement.
‣ For multiple conditions, what could be a simpler way? ‣ Also the code is easy to understand because the condition is clear.
2.6. Comparing if-elif statement and elif statement 2.8. Grade generator example C: grade generator code using if-elif-else
statement
Code using if-else Code using if-elif 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’
‣ Both codes perform the same task.
False
‣ The code on the right is indented less and the number of lines is reduced. Thus the code is easier to read and True
understand. score>=60 grade = ‘D’
False
grade = ‘F’
2.7. Grade generator example C: if-elif-else statement execution flowchart 2.8. Grade generator example C: grade generator code using if-elif-else
statement
14
16 /09 /2024
‣ The above code that generates results with two conditions when a = 10 and b = 14.
(('Enter item number(between 1~4) >> ')))
‣ The if statement in this code prints outputs by using logical operators and and or. (('Enter number of items(between 1~10) >> ')))
‣ 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.
15
16 /09 /2024
'Grape' Time
'Melon'
'Orange'
Write the entire code and the expected output results in the note.
(money, 'won received. Your change is', change, 'won.')
'Grape'
'Melon'
'Orange'
Write the entire code and the expected output results in the note.
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.
16
16 /09 /2024
("Welcome.")
id :
("ID not found.")
Line 2~3
• Receive ID and password from the user.
1.2. The program resolution code for ID verification. 1.3. Program to verify ID and password
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.
("Welcome.")
Enter ID:
Enter your ID: ("ID not found.")
Enter Password:
("The password is wrong.")
Welcome.
Password Enter ID: ilovepython
Enter password: mypass1234
Welcome.
17
16 /09 /2024
1.3. Program to verify ID and password 2.2. Coin tossing game using a random function
("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.
2.1. Code example of random number generation 2.2. Coin tossing game using a random function
("Front.")
("Back.")
("Game finished.")
18
16 /09 /2024
Output example
y
Enter x,y coordinates: -5 6
In the second quadrant
2 quadrant 1 quadrant
3 quadrant 4 quadrant
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.
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.
19
16 /09 /2024
1.1. Obesity is the cause of various diseases and increases the burden of
medical expenses in society as a whole
for in
iteration range
20
16 /09 /2024
2.1. What is Food Combination? 3.2. Delicious Food Combinations operation process
["Rye bread", "Wheat", "White"]
["Meatball", "Sausage", "Chicken breast"]
["Lettuce", "Tomato", "Cucumber"]
["Mayonnaise", "Honey Mustard", "Chili"]
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
3.1. How to make Delicious Food Combinations 3.4. Delicious Food Combinations final code
["Rye bread", "Wheat", "White"]
["Meatball", "Sausage", "Chicken breast"]
["Lettuce", "Tomato", "Cucumber"]
["Mayonnaise", "Honey Mustard", "Chili"]
21
16 /09 /2024
‣ 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.
1.1. Necessity of iterated statements 1.2. Basics of range and loop statement syntax
for n in range(5) :
for block that will be
executed repeatedly
Welcome!
‣ Write print function 5 times to print 5 times repeatedly without using loop statements.
‣ Consider repeating this task 1000 times. ‣ To repeat the above code 10 times, put 10 inside the parentheses range ().
‣ This is inefficient. ‣ This simple code executes a huge amount of tasks, and code modification and maintenance becomes easier.
‣ To repeat 100 times : change to range(100).
22
16 /09 /2024
TypeError
‣ 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.
range(5)
returned array
range(start = 0, stop, step = 1)
23
16 /09 /2024
08
2.2. About range 2.4. Overlap of sum() function and variable name sum
range(0, 5, 2)
range
0 1 2 3 4 5
‣ The sum() function calculates the sum of the elements in the list. Thus, a sum of numbers from 1 to 10, 55 is printed.
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.
Stop
10th 10 55 0+1+2+3+4+5+6+7+8+9+10
Iterating
24
16 /09 /2024
08
‣ The sum of the list elements can be easily calculated using the built-in function sum() without using the for
variable List to be visited statement.
for n in numbers :
for block to be iterated
n 11 22 33 44 55 66
numbers list
3.1. Object with order 3.3. Converting string data type to list data type
25
16 /09 /2024
V
J-Hope
RM
‣ You can convert the string 'Hello' into a list of character elements by applying the list function.
Example Output Jungkook
‣ Place the string after the for in expression. This will separate the string into individual characters, enabling the loop Jin
to visit each character. Jimin
Suga
‣ Insert the end =‘ ‘ argument inside the print function. It prints another line without changing the line after printing
ch.
Time
Write the entire code and the expected output results in the note.
08
Time
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.
Write the entire code and the expected output results in the note.
Time
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.
Write the entire code and the expected output results in the note.
26
16 /09 /2024
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
Example Output Sum of odd numbers from 1 to 100 : 2500 called an infinite loop.
Time
Write the entire code and the expected output results in the note.
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.
27