Conditional Statements

Conditional Statements in Python

Do you know about conditional statements in python programming?

python conditional statements

Well, don’t you worry! You’ll learn that in this lesson.

Topic Covered in the Lesson

  1. Introduction to conditional statements
  2. Use of Boolean operators
  3. Different types of conditional statements
  4. Use of Operators like Logical in conditional statements

Key Learning Outcomes

At the end of  the lesson, you will be able to:

  1. What are conditional statements?
  2. What is the use of Boolean operators?
  3. What are the different types of conditional statements?
  4. How to use operators in conditional statements?

Let’s begin!

Conditional Statements in Python

Decision-making is as important in any programming language as it is in life. Decision-making in a programming language is automated using conditional statements, in which Python evaluates the code to see if it meets the specified conditions.

The conditions are evaluated and processed as true or false. If this is found to be true, the program is run as needed. If the condition is found to be false, the statement following the If condition is executed.

Python has six conditional statements that are used in decision-making:-

 

  1. If statement
  2. If else statement
  3. Elif (Nested if statement)
  4. If…Elif ladder
  5. Short Hand if statement
  6. Short Hand if-else statement
    Before continuing further, we will look the use of Boolean operators in conditional statements

Boolean Operators

Boolean represents one of the two value: True or False

  • When we compare two values, the expression is evaluated and Python returns the Boolean answer :

For Example:

				
					print(10 > 9)
print(10 == 9)
print(10 < 9)

				
			

Output:

  • The bool() function allows you to evaluate any value, and give you True or False in return.

For Example:

				
					print(bool("Hello"))

print(bool(15))
				
			

Output:

Most Values are True

Almost any value is evaluated to True if it has some sort of content. Any string is True, except empty strings. Any number is True, except 0. Any list, tuple, set, and dictionary are True, except empty ones.

				
					a = bool("abc")
b = bool(123)
c = bool(["apple", "cherry", "banana"])
print(a,b,c)

				
			

Output:

Some Values are False

In fact, there are not many values that evaluate to False, except empty values, such as (), [], {}, “”, the number 0, and the value None. And of course the value False evaluates to False.

				
					a=bool(False)
b=bool(None)
c=bool(0)
d=bool("")
e=bool(())
f=bool([])
g=bool({})
print(a,b,c,d,e,f,g)

				
			

Output:

Functions can Return a Boolean

You can create functions that returns a Boolean Value:

				
					def myFunction() :

  return True

print(myFunction())
				
			

Output:

We can execute code based on the Boolean answer of a function:

Examples:

  • Print “YES!” if the function returns True, otherwise print “NO!”:
				
					def myFunction() :
  return True
if myFunction():
  print("YES!")
else:
  print("NO!")

				
			

Output:

  • Python also has many built-in functions that return a boolean value, like the isinstance() function, which can be used to determine if an object is of a certain data type:
				
					x = 200

print(isinstance(x, int))
				
			

Output:

If statement in Python

When you run a condition in an if statement, Python returns True or False. Python supports the usual logical conditions from mathematics as discussed in the previous session.

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in “if statements” and loops. An “if statement” is written by using the if keyword.

Flowchart:

				
					a = 33
b = 200
if b > a:
    print("b is greater than a")
				
			

Output:

Indentation

Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.

 

Example:

If statement, without indentation (will raise an error):

				
					a = 33
b = 200
if b > a:
print("b is greater than a") 
# you will get an error

				
			

Output:

If-else in Python

An “if-else statement” is written by using the if and else keyword when there are two conditions to show True or False.

Flowchart:

				
					a = 200
b = 33
if b > a:
  print("b is greater than a")
else:
  print("b is not greater than a")

				
			

Output:

Elif (Nested if statement)

There may be a situation when you want to check for another condition after a condition resolves to true. In such a situation, you can use the nested if construct.

The elif keyword is Python’s way of saying “if the previous conditions were not true, then try this condition”.

Flowchart:

				
					a = 33
 b = 33
 if b > a:
    print("b is greater than a")
 elif a == b:
     print("a and b are equal")

				
			

Output:

Else

The else keyword catches anything which isn’t caught by the preceding conditions.

Flowchart:

For Example:

				
					a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

				
			

Output:

Short Hand If

If you have only one statement to execute, you can put it on the same line as the if statement.

Flowchart:

				
					a=33
b=22
 if a > b:
print("a is greater than b")

				
			

Output:

Short Hand If ... Else

If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:

Flowchart:

Example :

One line if else statement:

				
					a = 2
b = 330
print("A") if a > b else print("B")

				
			

Output:

This technique is known as Ternary Operators, or Conditional Expressions. We can also have multiple else statements on the same line:

Flowchart:

				
					a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")

				
			

Output:

Activity 1: Vote Checker

As a democratic country, India is built on the foundations of election. Our Parliament and Legislatures are of the people, by the people and for the people. Voting is a constitutional right that we are privileged to have. We take it for granted, but the constitution has given us the right to elect who we want, and the right to make the change.

There are certain eligibility conditions which a voter need to satisfy, the most important one is age criteria, if a person’s age is equal to or greater than 18 years then the person is eligible to vote otherwise the person is not eligible. Let’s create a program to check whether you are eligible to vote or not.

It can be better understood in terms of the flowchart below.

Step 1 – Flowchart:

Try it yourself !

Step 2 - Let’s Code

The code is pretty simple. Let’s get straight to it. Follow the steps below:

  • First, ask the user to enter the age. So, we will use the input() function with a print statement
				
					print("What is your age")
age=input()

				
			
  • Now we will take the integer type for the age. Here, we will write int() in the variable.
				
					print("What is your age")
age=input()
age=int(age)
				
			
  • Now with the help of if-else condition we will check the age of the user whether it is equal to or greater than 18yrs, if yes then the output displayed would be “You can vote” otherwise the output would be “You cannot vote”.
				
					print("What is your age")
age=input()
age=int(age)
if age >= 18:
  print("You can vote")
else:
  print("You cannot vote")
 
Click the flag to start the script.

				
			

Output:

 

Next Session

Session 9

While Loop

Download PictoBlox – Coding and AI Project Making App

Incase of any difficulty with PictoBlox, please feel free to write us at support@thestempedia.com

Copyright 2021 – Delhi Government All rights reserved | Managed by Valeur Fabtex Private Limited | Technology Partner – STEMpedia