Branching

Note

Learning objectives: Explain equalities of numbers and strings. Create a conditional logic tree for branching. Modeling a program on the prior lesson, write a comparison involving if.

  • The if statement does your basic branching. Here is the structure.
    • Pretend <bool test> is some Boolean test like “myvariable == 1”.

digraph branching {
    if [ label="if <bool test>", shape=diamond ]
    elif1 [ label="elif <bool test>", shape=diamond ]
    elif2 [ label="elif <bool test>", shape=diamond ]
    elifn [ label="elif <bool test>", shape=diamond ]
    action0 [ label="Action_0", shape=box ]
    action1 [ label="Action_1", shape=box ]
    action2 [ label="Action_2", shape=box ]
    actionn [ label="Action_n", shape=box ]
    actionf [ label="Action_else", shape=box ]
    if -> action0 [ label = True, color=blue ]
    elif1 -> action1 [ label = True, color=blue ]
    elif2 -> action2 [ label = True, color=blue ]
    elifn -> actionn [ label = True, color=blue ]
    else -> actionf [ label = "otherwise", color=blue ]
    if -> elif1 -> elif2 -> elifn -> else [ label = False, color=red ]
}
  • So, how do we make a Boolean test? We use equality and comparison statements.

  • The following statements evaluate as True.

Integer 1 is equal to floating point value 1.0
>>> 1 == 1.0
True
Integer 1 is greater than or equal to floating point value 1.
>>> 1 >= 1.0
True
Floating point value 2.0 is greater than or equal to integer 1.
>>> 2.0 >= 1
True
Integer 2 is greater than integer 1.
>>> 2 > 1
True
String ‘a’ is less than or equal to string ‘b’, meaning it is first in the alphabet.
>>> 'a' <= 'b'
True
String ‘A’ is less than string ‘a’ because capitals come before lower case in ASCII.
>>> 'A' < 'a'
True
String ‘squirrel’ forced to be upper case is equal to string ‘SQUIRREL’
>>> 'squirrel'.upper() == 'SQUIRREL'
  • Based on the prior lesson, write a program and…
    • ask the user his or her age.

    • Print “You are an adult!” if the user is equal to or greater than 18, but less than 25

    • Tell the user “You may feel like a grown-up” if he is 25 or older.

    • Otherwise, tell the user “You are a a real grown-up,”