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.
- IF ELSE statement
- ELIF Statement
- 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.
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.
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
Here, you can set the destination to save your file into the local machine.
Open the Python file that you have saved recently.
Enter the following conditions on the file.
CODE WITH ERROR
- n=int (input("Enter the number: "))
- if n<100:
- print(n "is less than 100")
Then go to the Run - select “Run Module” or press “F5” key.
Error Screen
If the syntax is wrong, the system will show the notification message like the below screen.
Finding - Missed to add comma next to “n” variable.
VALID CODE
- n=int (input("Enter the number: "))
- if n<100:
- print (n, "is less than 100")
ELSE Statement
Here, included the else statement inside the file.
CODE
- n = int(input("Enter the number: "))
- if n < 100: print(n "is less than 100")
- else :print(n, "is greater than 100")
- print("Thanks!")
Output
When you click the F5 key in the Python file, you will see this in Python Shell.
In the above screen, entered the number 50. So, the result displays “
50 is less than 100”
In the above screen, I entered the number 150. So, the result displays “150 is greater than 100”.
Thanks.