Hacking Secret Ciphers with Python

(Ann) #1
Chapter 6 – The Caesar Cipher 79

'rosebud' is True, then the execution jumps inside of the following block to print out
'Access denied.'. If the condition is False, then this block of code is skipped.


The else Statement


Often we want to test a condition and execute one block of code if it is True and another block
of code if it is False. The previous password.py example is like this, but it used two if
statements.


An else statement can be used after an if statement’s block, and its block of code will be
executed if the if statement’s condition is False. You can read the code as “if this condition is
true, execute this block, or else execute this block.


Type in the following program and save it as password2.py. Notice that it does the same thing as
the previous password.py program, except it uses an if and else statement instead of two if
statements:


Source code for password2.py



  1. print('What is the password?')

  2. password = input()

  3. if password == 'rosebud':

  4. print('Access granted.')

  5. else:

  6. print('Access denied.')

  7. print('Done.')


The elif Statement


There is also an “else if” statement called the elif statement. Like an if statement, it has a
condition. Like an else statement, it follows an if (or another elif) statement and executes if
the previous if (or elif) statement’s condition was False. You can read if, elif and else
statements as, “If this condition is true, run this block. Or else, check if this next condition is true.
Or else, just run this last block.” Type in this example program into the file editor and save it as
elifeggs.py:


Source code for elifeggs.py



  1. numberOfEggs = 12

  2. if numberOfEggs < 4:

  3. print('That is not that many eggs.')

  4. elif numberOfEggs < 20:

  5. print('You have quite a few eggs.')

  6. elif numberOfEggs == 144:

Free download pdf