APDR

Branching and Iteration Lab

Algorithms, Programming, and Data Representation · Module 92313 · Chapter 6

Predict what Python does before it runs. Then watch it work one step at a time: an expression reduced operation by operation, a slice picking its characters, and a program’s running line, variables and output.

How the lab works

  1. Predict. Commit to an answer before the program runs.
  2. Rate your confidence. A sure but wrong answer marks an idea to revisit first.
  3. Reveal. Watch Python carry out each step, and compare the result with your prediction.
  4. Explore. Press Explore freely at any time, or finish the four challenges, to type your own expressions, strings and loops.

6.2 Operators: value, type and order

Python works out an expression one operation at a time, in precedence order, and each result has a type. Watch where a float appears and which operator goes first.

In the sandbox, type your own expression below.

Or try your own

Whole numbers and decimals with + - * / // % ** and brackets. A power with a decimal or negative exponent may differ from Python in its last digit.

6.4 Strings: index and slice

Every character has an index from the left, starting at 0, and one from the right, starting at −1. A slice starts at its start, steps by its step and stops before its stop; watch it pick the characters in order.

In the sandbox, slice your own string below.

Or try your own

Leave a field empty to leave that part out, as in s[::-1].

6.7 Branching: which lines run

The lecture’s program compares two numbers with an if, a nested if, an elif and an else. Predict which lines run, then watch the highlight move through the code.

In the sandbox, choose x and y below.

Or try your own

Whole numbers; the program turns them into floats, as float(input(…)) would.

6.8 Loops: count the rounds

A for loop takes one value of range per round; a while loop tests its condition before every round. Count the rounds and the final value, then watch the loop variable change.

In the sandbox, set up your own loop below.

Or try your own

start, stop and step set the for loop’s range; n is the starting value of the while loop.

6.9 break and continue: leave or skip

break leaves the innermost loop at once; continue skips the rest of one round. Watch which lines are skipped and where the loop goes next.

In the sandbox, set up your own loop below.

Or try your own

The loop is the lecture’s: mysum += i, then the test, then mysum += 1.

Your results

Personal study lab based on the Chapter 6 guide and the supplied “06_branching_and_iterations.pdf”, written in my own words; every result is computed with Python 3’s rules. Not an official FAU publication; check course details against the current notes. Made by Thanate Amornjiraporn (Focus).