100 days of code: Day 7 - for loops

Last modified on 2020-06-15

Source: 100-days-of-code.

Using a loop to execute a block of code multiple times and the range() function to specify the number of iterations. I created a program - for_numbers.py - that uses a for loop to display all numbers between START and STOP and the sum total of all the numbers in the range.

In addition to looping and range() I use:

import time

# Start and stop numbers for range().
STOP = 1_000_001

print("Use 2 different methods that employ a for loop to display all numbers "
        + f"between {START} and "
        + f"{STOP - 1:_}:")     # display large numbers with `_` separator

print("\nMethod #1: Pre-seed a list of numbers using list() and range().")
input("Press ENTER to continue ...")
start_time = time.time()    # let's time how long each method takes to run
numbers = list(range(START, STOP))
for number in numbers:
total_time = time.time() - start_time       # total elapsed time
print(f"Method #1 took {total_time:.2f} "   # display time to 2 decimal places
        + "seconds to run.")

print("\nMethod #2: Create an empty list and append each number generated "
        + "by range() in the loop.")
input("Press ENTER to continue ...")
start_time = time.time()
numbers = []    # clear the list generated by Method #1
for number in range(START, STOP):
total_time = time.time() - start_time
print(f"Method #2 took {total_time:.2f} " + "seconds to run.")

print(f"\nSum total of all numbers between {START} and "
        + f"{numbers[-1]:_} is " + f"{sum(numbers):_}" + ".")

After running the program several times, I find it interesting to note that Method #2 (start with an empty list and append) consistently takes (roughly 8%) longer than Method #1 (generate the list in the beginning).

Happy hacking!