Python Intermediate #2 - For Loop for Multiplication Tables

This post will demonstrate the use of a For loop in Python.  The example will print user selected multiplication tables.  The tables will run from 0 to 9.  Our first step is to make a list of values from 0 to 9.

values_in_table = [0,1,2,3,4,5,6,7,8,9]

The next step involves asking the user for input for what multiplication table they would like to have printed.

mult_table = int(input("Enter multiplication table that you would like to see: "))

We want to use a For loop in order to "loop" through each of the values in the list.  Without the For loop, we would have to use 10 print statements:

print(mult_table, "*", values_in_table[0], "=", mult_table*values_in_table[0])
print(mult_table, "*", values_in_table[1], "=", mult_table*values_in_table[1])
print(mult_table, "*", values_in_table[2], "=", mult_table*values_in_table[2])
print(mult_table, "*", values_in_table[3], "=", mult_table*values_in_table[3])
print(mult_table, "*", values_in_table[4], "=", mult_table*values_in_table[4])
print(mult_table, "*", values_in_table[5], "=", mult_table*values_in_table[5])
print(mult_table, "*", values_in_table[6], "=", mult_table*values_in_table[6])
print(mult_table, "*", values_in_table[7], "=", mult_table*values_in_table[7])
print(mult_table, "*", values_in_table[8], "=", mult_table*values_in_table[8])
print(mult_table, "*", values_in_table[9], "=", mult_table*values_in_table[9])

To save us some coding effort, the following For loop can be used to replace the 10 print statements:

for a in values_in_table:
    print(mult_table, "*", a, "=", a*mult_table)

On each iteration of the For loop the value of "a" is assigned the next value in the list, "values_in_table".

Here is what the entire code looks like:

values_in_table = [0,1,2,3,4,5,6,7,8,9]

mult_table = int(input("Enter multiplication table that you would like to see: "))

for a in values_in_table:
    print(mult_table, "*", a, "=", a*mult_table)

Below is a screenshot of the output from this code:



Comments