How to print a multiplication table in python in which the number must be defined by the user and print the table up to a maximum of 20 rows. Even if the number of rows asked by the user is more than 20, we should limit up to 20 rows and print an error message saying "rows is limited to 20"
Take input from the user in which-
6 * 1 = 6
6 * 2 = 12
6 * 3 = 18
6 * 4 = 24
6 * 5 = 30
6 * 6 = 36
6 * 7 = 42
6 * 8 = 48
6 * 9 = 54
6 * 10 = 60
6 * 11 = 66
6 * 12 = 72
6 * 13 = 78
6 * 14 = 84
6 * 15 = 90
6 * 16 = 96
6 * 17 = 102
6 * 18 = 108
Enter the number for the multiplication table: 9
Enter the number of rows for the multiplication table: 25
9 * 1 = 9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
9 * 5 = 45
9 * 6 = 54
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81
9 * 10 = 90
9 * 11 = 99
9 * 12 = 108
9 * 13 = 117
9 * 14 = 126
9 * 15 = 135
9 * 16 = 144
9 * 17 = 153
9 * 18 = 162
9 * 19 = 171
9 * 20 = 180
rows is limited to 20
x = int(input("Enter the number for the multiplication table: "))
y = int(input("Enter the number of rows for the multiplication table: "))
for i in range(1, y + 1):
result = x * i
print(f"{x} * {i} = {result}")
else:
if y > 20:
print("The number of rows has been limited to 20.")
Enter the number for the multiplication table: 9
Enter the number of rows for the multiplication table: 25
9 * 1 = 9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
9 * 5 = 45
9 * 6 = 54
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81
9 * 10 = 90
9 * 11 = 99
9 * 12 = 108
9 * 13 = 117
9 * 14 = 126
9 * 15 = 135
9 * 16 = 144
9 * 17 = 153
9 * 18 = 162
9 * 19 = 171
9 * 20 = 180
9 * 21 = 189
9 * 22 = 198
9 * 23 = 207
9 * 24 = 216
9 * 25 = 225
rows is limited to 20
I want to remove the extra lines after 9 * 20 = 180 and display the error message. (Please keep the for loop and the else statement)
If you want to keep the requirement of using for loop and else statement, you can add a conditional statement inside the loop and use it to break the loop when the condition is met. Here's the modified code:
x = int(input("Enter the number for the multiplication table: "))
y = int(input("Enter the number of rows for the multiplication table: "))
for i in range(1, y + 1):
result = x * i
print(f"{x} * {i} = {result}")
if i >= 20:
print("The number of rows has been limited to 20.")
break
else:
if y > 20:
print("The number of rows has been limited to 20.")