Python Basics 4 - Branching Programs

Python Basics 4 - Branching Programs

Hello 👋🏼 and welcome to fourth blog of series The Pythonic Way. Now that you have learnt about basic elements of a python program, lets learn about branching programs.

Lets revisit some expressions, Python has the ability to make decisions based on tests and for that, we have to compare things.

The following are common comparison operators in Python:

i>j   - greater than 
i>=j  - greater than or equal to  
i<j   - less than 
i<=j  - less than or equal to
i==j  - equal to 
i!=j  - not equal to

All of the above comparison operators will return True if true and False if false.

The following are common logic operators on booleans in Python:

not a - will return the opposite of the true/false value that a is 
a and b - will return True only if both a and b are true 
a or b - will return True if either a or b are true

There are three logical operators: and, or, and not. The semantics (meaning) of these operators is similar to their meaning in English. For example,

  • x > 0 and x < 10 is true only if x is greater than 0 and less than 10.

  • n%2 == 0 or n%3 == 0 is true if either of the conditions is true, that is, if the number is divisible by 2 or 3.

  • Finally, the not operator negates a boolean expression, so not (x > y) is true if x > y is false; that is, if x is less than or equal to y.

Priority of Boolean operations.

The order of operations is as follows:

  1. Parentheses. Before operating on anything else, Python must evaluate all parentheticals starting at the innermost level.

  2. not statements.

  3. and statements.

  4. or statements.

Branching Programs

A branching program is a program that can run down many different ways depending on the outcome of a test. The simplest branching statement is a conditional.

A conditional statement has three parts

◦ A test (expression that evaluates to True or False)

◦ A block of code to execute if the test is True

◦ An optional block of code to execute if the test is False

In Python, you can write a conditional with the if and else operators

if <boolean expression>:
    <block of code>
else:
    <block of code>

OR

if <boolean expression>:
    block of code

Each indented set of expressions in an if/else clause denotes a block of instructions.

The simplest form is the if statement:

x=5

if x<10: # a test that will either output true or false
    # what to do if the test outputs true
    print("Smaller") 

if x>20:
    print("Bigger")

print("Finis")

Output for above code will be

Smaller
Finis

Another important part of conditional statements is indentation. Python is unusual in using indentation this way. Most other programming languages use some sort of bracketing symbols to delineate blocks of code, e.g, C encloses blocks in bracket { } An advantage of Python approach is that it ensures that the visual strucuture of a program is an accurate representation of the semantic strucuture of that program. Because indentation is semantically important, the notion of a line is important.

  • Increase indent indent after an if statement or for statement (after :)

  • Maintain indent to indicate the scope of the block (which lines are affected by the if/for)

  • Reduce indent back to the level of the if statement or for statement to indicate the end of the block

  • Blank lines are ignored - they do not affect indentation

  • Comments on a line by themselves are ignored with regard to indentation

  • Use 4 spaces to intend. Avoid using tab .

Nested Conditionals

One conditional can also be nested within another.

if x%2 == 0:

    if x%3 == 0:
        print('Divisible by 2 and 3')

    else:
        # what to do if the test outputs false
        print('Divisible by 2 and not by 3') 

else:
    print("Not Divisible by 3 and 2")

else gives the conditional a set of instructions if all other tests output false, it gives alternative execution in a conditional program. Another example of alternative execution:

if x%2 == 0 : # a test that will either output true or false

    # what to do if the test outputs true
    print('x is even')

else :
    # what to do if the test outputs false
    print('x is odd')

If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a message to that effect. If the condition is false, the second set of statement is executed.

Since the condition must either be true or false, exactly one of the alternatives will be executed. The alternatives are called branches, because they are branches in the flow of execution.

Multiway decision

Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a multi way conditional:

if x < y:
    print('x is less than y')
elif x > y:
    print('x is greater than y')
else:
    print('x and y are equal')

elif is an abbreviation of “else if.” elif gives the conditional another test to check if the first one outputs false.

There is no limit on the number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one.

Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true branch executes.

We will read all about strings in next blog, so stay tuned 😄
Liked this article. Follow me on twitter 🐦

References

(Dr. Charles R. Severance, Python for Everybody : Exploring Data Using Python 3 , Chapter 3: Conditionals)