Creating a multiplication table is a fantastic way to practice loops and basic arithmetic operations in Python. It’s a great exercise for beginners and a handy utility for everyone.
Code to create Multiplication Table
We’ll write a Python script that takes an input number, ( n ), and prints out its multiplication table up to ( n \times 10 ).
Let’s create a new Python file for this task and name it as multiplication_table.py.
# multiplication_table.py def print_multiplication_table(n): # Print the multiplication table for n for i in range(1, 11): result = n * i print(f"{n} x {i} = {result}") # Main function if __name__ == "__main__": # Input from user n = int(input("Enter a number: ")) # Print the multiplication table print(f"Multiplication table for {n}:") print_multiplication_table(n)
Let’s break down this code. We define a function called print_multiplication_table that takes a single argument, ( n ). Inside this function, we use a for loop to iterate from 1 to 10. For each iteration, we calculate the product of ( n ) and the current loop variable ( i ), and then we print the result in a formatted string.
In the __main__ section of our script, we prompt the user to enter a number, convert it to an integer, and then call our print_multiplication_table function with this number.
Output
$ python multiplication_table.py Enter a number: 5 Multiplication table for 5: 5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50
As you can see, when we input the number 5, the script outputs the multiplication table for 5 from 1 to 10.