Practical 9: Program to Print the Multiplication Table of n Where n Value is Entered by User
Problem Statement
Write a Python program to print the multiplication table of a number n that is entered by the user.
The program should:
- Take an integer input n from the user.
- Print the multiplication table for n from 1 to 10.
For example, if the user enters 5, the program should print:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
…
5 x 10 = 50
Solution Code
# Program to print the multiplication table of n
# Input: Take an integer n from the user
n = int(input("Enter a number to print its multiplication table: "))
# Loop through numbers 1 to 10 and print the multiplication table
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")
Output
- The program will ask the user to input a number n.
- It will then print the multiplication table of n from 1 to 10.
Example outputs for different inputs:
Enter a number to print its multiplication table: 12
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6
= 72
12 x 7
84
12 x 8
96
12 x 9 108
12 x 10 = 120
Process finished with exit code 0
Explanation
Below is the explanation of F.E. PPS Unit 2 Practical 9 solution where we have written PythonProgram to Print the Multiplication Table of n Where n Value is Entered by User
- Input of Number:
- The program prompts the user to enter a number n using the input() function. The input is converted to an integer using int() to ensure that it can be used in mathematical operations.
- Loop for Multiplication Table:
- The program uses a for loop to iterate through numbers from 1 to 10 (range(1, 11)).
- For each iteration i, the program calculates the product of n and i (i.e., n * i), and then prints the result in the format n x i = product.
- Displaying the Multiplication Table:
- The result is printed in the format “n x i = product” using f-string formatting for clear and readable output.
Key Concept Learned
- Using Loops for Repetitive Tasks:
- The program demonstrates the use of a for loop to repeatedly perform a task (multiplication) and print the result. Loops are fundamental in programming, especially when dealing with tasks that require repetition.
- String Formatting:
- The program uses f-string formatting (e.g., f”{n} x {i} = {n * i}”) to output the multiplication table in a readable format. This is a clean and efficient way to format strings in Python.
- Basic Arithmetic Operations:
- The program reinforces the basic arithmetic operation of multiplication and shows how it can be used within a loop to generate a series of results.
- User Input Handling:
- The program demonstrates how to handle user input and use it in calculations.