Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

3.3 - Conditional Execution Using If Statement

The document discusses the if statement in Python which allows conditional execution of code. It explains the basic syntax and flow of if statements including else and elif blocks. It also covers nested if statements and importance of proper indentation. Examples are provided to illustrate different types of if statements.

Uploaded by

karlstephan065
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

3.3 - Conditional Execution Using If Statement

The document discusses the if statement in Python which allows conditional execution of code. It explains the basic syntax and flow of if statements including else and elif blocks. It also covers nested if statements and importance of proper indentation. Examples are provided to illustrate different types of if statements.

Uploaded by

karlstephan065
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

3.

3 — Conditional execution using if statement

Flow of execution

Flow of execution refers to order in which statements (lines of code) in


our program are executed.
So far in our programs, each line was executed unconditionally. For most
programs, it is not enough as we need to make choices or run code
repeatedly.
We need to control the flow of execution in our programs.
The control flow of a program determines:
Which parts of the code should always be executed
Which parts should be executed only under certain conditions
Which parts should be executed repeatedly
All of these can be achieved using control flow statements:
if statement for conditional execution
for and while loops for repeated execution
if statement — to execute or not to execute

To write useful programs, we almost always need to check certain


conditions.
We might want to execute certain statements only in specific
situations.
if statement give us this ability

if condition :
code block

condition must be a boolean expression


code block is one of more Python statements (lines of code)
code block is executed only if the condition is True, otherwise it is
skipped.
Notice space before code block. It is called indentation.
Indentation is required to tell Python that the code belongs
inside if statement.
Typically, 4 spaces are used for indentation.
We can use tab key to indent.
Try the following examples with different values for variables.
Example 1:
1 x = 10
2 if x > 0:
3 print(x, "is positive")

Example 2:

1 num = -5.2
2
3 absolute_num = num
4
5 if num < 0:
6 absolute_num = -num
7
8 print("Absolute value of", num, "is", absolute_num)

Output

Absolute value of -5.2 is 5.2

Example 3:

1 x = 1000
2 y = 123
3
4 min_value = x
5
6 if y < min_value:
7 min_value = y
8
9 print("Minimum of", x, "and", y, "is", min_value)

Output

Minimum of 1000 and 123 is 123


if statement with else part

if statements can have else part to make a choice between two code
blocks.

if condition :
code block1

else :
code block2

When condition is True , code block1 is executed


Otherwise (condition is False ) and code block2 is executed
The code blocks are also called branches of the if-statement.

1 x = 10 # change this to -5 and run


2
3 if x > 0:
4 print("x is positive.")
5 else:
6 print("x is not positive.")

Variables can be created inside the branches of if statement.


Be careful that all branches have same variable names!
There is an error in code below. To fix it, we have to make sure both
branches of if statement create the same variable name.
1 income = 15000
2
3 if income < 12000:
4 tax = 0.0
5 else:
6 taxes = income * 15.5 / 100 # Change variable name to tax
7
8 print("Your tax is", tax)

Output

NameError: name 'tax' is not defined

Try it!
Write a program that takes an integer as input from the user, call it
X . Then the program should display either The number X is even

OR The number X is odd , depending on the input received.

Show answer
Chained if-elif-else statement

Sometime, we want to check a series of mutually exclusive conditions.


To do so, we can use a series of elif blocks in an if statement.

1 income = 20000
2
3 if income < 12000:
4 tax = 0.0
5 elif income < 30000:
6 tax = income * 15.0 / 100
7 elif income < 100000:
8 tax = income * 20.0 / 100
9 else: # if all above were False i.e. income >= 100000
10 tax = income * 25.0 / 100
11
12 print("Your tax is", tax)

Mutually exclusive — only one of these blocks will get executed.


Order matters! If first of the conditions is True , later conditions are
not checked.
As soon as one block is executed, the remaining will be skipped.
You can have as many elif ’s as you want
The final else part is not required so you may omit it if not needed.
Example

Is there anything wrong in code below?

1 money = 5000.0
2
3 if money > 0.0:
4 print("Positive balance")
5 elif money > 1000.0:
6 print("You're rich! Go celebrate!")
7 else:
8 print("Uh-oh. No money.")

Output

Positive balance

Order of conditions matters!


Show answer
Nested if statements

if statements can be nested inside other if statements.

1 x = 10
2 if x > 0:
3 print("Positive")
4 else:
5 if x < 0:
6 print("Negative")
7 else:
8 print("Zero")

Above code is logically equivalent of the chained if below:

1 x = 10
2 if x > 0:
3 print("Positive")
4 elif x < 0:
5 print("Negative")
6 else:
7 print("Zero")

You can use either nested or chained conditionals, but note that nested
conditional can easily become hard to read.
Correct indentation is essential!

Sometimes, incorrect indentation may not give an error but it may lead to
unexpected program.

1 income = 1000
2
3 if income < 12000:
4 print("You don't have to pay tax.")
5 tax = 0.0
6 else:
7 print("You have to pay tax.")
8 tax = income * 15.0 / 100 # this line should be indented
9
10 print("Your tax is", tax)
Try it

Write a program that given a number x prints either of the following:

x is even
x is an odd number multiple of 3
x is an odd number not multiple of 3

Show answer

You might also like