Week 8 - Conditions
Week 8 - Conditions
Example 5+7 == 12
if condition :
Code out of if
statement range
if Statement
• Example.
indentation
Example: Python if Statement
# If the number is positive, we print a message
Output
Try to enter -1
Example: Python if statement
• In the previous example, num > 0 is the condition.
• The body of the “if statement” will be executed only if this
condition is True.
• When the variable num is equal to 3, the condition is True,
and the statement inside the body of “if statement” is
executed.
• When the variable num is equal to -1, the condition is False,
and the statement inside the body of is skipped.
• The print() statement outside of the “if statement” block is
executed regardless of the condition.
if-else statement:
if-else Statement
• What if you want to execute code if the condition is True and
execute another code if the condition is False?
• You can use ‘else’ with if statement.
• The else keyword will execute another code when the
condition is False.
• Example:
if-else Statement Example
If-else Statement … Cont’d
• Note that you can use one else only in each if
statement block. The code below is wrong
if...else Exercise
• Without writing the code,
• what is the output when num is 4?
• what is the output when num is 5?
The if-elif statement:
if-elif statement
• Sometimes, you want to test more than one condition.
In this case, you can use elif (short for else if) in if
statement block.
• The elif keyword means "if the previous condition is not
true, then try this condition".
Example: if-elif
Output
Using if for selection
Create a program that display the following list:
1- Area of Rectangle
2- Area of Triangle
3- Area of Circle
After that, ask the user to select a number by
writing the number 1, 2 or 3. If the user enters 1,
then ask to enter the length and width. If 2 is
selected, then ask to enter the base and height. If 3
is selected, then ask to enter the radius. For each
choice, calculate and display the area.
Review Questions
• What is the purpose of using if ?
• When should we use if-else?
• When should we use if-elif?
• How many statements will be as a result of if-
elif block?
• Can we use “==“ operator with strings?
• Can we use “>” and “<“ operators with strings?
Review Questions
• What is the output of this code if the user
enters 10?