+91 81900 98289

Python If...Else

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

if runs a block when the test is true. elif tries another test. else runs when every test above it failed.

The blocks are indented. A colon is required at the end of each test line.

Example 1: Start here

One if with several elif lines is clearer than nested if statements.

score = 82 # a whole number if score >= 90: # run the indented lines only when this is true band = "A" # text elif score >= 75: # checked only when the tests above were false band = "B" # text else: # runs when the test above was false band = "C" # text print(band)

Example 2: Two branches

Exactly one branch runs.

score = 82 # a whole number if score >= 80: # run the indented lines only when this is true print("Pass") else: # runs when the test above was false print("Try again")

Example 3: Three branches

elif is checked only when the earlier tests were false.

score = 74 # a whole number if score >= 80: # run the indented lines only when this is true print("Pass") elif score >= 60: # checked only when the tests above were false print("Revise") else: # runs when the test above was false print("Restart")

Example 4: A test with and

Both parts must be true.

score = 82 # a whole number submitted = True # True or False, not text if score >= 80 and submitted: # run the indented lines only when this is true print("Accepted")
One if with several elif lines is clearer than nested if statements.
Call Now 81900 98289