What You Need To Know About Conditional Statements In Python ?
Sakshi

Sakshi @bellatrix

About: Loves programming! Web Dev Enthusiast. Getting my hands dirty with ANGULAR. Available for hire

Location:
India
Joined:
Sep 11, 2021

What You Need To Know About Conditional Statements In Python ?

Publish Date: Mar 29 '24
0 0

PYTHON UNLEASH'D 04

HELLO LETS SEE CONDITIONAL STATEMENT IN PYTHON

As indentation plays major role in python. Indentation is used in place of brackets.
In conditional statements, we have colon which we have to use after is and else, at the end.

  1. if statement
  2. if-else statement
  3. nested if
if (condition):
    # Executes this block if
    # condition is true
else:
    # Executes this block if
    # condition is false
Enter fullscreen mode Exit fullscreen mode
if (condition1):
   # Executes when condition1 is true
   if (condition2): 
      # Executes when condition2 is true
   # if Block is end here
# if Block is end here
Enter fullscreen mode Exit fullscreen mode

Unlike C++, we do not write else-if we write elif in python in if-else chain

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

In case of nested if the following if statement execute only if the s=above statements are true, else if comes to 'else block'.

WE HAVE SHORTHANDS ALSO FOR IF ELSE

var = 6
if(var > 5): print("greater")
Enter fullscreen mode Exit fullscreen mode
print("hello") if var > 5 else print("no")
Enter fullscreen mode Exit fullscreen mode

Ternary Operator

In C++, we have below ternary operator

(5 < 6)?b = "true": b = "false";

Here in python, we have if-else in ternary operator

  • Each operand of the Python ternary operator is an expression, not a statement, that means we can’t use assignment statements inside any of them. Otherwise, the program will throw an error.
a, b = 10, 20

print ("Both a and b are equal" if a == b else "a is greater than b"
        if a > b else "b is greater than a")
Enter fullscreen mode Exit fullscreen mode

Shows good example of how we can use ternary operator with tuple, dictionaries and lambda function

We are pretty familiar with if-else so lets move to next new type of conditional statement, not definitely the new but here we have different name and keyword for that.

Also are you aware about 'pass' and when to use this?
Lets read about pass in next blog of this series.

Thanks for reading!

Comments 0 total

    Add comment