If Else Statements In Python

Introduction

 
In the session, we are going to discuss the if else statement and nested if statement for Python. If you want to learn the basics and environment setup for Python use the following link,
Now, we are going to discuss the following statements.
  1. IF ELSE statement
  2. ELIF Statement
  3. Nested IF Statement
IF ELSE Statement
 
The statement is a common process for every machine language. The machine or application should have an option/condition to enable/disable the records, control, notifications etc.
 
Python
 
Let’s discuss the step by step process to implement the IF else statement.
 
Go to Start - Python 3.6 - IDLE (Python 3.6 32bit) - Click OK.
 
Python
 
Create a New File
 
To Create a new Python file,
 
Go to New - New - Save the file in the local machine - Open the file through Python Shell
 
Python
 
Here, you can set the destination to save your file into the local machine.
 
Python
 
Open the Python file that you have saved recently.
 
Enter the following conditions on the file.
 
CODE WITH ERROR
  1. n=int (input("Enter the number: "))  
  2. if n<100:  
  3.     print(n "is less than 100")  
Python
 
Then go to the Run - select “Run Module” or press “F5” key.
 
Python
 
Error Screen
 
If the syntax is wrong, the system will show the notification message like the below screen.
 
Python
 
Finding - Missed to add comma next to “n” variable.
 
VALID CODE
  1. n=int (input("Enter the number: "))  
  2. if n<100:  
  3.     print (n, "is less than 100")  
ELSE Statement
 
Here, included the else statement inside the file.
 
CODE
  1. n = int(input("Enter the number: "))  
  2. if n < 100print(n "is less than 100")  
  3. else :print(n, "is greater than 100")  
  4. print("Thanks!")  
Python
 
Output
 
When you click the F5 key in the Python file, you will see this in Python Shell.
 
Python
 
In the above screen, entered the number 50. So, the result displays “50 is less than 100
 
Python
 
In the above screen, I entered the number 150. So, the result displays “150 is greater than 100”.
 
Thanks.


Recommended Free Ebook
Similar Articles