0% found this document useful (0 votes)
9 views27 pages

Samsung If Statement and Loops

Dev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views27 pages

Samsung If Statement and Loops

Dev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

16 /09 /2024

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

# If n is 3, three numbers matched # If n is 3, three numbers matched


('You won the lottery!') ('You won the lottery!')

Enter a three-digit lottery number :


You won the lottery!

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

2.3. Programming Plan 1.1 Conditional statements that have different flows depending on the
conditions
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 1
16 /09 /2024

1.2. Basic control structures of a program 1.4. Sequential statements and various flow statements

‣ 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. ‣ 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

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

False
거 짓 거False

True
참 True

1.2. Basic control structures 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.
‣ 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>

1.3. Sequential statements 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


# 100 is printed tasks is called a branch.
# 100 is added to num and 200 is printed False
True Conditional
# 100 is added again to num and 300 is printed Statement

100 Executable Executable


num = 100 + 100 statement 1 statement 2
num
200
num = num + 100 num + 100

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

A structure in which commands are executed sequentially


2
16 /09 /2024

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

1.8. if statement syntax 1.10. Block of if statement


Conditional statement and block

if keyword Conditional statement colon ‣ Learn the necessity of indentation and the term block.
‣ The code below prints an error.
if ` :

indent block executed when a condition is true ('youth discount')

('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.

1.9. if statement example code 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.
# if age is 18
# result of age < 20 is True ‣ [Indentation code 1] If the conditions of age <20 is satisfied
('youth discount')
youth discount
('youth discount')
('Welcome')
‣ When the age value is 18, the conditional statement of age <20 becomes True,
so 'youth discount' is printed on the screen. youth discount
Welcome
‣ When the age value is 20 or more, no output is printed. ‣ [Indentation code 2] If the conditions of age <20 is not satisfied
False
age < 20

True ('youth discount')


('Welcome')
print(‘youth discount’) Welcome

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

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


‣ [Indentation code 4] If the condition age <20 is not satisfied
24 ('Enter an integer: ')) # Change input value to integer type
('age', age) 'is a multiple of 3.')
('youth welcome')
('youth discount') Enter an integer : 6
No output 6 is a multiple of 3.

Line 3-5 Line 2


• Since the age is 24, age <20 is False and Line 3-5 are not printed. • 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.

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.

Wrong Indentation 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.
('age', age)
('youth welcome') • In this way, it is possible to determine whether the number is a multiple of 3 as well as 5.
('youth discount')

('youth welcome')

4
16 /09 /2024

2.3. == operator 3.2. Scenario verifying if two strings match

('Two strings match.')

('ID matches.') ('Two strings are different.')

Enter your id: david Two strings are different.


ID matches.
Line 5
Line 2, 5 • If the values of the two strings are different, Line 6 block is executed. In this case, it is printed because the
• If the string input is 'david', the two strings s and my_id match, and Line 5 is executed. When another string is values of str1 and str2 are different.
given, Line 5 is not executed.

3.1. Even-number discrimination scenario 4.1. Role of pass statement

("Enter an integer : "))

"is an even number.")

Enter an integer : 50 ('Even number')


n = 50
50 is an even number.
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 5
line 4 is executed.
• It leaves a block empty to complete the functionality later.

3.2. Scenario verifying if two strings match 4.1. Role of pass statement

('Two strings match.')

('Two strings are different.')

Two strings are different.

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

4.2. pass statement’s role


pass statement plays an important role.
Enter game score : 1500
game_score = 1500
You are a master.
Example Output or
Enter game score : 100
game_score = 100

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

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


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

The general form of a function

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

("x is greater than 1.")


("Enter the score: "))
x is greater than 1. # if the condition is true, block indent is all executed
("Congratulations.")
‣ Check the function of the if statement with an actual code. Put 100 in the variable x and write the if statement as ("You are accepted.")
above. In this case, since the conditional expression x>1 returns True, the following execution is run. ("You are qualified for a scholarship.")

‣ 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.

1.2. Relational operator =, == 1.3. Indentation in Python


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 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.")

("You are accepted.")

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

1.3. Indentation in Python 2.1. split method

‣ 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.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.

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

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

Double Conditional Random


Statement Numbers

9
16 /09 /2024

1.1. The scale of the global game market 1.4. Additional reference for penalty shootout

1.2. FIFA Online 4 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

1.3. Penalty shootout rules 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

10
16 /09 /2024

2.3. Penalty shootout game final code 1.2. if statement without else statement

# randomly generates numbers among 1,2,3


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

"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.’)

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’)

1.1. else statement which is executed when the condition is false 1.4. Comparing flowchart of if-else and if

‣ The left is much clearer. 10


‣ Code as follows in Python.
hour
('Accepted') 10
('Also receive a scholarship') False
hour < 12
('Not accepted.') 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.’)

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

'is an even number.') 'is negative.')

'is an odd number.') 'is not negative.')

10 is and even number 'is an even number.')

'is an odd number.')


Line 2, 4 100 is not negative.
• If num is divided by 2 and the remainder is 0, the lower Line 3 block is executed if the remainder is 0. 100 is even number.

• Otherwise, Line 5 block under else is executed.


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.

1.6. Writing if-else statement inside if-else statement 1.7. Using double if – else statement to discriminate even/odd numbers

True 'is negative.')


num >= 0 Inner if block
'is not negative.')
False True 'is an even number.')
num == 0
'is an odd number.')
False
100 is not negative.
print(”Negative.") print(”Positive. ") print(”It is 0.") 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.

1.6. Writing if-else statement inside if-else statement 1.8. Flow control in various cases

‣ 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
'is negative.')
result on a screen.
'is not negative.')
("Enter an integer: "))
# make sure to indent the block 'is an even number.')
# check specific conditions inside the block
("It is 0.") 'is an odd number.')
("It is positive.") -100 is negative.
("It 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
Enter an integer: -20 if-else statement on the inside is called the inner if-else statement. Closely examine the code.
It is negative.
‣ The if-else conditional statement of Line 2 and 4 is an outer if-else statement. The if statement of Line 2 is executed
‣ As such, you can solve problems by inserting an if-else statement inside an if-else statement. only when the value of num is less than 0, i.e., negative.

12
16 /09 /2024

1.8. Flow control in various cases 2.3. Reason to use nested conditional statement

'is negative.')

'is not negative.') Score Grade


'is an even number.') 90 ~ 100 A
'is an odd number.') 80 to Less than 90 B
-100 is negative. 70 to Less than 80 C
60 to Less than 70 D
‣ 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. Below 60 F

‣ 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'

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


num > 0 print(”It is positive.")
#If under 60, 'F'
False ('Your grade is: ', grade)
True
num == 0 print(”It is 0.") Enter score : 88
Your grade is: B
False
‣ Grade B for 88 points is properly printed.
print(”It is negative.")
‣ 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.

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: "))

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


("It is positive.")

("It is 0.") # If under 80, 70 or above, 'C'

("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

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


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

14
16 /09 /2024

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.
('Enter the year: '))
Comparison operator Explanation
'is a leap year?',
== Returns True if two operands have identical value.
Enter the year : 2021
!= Returns True if the values of the two operands are different.
2021 is a leap year? False
> 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.

2.10. Example of a complex conditional expression 3.1. Application exercise

# 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.
This is David’s fruit shop.
1: Apple( price : 5000 won)
‣ The above code that generates results with two conditions when a = 10 and b = 14. 2: Grape( price : 6000 won)
‣ The if statement in this code prints outputs by using logical operators and and or. 3: Melon( price : 8000 won)
4: Orange( price : 2000 won)
‣ 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.
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.

2.10. Example of a complex conditional expression 3.1. Application exercise

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


# first conditional statement ('This is David’s fruit shop.')
('Both are positive.') ('1: Apple( price : 5000 won)')
# second conditional statement ('2: Grape( price : 6000 won)')
('More than one is positive.')
('3: Melon( price : 8000 won)')
More than one is positive. ('4: Orange( price : 2000 won)')

‣ 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

3.1. Application example

Enter the alphabet : k


'Apple'
Example Output
K is a consonant

'Grape' Time

'Melon'

'Orange'

('Fruit selected :', fruit)


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

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

('Not enough money.')

Write the entire code and the expected output results in the note.
(money, 'won received. Your change is', change, 'won.')

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 Write two integers: 30 3
Example Output 30 is a multiple of 3
verification through the if-elif statement.
‣ In such way, the if-elif-else statement simplifies the code.
Time
'Apple'

'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

1.1. Program for ID verification 1.3. Program to verify ID and password

("Enter ID: ")


("Enter Password: ")

("Welcome.")
id :
("ID not found.")

("The password is wrong.")


Log in to Account
Enter ID: ilovepython
Enter password: mypass1234
Welcome.

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

("Enter the ID: ") ("Enter ID: ")


("Enter Password: ")
("Welcome.")
("Welcome.")
("ID not found.")
("ID not found.")
Enter the ID: ilovepython
Welcome. ("The password is wrong.")

Enter ID: ilovepython


‣ Take a string input using the input function. Next, the relational operator == checks whether the input string Enter password: mypass1234
identical to 'ilovepython'. If the result of the relational operator is True, print 'Welcome’. 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.

1.3. Program to verify ID and password

("Enter ID: ")


("Enter Password: ")

("Welcome.")
Enter ID:
Enter your ID: ("ID not found.")
Enter Password:
("The password is wrong.")
Welcome.
Password Enter ID: ilovepython
Enter password: mypass1234
Welcome.

Log in to Account 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.

17
16 /09 /2024

1.3. Program to verify ID and password 2.2. Coin tossing game using a random function

("Enter ID: ")


("Enter Password: ")

("Welcome.")

("ID not found.")


‣ This is a test code for making a coin tossing game with a random function.
("The password is wrong.")
‣ Run several times. 0 or 1 will be printed.
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.

2.1. Code example of random number generation 2.2. Coin tossing game using a random function

# call the random module ("Start coin tossing game. ")

("Front.")

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

Start coin tossing game.


Line 1 Front.
• In order to use the function randint which produces random numbers between 1 and 100, the random number Game finished.
module must be imported using an import statement.
Line 4
• The function called randrange(2) is a function that returns 0 or 1 through a random number generator.

2.2. Coin tossing game using a random function

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

1.2. How to prevent obesity

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"]

('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

2.2. Additional Information for Food Combination 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

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"]

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

21
16 /09 /2024

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.

1.1. Necessity of iterated statements 1.2. Basics of range and loop statement syntax

variable range function

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

Welcome!

1.1. Necessity of iterated statements 1.3. for statement example

‣ 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

1.4. loop control variable


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

‣ 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.

2.2. About range


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.

2.1. Structure of range 2.2. About range

range(5)

Value that stops generation.


This value is excluded from generation.
0 1 2 3 4 5
Value that starts generation The size of the value that changes in one increment.

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

Start value Stop value


(Stop value not returned)

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.

step value = 2 step value = 2


start value stop value

08

Overlapping use of sum() function and variable name


2.3. Problem solving using for in range
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)

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

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.

2.5. Computing factorial

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
('Enter a number: '))
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 Enter a number :
7th 7 28 Iterate 0+1+2+3+4+5+6+7 5! = 120
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

24
16 /09 /2024

08

3.2. Cumulative addition code example


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
('Sum of list items : ', s)
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 Sum of list items : 150
expression. This is another big advantage of Python.
‣ This is a program to find the sum of integer item values in the list using the cumulative addition functionality.

3.1. Object with order 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
variable List to be visited statement.

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

3.1. Object with order 3.3. Converting string data type to list data type

# different values are printed each time


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

25
16 /09 /2024

3.4. How to use string data type in for loops

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

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.
Example Output Sum of integers from 1 to 100 : 5050

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.

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

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.

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.

27

You might also like