From 3f5de6b8f7b79ad45893662ca29b36a2c52624a4 Mon Sep 17 00:00:00 2001 From: Giles Greenway Date: Thu, 4 May 2023 11:41:16 +0100 Subject: [PATCH] Replace the basic summation example with a simple simulation of coin-tosses: 1) It's *entirely* valid for an accumulator to not depend on the loop varaible, c.f. Monte-Carlo integration. 2) We shouldn't solve the problem of `range` starting from zero with spurious additions in a loop, just use `range` properly. 3) A trvial summation over the loop variable should be done with the built-in `sum` function. 4) The later excercise with a cumulative sum is a far better example. Delete the string revering excercise. 1) Strings, and other sequences are more idiomatically reversed with slice operators. 2) The other exercises with string accumulators are much better. On branch loops_grg modified: episodes/12-for-loops.md --- episodes/12-for-loops.md | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/episodes/12-for-loops.md b/episodes/12-for-loops.md index c73f9ced2..5e0708903 100644 --- a/episodes/12-for-loops.md +++ b/episodes/12-for-loops.md @@ -147,25 +147,27 @@ a range is not a list: range(0, 3) - A common pattern in programs is to: 1. Initialize an *accumulator* variable to zero, the empty string, or the empty list. - 2. Update the variable with values from a collection. + 2. Update the variable incrementally, this might use the values of the loop variable, but doesn't have to. ```python -# Sum the first 10 integers. -total = 0 -for number in range(10): - total = total + (number + 1) -print(total) +# Simulating 100 coin flips. +import random + +total_flips = 100 +total_heads = 0 +for flip in range(total_flips): + if random.random() < 0.5: + total_heads += 1 + +print(f'Of {total_flips} coin flips, {total_heads} were heads.') ``` ```output -55 +Of 100 coin flips, 48 were heads. ``` -- Read `total = total + (number + 1)` as: - - Add 1 to the current value of the loop variable `number`. - - Add that to the current value of the accumulator variable `total`. - - Assign that to `total`, replacing the current value. -- We have to add `number + 1` because `range` produces 0..9, not 1..10. +- Read `total_heads += 1` as: + - Add 1 to the the accumulator variable `total_heads`, replacing the current value. ::::::::::::::::::::::::::::::::::::::: challenge