Function to return table of a number
Question:
I have tried below code to return a multiplication table for input number:
def table_of(n):
for i in range(1,11):
print(n,"*",i,"=",n*i)
a = input("Enter a Number:")
table_of(a)
This returns:
Enter a Number:2
2 * 1 = 2
2 * 2 = 22
2 * 3 = 222
2 * 4 = 2222
2 * 5 = 22222
2 * 6 = 222222
2 * 7 = 2222222
2 * 8 = 22222222
2 * 9 = 222222222
2 * 10 = 2222222222
What is the problem?
Answers:
The output from an input statement is always a string. You need to convert n
to an integer before multiplying, either at the input
statement, or in the print
, as below.
def table_of(n):
for i in range(1,11):
print(n,"*",i,"=",int(n)*i)
a = input("Enter a Number:")
table_of(a)
Gives the output:
Enter a Number:>? 2
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
The input()
function returns a string therefor the loop prints that string i times. The solution would be to replace a = input(“Enter a number: ”)
with
a = int(input(“Enter a number: ”))
make a function to return a table of any number without using print inside a functio python
def table(x):
for i in range(1,11):
yield f'{x}{i}={xi}’
num = int(input("Enter a number : "))
a = table(num)
for i in a:
print(i)
I have tried below code to return a multiplication table for input number:
def table_of(n):
for i in range(1,11):
print(n,"*",i,"=",n*i)
a = input("Enter a Number:")
table_of(a)
This returns:
Enter a Number:2
2 * 1 = 2
2 * 2 = 22
2 * 3 = 222
2 * 4 = 2222
2 * 5 = 22222
2 * 6 = 222222
2 * 7 = 2222222
2 * 8 = 22222222
2 * 9 = 222222222
2 * 10 = 2222222222
What is the problem?
The output from an input statement is always a string. You need to convert n
to an integer before multiplying, either at the input
statement, or in the print
, as below.
def table_of(n):
for i in range(1,11):
print(n,"*",i,"=",int(n)*i)
a = input("Enter a Number:")
table_of(a)
Gives the output:
Enter a Number:>? 2
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
The input()
function returns a string therefor the loop prints that string i times. The solution would be to replace a = input(“Enter a number: ”)
with
a = int(input(“Enter a number: ”))
make a function to return a table of any number without using print inside a functio python
def table(x):
for i in range(1,11):
yield f'{x}{i}={xi}’
num = int(input("Enter a number : "))
a = table(num)
for i in a:
print(i)