Lecture 12 If Statement

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 20

Chapter 12:

If Statement
Alex Kuhudzai
alexkuhudzai@gmail.com
Cape Peninsula University of Technology,
Cape Town, South Africa
The If Statement
 The if statement is used to create a decision structure, which allows a program to
have more than one path of execution. The if statement causes one or more
statements to execute only when a Boolean expression is true.
 A control structure is a logical design that controls the order in which a set of
statements execute. A sequence structure is a set of statements that execute in the
order in which they appear. For example, the following code is a sequence
structure because the statements execute from top to bottom:
The If Statement
 The if statement is used to create a decision structure, which allows a program to
have more than one path of execution. The if statement causes one or more
statements to execute only when a Boolean expression is true.
 A control structure is a logical design that controls the order in which a set of
statements execute. So far in this book, we have used only the simplest type of
control structure: the sequence structure. A sequence structure is a set of
statements that execute in the order in which they appear. For example, the
following code is a sequence structure because the statements execute from top to
bottom:
The If Statement
 Although the sequence structure is heavily used in programming, it cannot handle every
type of task. This is because some problems simply cannot be solved by performing a set
of ordered steps, one after the other. For example, consider a pay calculating program that
determines whether an employee has worked overtime. If the employee has worked more
than 40 hours, he or she gets paid extra for all the hours over 40. Otherwise, the overtime
calculation should be skipped. Programs like this require a different type of control
structure: one that can execute a set of statements only under certain circumstances.
 This can be accomplished with a decision structure. (Decision structures are also known as
selection structures.) In a decision structure’s simplest form, a specific action is performed
only if a certain condition exists. If the condition does not exist, the action is not
performed. The flowchart shown on the next slide shows how the logic of an everyday
decision can be diagrammed as a decision structure. The diamond symbol represents a
true/false condition. If the condition is true, we follow one path, which leads to an action
being performed. If the condition is false, we follow another path, which skips the action.
The If Statement

 In the flowchart, the diamond symbol indicates some condition that must be tested. In this
case, we are determining whether the condition Cold outside is true or false. If this condition
is true, the action Wear a coat is performed. If the condition is false, the action is skipped.
The action is conditionally executed because it is performed only when a certain condition
is true.
The If Statement
 Let’s look at the following example of the if statement:
if sales > 50000:
bonus = 500.0
 This statement uses the > operator to determine whether sales is greater than 50,000. If
the expression sales > 50000 is true, the variable bonus is assigned 500.0. If the
expression is false, however, the assignment statement is skipped. The figure on the
next slide shows a flowchart for this section of code.
The If Statement
The If Statement
 The following code uses the == operator to determine whether two values are equal. The
expression balance == 0 will be true if the balance variable is assigned 0. Otherwise
the expression will be false.
if balance == 0:
# Statements appearing here will
# be executed only if balance is
# equal to 0.
 The following code uses the != operator to determine whether two values are not equal.
The expression choice != 5 will be true if the choice variable does not reference the value
5. Otherwise, the expression will be false.
if choice != 5:
# Statements appearing here will
# be executed only if choice is
# not equal to 5.
An Example
 Kathryn teaches a science class and her students are required to take three tests.
She wants to write a program that her students can use to calculate their average
test score. She also wants the program to congratulate the student enthusiastically
if the average is greater than 95.
 Lets put together the pseudocode

Get the first test score


Get the second test score
Get the third test score
Calculate the average
Display the average
If the average is greater than 95:
Congratulate the user
The code
1 # This program gets three test scores and displays
2 # their average. It congratulates the user if the
3 # average is a high score.

5 # The HIGH_SCORE named constant holds the value that is


6 # considered a high score.
7 HIGH_SCORE = 95
8
9 # Get the three test scores.
The code
10 test1 = int(input('Enter the score for test 1: ' ))
11 test2 = int(input('Enter the score for test 2: ' ))
12 test3 = int(input('Enter the score for test 3: ' ))
13
14 # Calculate the average test score.
15 average = (test1 + test2 + test3) / 3
16
17 # Print the average.
18 print(f'The average score is {average}.')
The code
20 # If the average is a high score,
21 # congratulate the user.
22 if average >= HIGH_SCORE:
23 print('Congratulations!’)
24 print('That is a great average!')
The If –Else Statement
 An if-else statement will execute one block of statements if its condition is true, or another
block if its condition is false.
 Let us look at the flow chart below
The If –Else Statement
 The decision structure in the flowchart tests the condition temperature < 40. If this
condition is true, the message "A little cold, isn't it?" is displayed. If the condition is false,
the statement message "Nice weather we're having." is displayed.
 In code, we write a dual alternative decision structure as an if-else statement. Here is the
general format of the if-else statement:
if condition:
statement
statement
etc.
else:
statement
statement
etc.
The If –Else Statement
 When this statement executes, the condition is tested. If it is true, the block of
indented statements following the if clause is executed, then control of the
program jumps to the statement that follows the if-else statement. If the condition
is false, the block of indented statements following the else clause is executed,
then control of the program jumps to the statement that follows the if-else
statement. This action is described in in the figure below:
Example
 Chris owns an auto repair business and has several employees. If any employee
works over 40 hours in a week, he pays them 1.5 times their regular hourly pay
rate for all hours over 40. He has asked you to design a simple payroll program
that calculates an employee’s gross pay, including any overtime wages.
Get the number of hours worked.
Get the hourly pay rate.
If the employee worked more than 40 hours:
Calculate and display the gross pay with overtime.
Else:
Calculate and display the gross pay as usual.
The Code
The Code
Another Example
 Let us write a code that asks the user to enter an integer as an input and displays
whether the integer is even or odd
Another Example

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy