Python Use a Loop to Output the nth Row of the Multiplication Table
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
)
:
(
f
"{n} * {i} = {n * i}"
)
Example: Output the 3rd row
print_multiplication_table_row
(
3
)
Code analysis:
def print_multiplication_table_row(n):defined a functionprint_multiplication_table_rowthat accepts a parameternrepresenting the row number of the table.for i in range(1, 10):UseforLoop through the numbers 1 to 9,iis the loop variable.print(f"{n} * {i} = {n * i}")Use an f-string to format and output the nth row of the multiplication table,n * icomputing the multiplication result.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
Python3 Examples