Programmer Coding

Conditional statements (if, elif, else)

Conditional statements (if, elif, else)?

if…elif…else are conditional statements that provide you with the choice making that is required while you want to execute code based totally on a particular circumstance.

The if…elif…else statement utilized in Python facilitates automate that choice making method.

If Statements

The if statements is taken into consideration the most effective of the 3 and makes a choice based totally on whether the condition is true or no longer. If the condition is genuine, it prints out the indented expression. If the condition is false, it skips printing the indented expression.

Example

if 10 > 5:

    print("10 greater than 5")

print("Program ended")

Output

10 greater than 5Program ended

If..else Statements

The if-else circumstance provides an extra step inside the choice-making manner in comparison to the simple if assertion. the start of an if-else statement operates much like a easy if assertion; but, if the situation is fake, in preference to printing not anything, the indented expression below else might be printed.

Example

# if..else statement

x = 3
if x == 4:
    print("Yes")
else:
    print("No")

Output

No

if-elif statements

The if-elif statement is shortcut of if..else chain. While using if-elif statement at the end else block is added which is performed if none of the above if-elif statement is true.

Example

grade = 75
if grade >= 90:
    print("Grade: A")
elif grade >= 80:
    print("Grade: B")
elif grade >= 70:
    print("Grade: C")
else:
    print("Grade: D")

Output:

Grade: C

Nested if

if assertion can also be checked internal different if announcement. This conditional statement is known as a nested if assertion. because of this internal if condition may be checked simplest if outer if situation is actual and through this, we will see a couple of conditions to be happy.

Example

Nested if statement example

num = 10
if num > 5:
    print("Bigger than 5")
if num <= 15:
    print("Between 5 and 15")

Output

Bigger than 5 Between 5 and 15

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top