1 of 16

Branching and Choice

2 of 16

Objectives

  • Why use branching?
  • Branching structures in Python
  • Practice

2

3 of 16

Why Use Branching?

The Challenges of Choice

4 of 16

Branching Allows Choice

  • Most programs require choices
  • Different behaviour leads to different paths through the program
  • Primary mechanism is the if keyword
  • Combines with conditions that evaluate to True or False

4

5 of 16

Simplest Branching

5

6 of 16

Branching Structures in Python

How Do We Branch?

7 of 16

Python Branches

  • Simplest approach using if keyword

  • Can be extended with else keyword

7

8 of 16

More Complicated Branches

  • Can also use elif keyword
  • Can have as many elif’s as necessary

8

9 of 16

Practice

Putting it all together!

10 of 16

Example 1: Even and Odd

  • How do we know if an integer is even?

10

11 of 16

Example 1: Even and Odd

  • How do we know if an integer is even?
  • If it is divisible by 2, then it is even
    • Otherwise, it is odd
  • This suggests branching!

  • Use the mod operator (%)
  • 23 % 5 = 3 since 23 = 4x5 + 3
  • Consider the same thing with % 2

  • Complete L1.5 Even and Odd

11

12 of 16

Example 1: Even and Odd

12

13 of 16

Example 2: Classifying Numbers

  • Any integer can be positive, negative, or zero
  • Make a program that gets an integer from the user and then determines if the number is positive, negative, or zero

13

14 of 16

Example 2: Classifying Numbers

14

15 of 16

Additional Practice

  • L1.4 Branching 1
  • L1.5 Even and Odd
  • L1.6 Tall Person

Teacher Solution L1.04

15

16 of 16

CREDITS

Special thanks to all the people who made and released these awesome resources for free:

  • Presentation template by SlidesCarnival

16