Mo yo
Mo yo

Reputation: 1

Im trying to make a multiplication table

I am trying to print a table that looks like this without extra spaces and the user inputs the lower bound(in this example 4) and the upper bound( in this example8).

#Get the inputs
input3=int(float(input("Give me the lower bound: ")))
input4=int(float(input("Give me the upper bound: ")))
#create a loop to multiply the upper and lower bounds 
multiplication_table_str= ""

for i in range(input3,input4+1):
    multiplication_table_str+= str(i) + ": "
    for x in range(input3,input4+1):
        multiplication_table_str+=str(i*x)+"\t"
    multiplication_table_str+="\n"    

print(multiplication_table_str)

what I have is outputting correctly but the numbers have a extra indent inside of that that I want to get rid of and I dont know how. I want it to look like this:

4: 16 20 24 28 32

5: 20 25 30 35 40

6: 24 30 36 42 48

7: 28 35 42 49 56

8: 32 40 48 56 64

Upvotes: 0

Views: 122

Answers (1)

Alain T.
Alain T.

Reputation: 42133

You should use format strings and the join() function to build your strings. This will give you full control on spacing and number alignment:

#Get the inputs
low=int(float(input("Give me the lower bound: ")))
high=int(float(input("Give me the upper bound: ")))

rWidth = len(str(high))
mTable = "\n".join( f"{r:{rWidth}}: "
                    + " ".join(f"{r*c:{len(str(c*high))}}"
                               for c in range(low,high+1))
                    for r in range(low,high+1))    
print(mTable)

Sample runs:

Give me the lower bound: 4
Give me the upper bound: 8
4: 16 20 24 28 32
5: 20 25 30 35 40
6: 24 30 36 42 48
7: 28 35 42 49 56
8: 32 40 48 56 64

Give me the lower bound: 8
Give me the upper bound: 11
 8: 64 72  80  88
 9: 72 81  90  99
10: 80 90 100 110
11: 88 99 110 121

Upvotes: 1

Related Questions