Python uses a loop to output the nth row of the multiplication table

Document 对象参考手册Python3 Example

We can use Python to write a simple loop to output the nth row of the multiplication table. Assuming n is an integer representing the row number of the multiplication table (1 to 9), we can use a loop to generate the multiplication results for that row.

Example

def print_multiplication_table_row(n):
    for i in range(1, 10):
        print(f"{n} * {i} = {n * i}")

# Example: output row 3
print_multiplication_table_row(3)

Code analysis:

  1. def print_multiplication_table_row(n):Defines a functionprint_multiplication_table_row, which accepts a parametern, representing the row number of the multiplication table.
  2. for i in range(1, 10):Usefora loop to iterate over numbers 1 to 9,iwhich is the loop variable.
  3. print(f"{n} * {i} = {n * i}")Use f-string formatting to output the nth row of the multiplication table,n * iand compute the multiplication result.
  4. print_multiplication_table_row(3)Call the function and pass in the argument 3, meaning output the multiplication table for row 3.

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 对象参考手册Python3 Example

Other extensions