0% found this document useful (0 votes)
52 views

L1 Conditional Statements

The document discusses conditional statements in Python, including if/else statements, elif statements, and minimizing conditional code. It provides examples of using if/else statements to check conditions and execute different code blocks depending on whether the condition is true or false. It also demonstrates how elif statements can be used to check additional conditions when the if condition is not met. Finally, it shows how conditional statements can be condensed into a single line of code to minimize repetitive code blocks.

Uploaded by

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

L1 Conditional Statements

The document discusses conditional statements in Python, including if/else statements, elif statements, and minimizing conditional code. It provides examples of using if/else statements to check conditions and execute different code blocks depending on whether the condition is true or false. It also demonstrates how elif statements can be used to check additional conditions when the if condition is not met. Finally, it shows how conditional statements can be condensed into a single line of code to minimize repetitive code blocks.

Uploaded by

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

Python Conditional Statements: IF…Else,

ELIF & Switch Case


BySteve CampbellUpdatedSeptember 10, 2022

What are Conditional Statements in Python?


Conditional Statement in Python perform different computations or actions
depending on whether a specific Boolean constraint evaluates to true or false.
Conditional statements are handled by IF statements in Python.

In this tutorial, we will see how to apply conditional statements in Python.

 What is If Statement? How to Use it?


 What happen when “if condition” does not meet
 How to use “else condition”
 When “else condition” does not work
 How to use “elif” condition
 How to execute conditional statement with minimal code
 Python Nested if Statement
 Switch Case Statement in Python

What is Python If Statement?


Python if Statement is used for decision-making operations. It contains a body of
code which runs only when the condition given in the if statement is true. If the
condition is false, then the optional else statement runs which contains some code
for the else condition.
When you want to justify one condition while the other condition is not true, then
you use Python if else statement.

Python if Statement Syntax:

if expression
Statement
else
Statement

Python if…else Flowchart


Let’s see an example of Python if else Statement:
This code is editable. Click Run to Execute

1
#
2
#Example file for working with conditional statement
3
#
4
def main():
5
x,y =2,8
6

7
if(x < y):
8
st= "x is less than y"
9
print(st)
10

11
if __name__ == "__main__":
12
main()

Run

 Code Line 5: We define two variables x, y = 2, 8


 Code Line 7: The if Statement in Python checks for condition x<y which
is True in this case
 Code Line 8: The variable st is set to “x is less than y.”
 Code Line 9: The line print st will output the value of variable st which is “x is
less than y”,

What happen when “if condition” does not meet


In this step, we will see what happens when if condition in Python does not meet.
 Code Line 5: We define two variables x, y = 8, 4
 Code Line 7: The if Statement in Python checks for condition x<y which
is False in this case
 Code Line 8: The variable st is NOT set to “x is less than y.”
 Code Line 9: The line print st – is trying to print the value of a variable that
was never declared. Hence, we get an error.

How to use “else condition”


The “else condition” is usually used when you have to judge one statement on the
basis of other. If one condition goes wrong, then there should be another condition
that should justify the statement or logic.

Example:
This code is editable. Click Run to Execute

1
#
2
#Example file for working with conditional statement
3
#
4
def main():
5
x,y =8,4
6

7
if(x < y):
8
st= "x is less than y"
9
else:
10
st= "x is greater than y"
11
print (st)
12

13
if __name__ == "__main__":
14
main()

Run

 Code Line 5: We define two variables x, y = 8, 4


 Code Line 7: The if Statement in Python checks for condition x<y which
is False in this case
 Code Line 9: The flow of program control goes to else condition
 Code Line 10: The variable st is set to “x is greater than y.”
 Code Line 11: The line print st will output the value of variable st which is “x
is greater than y”,

When “else condition” does not work


There might be many instances when your “else condition” won’t give you the
desired result. It will print out the wrong result as there is a mistake in program
logic. In most cases, this happens when you have to justify more than two
statement or condition in a program.

An example will better help you to understand this concept.

Here both the variables are same (8,8) and the program output is “x is greater
than y”, which is WRONG. This is because it checks the first condition (if condition
in Python), and if it fails, then it prints out the second condition (else condition) as
default. In next step, we will see how we can correct this error.
This code is editable. Click Run to Execute

1
#
2
#Example file for working with conditional statement
3
#
4
def main():
5
x,y =8,8
6

7
if(x < y):
8
st= "x is less than y"
9
else:
10
st= "x is greater than y"
11
print(st)
12

13
if __name__ == "__main__":
14
main()

Run

How to use “elif” condition


To correct the previous error made by “else condition”, we can
use “elif” statement. By using “elif” condition, you are telling the program to print
out the third condition or possibility when the other condition goes wrong or
incorrect.

Example
This code is editable. Click Run to Execute

1
#
2
#Example file for working with conditional statement
3
#
4
def main():
5
x,y =8,8
6

7
if(x < y):
8
st= "x is less than y"
9

10
elif (x == y):
11
st= "x is same as y"
12

13
else:
14
st="x is greater than y"
15
print(st)
16

17
if __name__ == "__main__":
18
main()

Run

 Code Line 5: We define two variables x, y = 8, 8


 Code Line 7: The if Statement checks for condition x<y which is False in this
case
 Code Line 10: The flow of program control goes to the elseif condition. It
checks whether x==y which is true
 Code Line 11: The variable st is set to “x is same as y.”
 Code Line 15: The flow of program control exits the if Statement (it will
not get to the else Statement). And print the variable st. The output is “x is
same as y” which is correct
How to execute conditional statement with minimal
code
In this step, we will see how we can condense out the conditional statement.
Instead of executing code for each condition separately, we can use them with a
single code.

Syntax

A If B else C
Example:

This code is editable. Click Run to Execute

2
def main():
3
x,y = 10,8
4
st = "x is less than y" if (x < y) else "x is greater than or equal to y"
5
print(st)
6

7
if __name__ == "__main__":
8
main()

Run

 Code Line 2: We define two variables x, y = 10, 8


 Code Line 3: Variable st is set to “x is less than y “if x<y or else it is set to “x is
greater than or equal to y”. In this x>y variable st is set to “x is greater than
or equal to y.”
 Code Line 4: Prints the value of st and gives the correct output

 Instead of writing long code for conditional statements, Python gives you
the freedom to write code in a short and concise way.

Python Nested if Statement


Following example demonstrates nested if Statement Python

This code is editable. Click Run to Execute

1
total = 100
2
#country = "US"
3
country = "AU"
4
if country == "US":
5
if total <= 50:
6
print("Shipping Cost is $50")
7
elif total <= 100:
8
print("Shipping Cost is $25")
9
elif total <= 150:
10
print("Shipping Costs $5")
11
else:
12
print("FREE")
13
if country == "AU":
14
if total <= 50:
15
print("Shipping Cost is $100")
16
else:
17
print("FREE")

Run

Uncomment Line 2 in above code and comment Line 3 and run the code again

Switch Case Statement in Python


What is Switch statement?

A switch statement is a multiway branch statement that compares the value of a


variable to the values specified in case statements.

Python language doesn’t have a switch statement.

Python uses dictionary mapping to implement Switch Case in Python

Example

function(argument){
switch(argument) {
case 0:
return "This is Case Zero";
case 1:
return " This is Case One";
case 2:
return " This is Case Two ";
default:
return "nothing";
};
};

For the above Switch case in Python

def SwitchExample(argument):
switcher = {
0: " This is Case Zero ",
1: " This is Case One ",
2: " This is Case Two ",
}
return switcher.get(argument, "nothing")

if __name__ == "__main__":
argument = 1
print (SwitchExample(argument))
Python 2 Example

Above codes are Python 3 examples, If you want to run in Python 2 please consider
following code.

# If Statement
#Example file for working with conditional statement
#
def main():
x,y =2,8

if(x < y):


st= "x is less than y"
print st

if __name__ == "__main__":
main()

# How to use "else condition"


#Example file for working with conditional statement
#
def main():
x,y =8,4

if(x < y):


st= "x is less than y"
else:
st= "x is greater than y"
print st

if __name__ == "__main__":
main()
# When "else condition" does not work
#Example file for working with conditional statement
#
def main():
x,y =8,8

if(x < y):


st= "x is less than y"
else:
st= "x is greater than y"
print st

if __name__ == "__main__":
main()

# How to use "elif" condition


#Example file for working with conditional statement
#
def main():
x,y =8,8

if(x < y):


st= "x is less than y"

elif (x == y):
st= "x is same as y"

else:
st="x is greater than y"
print st

if __name__ == "__main__":
main()

# How to execute conditional statement with minimal code


def main():
x,y = 10,8
st = "x is less than y" if (x < y) else "x is greater than or equal to y"
print st

if __name__ == "__main__":
main()

# Nested IF Statement
total = 100
#country = "US"
country = "AU"
if country == "US":
if total <= 50:
print "Shipping Cost is $50"
elif total <= 100:
print "Shipping Cost is $25"
elif total <= 150:
print "Shipping Costs $5"
else:
print "FREE"
if country == "AU":
if total <= 50:
print "Shipping Cost is $100"
else:
print "FREE"

#Switch Statement
def SwitchExample(argument):
switcher = {
0: " This is Case Zero ",
1: " This is Case One ",
2: " This is Case Two ",
}
return switcher.get(argument, "nothing")

if __name__ == "__main__":
argument = 1
print SwitchExample(argument)
Summary:
A conditional statement in Python is handled by if statements and we saw various
other ways we can use conditional statements like Python if else over here.

 “if condition” – It is used when you need to print out the result when one of
the conditions is true or false.
 “else condition”- it is used when you want to print out the statement when
your one condition fails to meet the requirement
 “elif condition” – It is used when you have third possibility as the outcome.
You can use multiple elif conditions to check for 4th,5th,6th possibilities in your
code
 We can use minimal code to execute conditional statements by declaring all
condition in single statement to run the code
 Python If Statement can be nested

You might also like