DEV Community

Cover image for Python Beginners Guide - Conditional Statements
Hillary Nyakundi
Hillary Nyakundi

Posted on

Python Beginners Guide - Conditional Statements

Just like any other programming language python also supports use of conditional statements also known as decision making statements. They are used to determine if given condition is true or false.

But first before we take a look at some of the most common ones, let's begin by going through some of the basic comparison operators and how they are used:

  • Equals (==)
  • Not Equal (!=)
  • Less than (<)
  • Less than or equal to (<=)
  • Greater than (>)
  • Greater than or equal to (>=)

All of these comparison operators can be leveraged in the conditional statements mostly in if statements and loops.

Types of Condition Statements

1. If Statement

It is the most commonly used, It's main purpose is to check if a statement is true or false.
Syntax

if expression:
    statement
Enter fullscreen mode Exit fullscreen mode

example

x=10
y=15
if y>x:
   print("Y is greater")
Enter fullscreen mode Exit fullscreen mode

2. If else Statement

It is a conditional statement that compares between two conditions. The else keyword helps you add some additional statements to your condition clause.
Syntax

if (condition):
   #statement
else:
   #statement
Enter fullscreen mode Exit fullscreen mode

example

x=10
y=15
if y==x:
   print("Values are equal")
else:
  print("Values are not equal")
Enter fullscreen mode Exit fullscreen mode

3. Elif Statement

Used to compare one or more statements, it is a shortcut of the else if condition.
Syntax

if(condition):  
  statement    
elif(condition):  
  statement   
else:  
  else statement    
Enter fullscreen mode Exit fullscreen mode

example

x = 15  
y = 15  
if a < b:  
  print("a is greater")  
elif a == b:  
  print("a and b are equal")  
else:  
  print("b is greater")  
Enter fullscreen mode Exit fullscreen mode

4. If-Not Statement

It let's you check for the opposite condition to verify whether thee value is Not True. The statements passed will execute if the value passed is False.
Syntax

if Not value:
   statement
Enter fullscreen mode Exit fullscreen mode

example

list1 = [2,4,6,8]
y = 10
if y not in list1:
   print("Y is missing in the list")
Enter fullscreen mode Exit fullscreen mode

5. Nested Statements

This is when an if statement is used inside another if statement.
Syntax

if condition1:
   if condition2:
     statement
Enter fullscreen mode Exit fullscreen mode

example

x = 15
if x >= 0:
    print("Zero")
    if x == 0:
        print("Zero")
Enter fullscreen mode Exit fullscreen mode

In this article we have gone through some of the common conditional statements we have in python, in the article I share more on loops and how they are used in python.

See you in the next one!

Buy Me A Coffee

Connect With me at Twitter | GitHub | YouTube | LinkedIn |

Oldest comments (0)