Understanding Python if-else Statement 2021

Contents show

Python if-else Statement

Python if-else Statement
Python if-else Statement

if else in python

THE IF CONDITIONALS

Python if-else Statement
The if conditionals of Python come in multiple forms : plain if conditional, if-else conditional and if-elif conditionals.

1. Plain if Conditional Statement

An if statement tests a particular condition; if the condition evaluates to true, a course-of-action is followed i.e., a statement or set-of-statements is executed. If the condition is false, it does nothing :

Plain if Conditional Statement
Plain if Conditional Statement


The syntax (general form) of the if statement is as shown below :

         if <conditional expression> :
               statement
               [statements]

For example, consider the following code fragments using if conditionals :

if grade == 'A' :
       print("Congratulations! you did well")
:
if a > b :
       print("A has more than B has")
       print("Their difference is", (a-b))

Q1. Write a program in which if the percentage of a student is greater than or equal to 65 then it give output Passing grade and display the percentage of student in grade variable.

grade = int(input("Enter the percentage of the student :")
if grade >= 65:
    print("Passing grade")
Sample run of above program :


Enter the percentage of the student : 75
Passing grade

2. The if-else Conditional Statement

This form of if statements tests a condition and if the condition evaluates to true, it carries out statements indented below if and in case condition evaluates to false, it carries out statements indented below else.

if-else Conditional Statement
if-else Conditional Statement

If you want to read :

Conditional And Iterative Statements

Related Question Answer to Conditional And Iterative Statements


The syntax (general form) of the if-else statement is as shown below :

if <conditional expression> :
      statement              
      [statements]
else :
      statement
      [statements]

For example, consider the following code fragments using if-else conditionals :

if a >=  0 :
       print(a, "is zero or a positive number")
else :
       print(a, "is a negative number")


Q1. Write a program in which if the percentage of a student is greater than or equal to 65 then it give output Passing grade and if percentage is below than 65 it return failing grade display the percentage of student in grade variable.

grade = int(input("Enter the percentage of the student :")
if grade >= 65:
    print("Passing grade")
else :
    print("Failing grade")

Sample run of above program :

Enter the percentage of the student : 60
Failing grade

3. The if-elif Conditional Statement

Sometimes, you want to check a condition when control reaches else, i.e., condition test in the form of else if. To serve such conditions, Python provides if-elif and if-elif-else statements.


The general form of these statement is :

if <conditional expression> :
     statement
     [statements]
elif <conditional expression> :
      statement
      [statements]

and

if <conditional expression> :
     statement
     [statements]
elif <conditional expression> :
      statement
      [statements]
else :
     statement
     [statements]

Consider following two example code fragments :

if runs >= 100 :
      print("Batsman scored a century")
elif run >= 50 :
      print("Batsman has neither scored a century nor fifty")
:
if num < 0 :
     print(num, "is a negative number .")
elif num == 0 :
     print(num, "is equal to zero .")
else :
     print(num, "is a positive number .")

Program 1. Write a program that inputs an integer in range 0-999 and then prints if the integer entered is a 1/2/3 digit number.

num = int(input("Enter a number (0 . . 999) :))
if num < 0:
           print("Invalid entry. valid range is 0 to 999.")
elif num < 10 :
          print("Single digit number is entered")
elif num < 100:
          print("Two digit number is entered")
elif num <= 999:
         print("Three digit number is entered")
else :
        print("Invalid entry. valid range is 0 to 999.")

Sample runs of this program are given below :
Enter a number (0 . . 999) : -3

Invalid entry. valid range is 0 to 999.

===========================

Enter a number (0 . . 999) : 4

Single digit number is entered

===========================

Enter a number (0 . . 999) : 100

Three digit number is entered

===========================

Enter a number (0 . . 999) : 10

Two digit number is entered

===========================

Enter a number (0 . . 999) : 3000
Invalid entry. valid range is 0 to 999.

Q 1. Write a program to check if number is positive or negative or zero and display in an appropriate message.

num = (int(input("Enter a number :")
if num > 0:
    print("Positive number")
elif num == 0:
    print("Zero")
else:
    print("Negative number")

Sample run of above program is :

Enter a number : 0

Zero

=============================

Enter a number : 5

Positive number

=============================

Enter a number : -25

Negative number

=============================

4. Nested if Statements

Sometimes you may need to test additional conditions. For such situations, Python also supports nested-if form of if.

A nested if is an if that has another if in its if’s body or in elif’s body or in its else’s body.

Nested if Statements
Nested if Statements


Consider the following example code using nested-if statements :

x = int(input("Enter first number :"))
y = int(input("Enter second number :"))
z = int(input("Enter third number :"))
min = mid = max = None
if x < y and x < z :
    if y < z :
         min, mid, max = x, y, z
    else :
          min, mid, max = x, z, y
elif y < x and y < z :
        if x < z :
         min, mid, max = y, x, z
    else :
          min, mid, max = y, z, x
else x < y :
        if x < y :
         min, mid, max = z, x, y
    else :
          min, mid, max = z, y, x
print("Number in ascending order :", min, mid, max)

Q 1. Write a program to input a number check if the number is positive or negative or zero display in appropriate message.


num = float(input("Enter a number: "))
if num >= 0:
    if num == 0:
        print("Zero")
    else:
        print("Positive number")
else:
    print("Negative number")

Sample run of above program is :

Enter a number : 0

Zero

=============================

Enter a number : 6

Positive number

=============================

Enter a number : -2.5

Negative number

=============================

5. Storing Conditions

Sometimes the conditions being used in code are complex and repetitive. In such cases to make your program more readable, you can use named conditions i.e., you can store conditions in a name and then use that named conditional in the if statements.


Consider the following example code :

b, c = 2, 3
#store condition in a name called all.
all = a ==1 and b ==2 and c == 3
#Test variable.
if all :
     print("condition fulfilled")
#Use it again.
if all :
     print("condition fulfilled again.")

Tip :-

  • Using Named or stored conditionals reduces repetition.
  • It may also improve processing speed : fewer comparisons are done.


Using nested if statements, we can rewrite the previous program as follows :

Program 2. Write a program that inputs an integer in range 0-999 and then prints if the integer entered is a 1/2/3 digit number.

num = int(input("Enter a number (0 . . 999) :))
if num < 0 or num > 999 :
      print("Invalid entry. valid range is 0 to 999.")
else :
      if num < 10 :
              print("single digit number is entered")
      else :
            if num < 100 :
                   print("Two digit number is entered")
             else :
                   print("Three digit number is entered")

The sample run of this program is just the same as previous program.

Python if-else Statement

FAQ :-

Q 1. How do you write an IF ELSE statement in Python?

ans. The if..else statement evaluates test expression and will execute the body of if only when the test condition is True . If the condition is False , the body of else is executed. Indentation is used to separate the blocks.

Q 2. What is if else statement in Python?

ans. The ifelse statement is used to execute both the true part and the false part of a given conditionIf the condition is true, the if block code is executed and if the condition is false, the else block code is executed.

Q 2. Can you have two if statements in python?

ans. The elif. Python supports multiple independent conditions in the same if block. Say you want to test for one condition first, but if that one isn’t true, there’s another one that you want to test. Then, if neither is true, you want the program to do something else.

Q 3. How do you write multiple if else statements in python?

ans. A nested if is an if statement that is the target of another if statement

Nested if statements means an if statement inside another if statement.

Yes, Python allows us to nest if statements within if statements. i.e., we can place an if statement inside another if statement.

Q 4. When python if statement multiple conditions are used ?

ans. If-else conditional statement is used in Python when a situation leads to two conditions and one of them should hold true.

Q 5. Can you have two if statements in python?

ans. Elif. Python supports multiple independent conditions in the same if block. Say you want to test for one condition first, but if that one isn’t true, there’s another one that you want to test.

Q 6. How do you write if else in Python 3?

ans. An else statement can be combined with an if statement. An else statement contains a block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value. The else statement is an optional statement and there could be at the most only one else statement following if.

Read More :

Python Loops – For, While, Nested Loops With Examples

if else in python read more