Skip to content

Examples / exercises encourage anti-patterns in 12-for-loops.md #636

@augeas

Description

@augeas

There are two examples/exercises whose solutions encourage anti-patterns, miss basic Python features introduced previously, and use the language non-idiomatically. We shouldn't add the confusing cognitive load of "Here's an example, but don't do it this way.".

  1. Intro to the accumulator pattern:

To be worthwhile, the accumulated values should be somewhat non-trivial, students should not leave the session thinking that a for loop is required to merely sum over an iterable:

sum_to_10 = sum(range(1, 11))

This is a missed opportunity to introduce "sum" in the previous built-in functions section.
Solving the problem of range(10) going from 0-9 would be better solved by explaining that one wanted range(1,11) rather than a superfluous extra addition.
If a cheap-and-cheerful Monte-Carlo simulation to estimate Pi is too much, maybe just count the number of heads in some coin-tosses?

  1. Reversing a String:

This is not a good use for a for loop. Slice operators have already been introduced previously, and students should leave thinking that this is how you reverse a string.
reversed_string = 'This is not a palindrome![::-1]

Easy. Yes, this demonstrates that iteratively appending items from a collection will cause them to be in reverse order, but why would anyone do that?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions