Conditional Statements in Python (With Examples):

conditional-statements-in-python-with-examples

Wanna know “What is a conditional statement in python” basically conditional statements are used to make decisions based on certain conditions.

If you are new then visit the previous module to learn about Python Fundamentals to get an exact understanding of this module. So, let’s start without wasting time.

Conditional statements are also used to control the flow of the program. The main types of conditional statements are:

What is “if” statement in python:

The if statement executes a block of code if a condition is True. It runs the loop only when the state is true otherwise not.

The most important thing you need to know when we use conditional statements the next line will start after the space of TAB.

if condition:
    print("Condition is True")
# execute this block if condition is True

If we don’t give TAB space after the conditional statement we got an error.

if condition:
print("Condition is True")
# execute this block if condition is True

Using “elif” Ststement in Python:

The elif statement is used to check an additional condition if the previous condition(s) is False.

a=7
if a==5:
    print('Hello Word')
# Here condition is false because a is not equal to 5, so compiler moves to other line of code.
elif a==7:
    print("Hello Word 2")
# Here “Hello Word 2” print because condition is true.

So in this code, all elif statements run.

Using “else” Statement in Python:

The else statement executes a block of code if all the aforementioned conditions are False.

a=7
if a==5: #condition1
       print("Hello Word")
#execute this block if condition1 is true.

elif a==6: #condition2
    print("Hello Word")
#execute this block if condition2 is True and condition1 is False
else:
    print("Hello Word")
#execute this block if both condition1 and condition2 are False

Here are all about python conditional statements. in this tutorial, we learn how to use conditional statements in python. How to execute conditional statements.

So, in the next tutorial, we are going to learn about Logical Operators. So, make sure to subscribe to us to learn python in easy way.

Was this helpful?
YesNo

Related Articles:

Recent Articles:

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x