Conditional Branching in Python

Conditions in Python are comparable to those in all C-like languages. The if keyword is used to create conditions, which are then followed by a logical statement and a colon (:). If the expression returns true, the next sentence will be carried out. If it is false, the program will move on to the next statement without skipping the previous one.

Some Branching Statement in python

  • If statement
  • Pass statement
  • If-else statement
  • AND , OR operator
  • If-elif-else statement
  • in keyboard
  • Check empty or not

If statement

Python if Statement is used for decision-making operations. It contains a body of code which runs only when the condition given in the if statement is true.

age=int(input("enter your age"))
if age>=14 :
    print("you are greater than 14 years old")
enter your age20
you are greater than 14 years old

Pass statement

Pass statements are typically used as placeholders.

Let's say we have a loop or function that isn't used right now but that we wish to in the future. They cannot have an empty body. An error would be displayed by the interpreter. Therefore, we create a body that accomplishes nothing using the pass statement.

x = 18
if x >18:
    pass

If-else statement

The true and false parts of a given condition are both executed using the if-else expression. If the condition is true, the code in the if block is performed; if it is false, the code in the else block is executed.

age=int(input("enter your age"))
if age>=14 :
    print("you are greater than 14 years old")
else:
    print("you are smaller than 14")
enter your age 12
you are smaller than 14

AND , OR operator

AND opertor returns true if both statements are true and OR operator returns true if one of the statement is true.

name = 'anisha'
age = 20
if name == "anisha" and age == 20:
    print ("She is good girl")
else:
    print ("She is not like anisha")
She is good girl

If-elif-else statement

The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE.

name = 'abc'
age = 20
if name == "abc" and age == 20:
    print ("She is good girl")
elif name == "abc" or age == 19:
    print ("She is bad girl")
else:
    print("I don't know about her")
She is good girl

in keyboard

in keyboard returns True if a sequence with the specified value is present in the object.

name = "Anisha"
if 'A' in "Anisha":
    print("true")
else:
    print("False")
true

Check empty or not

name = "anisha"
if name:
    print("not empty")
else:
    print("is empty")
not empty