+91 81900 98289

This Nested If lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

An if inside another if runs only when both tests are true. Each level is indented one step further.

When the inner block has no else of its own, one if with and is usually easier to read.

Example 1: Start here

The inner test is not even considered when the outer test fails.

score = 82 # a whole number city = "Chennai" # text if score >= 70: # run the indented lines only when this is true if city == "Chennai": # run the indented lines only when this is true print("shortlisted")

Example 2: A test inside a test

The inner if runs only when the outer if is true.

score = 82 # a whole number submitted = True # True or False, not text if submitted: # run the indented lines only when this is true if score >= 80: # run the indented lines only when this is true print("Accepted")

Example 3: Flatten it with and

and is easier to read when both tests are simple.

score = 82 # a whole number submitted = True # True or False, not text if submitted and score >= 80: # run the indented lines only when this is true print("Accepted")

Example 4: An else on the inner test

The else belongs to the inner if because it is indented at that level.

score = 70 # a whole number submitted = True # True or False, not text if submitted: # run the indented lines only when this is true if score >= 80: # run the indented lines only when this is true print("Accepted") else: # runs when the test above was false print("Revise")
The inner test is not even considered when the outer test fails.
Call Now 81900 98289