Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Use a Loop to Output the nth Row of the Multiplication Table

Python Use a Loop to Output the nth Row of the Multiplication Table

Document Object Reference Manual Python3 Examples

We can use Python to write a simple loop to output the nth row of the multiplication table. Suppose n is an integer representing the row number of the table (1 to 9); we can generate that row's multiplication results via a loop.

Example

def

print_multiplication_table_row

(

n

)

:

   

for

i

in

range

(

1

,

10

)

:

       

print

(

f

"{n} * {i} = {n * i}"

)

Example: Output the 3rd row

print_multiplication_table_row

(

3

)

Code analysis:

  1. def print_multiplication_table_row(n): defined a function print_multiplication_table_rowthat accepts a parameter nrepresenting the row number of the table.
  2. for i in range(1, 10): Use for Loop through the numbers 1 to 9,i is the loop variable.
  3. print(f"{n} * {i} = {n * i}") Use an f-string to format and output the nth row of the multiplication table,n * i computing the multiplication result.
  4. print_multiplication_table_row(3) Call the function and pass the argument 3, meaning output the multiplication table of the 3rd row.

Output result:

3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27

Document Object Reference Manual Python3 Examples