Conditional Statements in Python

In programming languages, most of the time we have to control the flow of execution of your program, you want to execute some set of statements only if the given condition is satisfied, and a different set of statements when it’s not satisfied. Which we also call it as control statements or decision making statements.Conditional statements are also known as decision-making statements. We use these statements when we want to execute a block of code when the given condition is true or false.

In Python we can achieve decision making by using the below statements:
  • If statements
  • If-else statements
  • Elif statements
  • Nested if and if-else statements
  • Elif ladder
In this tutorial, we will discuss all the statements in detail with some real-time examples.

If statements
The below code will print 25 is less than 50 because conditions returns the boolean value true.
if 25 < 50:
print("25 is less than 50")
The below code will not print 25 is greater than 50 because conditions returns the boolean value false.
if 25 > 50:
print("25 is greater than 50")
Similarly the below code will not print 25 is equal to 50 because conditions returns the boolean value false.
if 25 > 50:
print("25 is greater than 50")
num=5
if(num < 10):
print("Number is small")
Number is small
if(35 + 165 == 100+ 100):
print("35+165 == 100+100 is correct")
if 100>50>10:
print("100>50>10")

if 100<50<10
   print("Nothing will be printed")

If-else statements
num=5
if(num < 10):
print("Number is smaller")
else:
print("Invalid Number ")
print("finished")

Elif statements
num=3
if(num == 0):
print("Number is Zero")
elif (num > 5):
print("Number is greater than 5 ")
else:
print("Number is less than 5 ")

 
Nested if and if-else statements
num = 5
if(num >0):
print("number is positive")
if(num<10):
print("number is less than 10")
num = 7
if (num != 0):
if (num > 0):
print("Number is greater than Zero")


if ('python' in ['Java', 'python','C#']):
                         print("Python is present in the list")
                         if ('C#' in ['Java','python','C#']):
                                  print("Java is present in the list")
                                  if ('C#' in ['Java','python','C#']):
                                           print("C# is present in the list")


No comments:

Post a Comment