Write a function to print the table of a given number. The number has to be entered by the user.
python
Function to print the table of a given number
def print_table(num): print("Table of", num, "is:") for i in range(1, 11): print(num, "x", i, "=", num * i)
Main program
n = int(input("Enter a number: ")) print_table(n)
Explanation:
The program defines a function named print_table that takes one parameter num. Inside the function, a for loop is used with range(1, 11) to iterate from 1 to 10. For each iteration, it prints the multiplication in the format "num x i = result".
In the main program, the user enters a number using the input() function. The input is converted to an integer using int() and stored in variable n. The function print_table(n) is then called to display the multiplication table.
Sample Output:
Enter a number: 5 Table of 5 is: 5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 ... 5 x 10 = 50
Explanation
The textbook context shows examples of using for loops with range() for iteration (Program 6-5 and Program 6-19). The factorial program demonstrates how to take user input with int(input()) and use a for loop for calculations. This same pattern is applied here for printing a multiplication table. The function approach follows the question requirement, and the loop iterates 10 times to print the standard multiplication table format.
Solution Steps
Step 1: Define a function print_table() that accepts a number as parameter.
Step 2: Use a for loop with range(1, 11) to iterate from 1 to 10.
Step 3: Inside the loop, print each multiplication line using print(num, 'x', i, '=', num * i).
Step 4: In the main program, accept user input using int(input()).
Step 5: Call the function with the user-entered number.