Python: else and elif statements

Go to Chapter 11 of A Smarter Way.

You could use a series of if statements for multiple tests:

if text == 'this text':
    print("this text")
if text == 'that text':
    print("that text")
if text == 'some other text':
    print("some other text")

If you use a series of if statements, all of them are evaluated. This is not true if you use elif:

if text == 'this text':
    print(text)
elif text == 'that text':
    print("text")
elif text == 'some other text':
    print("text")

If you use if … elif statements, the code will run only until a match is found. Though there is no “break” statement in each if or elif block, Python will in fact break out of the if series once a match is found.

You still need a “catch-all” statement to catch all other possibilities:

if text == 'this text':
    print(text)
elif text == 'that text':
    print("text")
elif text == 'some other text':
    print("text")
else:
    print("No match")

Else does the job: in this case if there’s no match, “No match” will be printed.

Exercises

See http://www.asmarterwaytolearn.com/python/11.html

See http://introtopython.org/if_statements.html

  1. Return to examples.py.
  2. Do a test on the author’s name. If the name variable holds the proper name, print “Authorized Edition”.
  3. If the name variable doesn’t hold the proper name, print “Not an Authorized Edition!”
  4. If the name variable holds no value, print “No name”.