Search code examples
pythonloopswhile-loopmultiplication

While loop is not producing multiplication table


i = 0
d =  input("Enter the no. you want ")
while i < 11 :
    print(i * d)
    i+= 1

It is supposed to give multiplication table of d but it gives the following result for eg. '3' instead

3 

33

333

3333

33333

333333

3333333

33333333

333333333

3333333333

Solution

  • The input() returns a string not an int and if you multiply a string in Python with an integer num, then you will get a string repeated num times. For example,

    s = "stack"
    print(s * 3) # Returns "stackstackstack"
    

    You need to use int() constructor to cast the input from str to int.

    d =  int(input("Enter the no. you want "))
    

    Try this:

    d = int(input("Enter the no. you want "))
    for i in range(1,11):
        print(i * d)
    

    In the above code, I have replaced your while loop construct with for loop and range() to get sequence of numbers.

    BONUS:

    To print/display the table in a nice and better way, try the below code:

    for i in range(1,11):
        print("%d X %d = %d" % (d, i, i * d))
    

    Outputs:

    Enter the no. you want 2
    2 X 1 = 2
    2 X 2 = 4
    2 X 3 = 6
    2 X 4 = 8
    2 X 5 = 10
    2 X 6 = 12
    2 X 7 = 14
    2 X 8 = 16
    2 X 9 = 18
    2 X 10 = 20