#!/usr/bin/env python # Several wrong versions of introductory python code, with explanations # Version 1: for n in range(5): sum += n print("Total sum = " + sum) # BUT: there is no += in Python # Version 2: for n in range(5): sum = sum + n print("Total sum = " + sum) # BUT: sum is a builtin fct, so can't be used as variable # Version 3: global s for n in range(5): s = s + n print("Total sum = " + s) # BUT: you don't need to declare a variable, to make it known, just assign to it # Version 4: s = 0 for n in range(5): s = s + n print("Total sum = " + s) # BUT: printing fails because you can't append ('+') a string with an int # Version 5 # compute the sum over the first 5 integer numbers s = 0 for n in range(5): s = s + n print("Total sum = ") print(s) # BUT: this is the wrong result!! # Version 6 # compute the sum over the first 5 integer numbers s = 0 for n in range(5): s = s + n print("Total sum = " + str(s)) print(s) # NB: str(s) turns the int value into a string # Version 7 (final) s = 0 for n in range(6): s = s + n print("Total sum = ") print(s) # finally, this is the correct code