1

Am a beginner in Programming and am practicing how to use nested for loops to make a multiplication table in python 2.7.5. Here is my code

x=range(1,11)
y=range(1,11)
for i in x:
    for j in y:
        print i*j
    pass

well,the result is correct but it does not appear in a square matrix form as i wish.Please help me improve the code

martineau
  • 119,623
  • 25
  • 170
  • 301
  • you could read about list comprehension and print such lists. also the `pass` is useless. – Julien Aug 09 '16 at 15:00
  • 1
    @JulienBernu: The OP is just learning about basic `for` loops. They should master them before going onto more advanced syntax like list comprehensions. – PM 2Ring Aug 09 '16 at 15:01
  • Sure, `r=range(1,11);print '\n'.join([''.join(['%4s'%(i*j)for i in r])for j in r])` does the trick, but it's not exactly easy to read. :) And it's totally _unhelpful_ for someone who's just starting to learn how to program. – PM 2Ring Aug 09 '16 at 15:20
  • The old print statement has been phased out in Python 3. You should probably be using the new print _function_ instead. It's got a few neat features that the old print statement doesn't have. You can use that function in Python 2.7 by putting `from __future__ import print_function` at the start of the script. – PM 2Ring Aug 09 '16 at 15:26
  • BTW, you probably should be learning Python 3 if you're just starting now, unless you have a _really_ good reason to be learning Python 2, since Python 2 will no longer be supported after 2020. – PM 2Ring Aug 09 '16 at 15:27

5 Answers5

8

You should print without a line break.

x = range(1,11)
y = range(1,11)
for i in x:
    for j in y:
        print i*j,    # will not break the line
    print   # will break the line
Doron Cohen
  • 1,026
  • 8
  • 13
2

you may add formatting to keep constant cell width

x = range(1,11)
y = range(1,11)
for i in x:
    for j in y:
        # substitute value for brackets
        # force 4 characters, n stands for number
        print '{:4n}'.format(i*j),  # comma prevents line break
    print  # print empty line
warownia1
  • 2,771
  • 1
  • 22
  • 30
1

Python's print statement adds new line character by default to the numbers you wish to have in your output. I guess you would like to have just a trailing spaces for inner loop and a new line character at the end of the outer loop.

You can achieve this by using

print i * j,   # note the comma at the end (!)

and adding just a new line at the end of outer loop block:

print ''

To learn more about the trailing coma, and why it works, look here: "How to print in Python without newline or space?". Mind that it works differently in Python 3.

The final code should look like:

x=range(1,11)
y=range(1,11)
for i in x:
    for j in y:
        print i*j,
    print ''

You can also look for '\t' special character which would allow you to get better formatting (even this old resource is good enough: https://docs.python.org/2.0/ref/strings.html)

Community
  • 1
  • 1
krassowski
  • 13,598
  • 4
  • 60
  • 92
0

USE This Code. It works MUCH better. I had to do this for school, and I can tell you that after putting about 4 hours into this it works flawlessly.

def returnValue(int1, int2):
    return int1*int2

startingPoint = input("Hello! Please enter an integer: ")
endingPoint = input("Hello! Please enter a second integer: ")

int1 = int(startingPoint)
int2 = int(endingPoint)

spacing = "\t"

print("\n\n\n")
if int1 == int2:
    print("Your integers cannot be the same number. Try again. ")
    

if int1 > int2:
    print("The second number you entered has to be greater than the first. Try again. ")


for column in range(int1, int2+1, 1):  #list through the rows(top to bottom)
    
    if column == int1:
            for y in range(int1-1,int2+1):
                if y == int1-1:
                    print("", end=" \t") 
                    
                else: 
                    individualSpacing = len(str(returnValue(column, y)))
                    print(y, " ", end=" \t")
            print()
            
    print(column, end=spacing)

    
    for row in range(int1, int2+1, 1): #list through each row's value. (Go through the columns)
        #print("second range val: {:}".format(row))
        
            individualMultiple = returnValue(row, column)
            print(individualMultiple, " ", end = "\t")
        
    print("")

Have a good day.

J Derbs
  • 153
  • 14
0
#Generate multiplication table by html


import random

from copy import deepcopy

N = 15



colors = ['F','E','D','C','B','A']

i = 0

colorsall = []

while i < N:

    colornow = deepcopy(colors)

    random.shuffle(colornow)

    colornow = "#"+"".join(colornow)

    colorsall.append(colornow)

    i += 1

t = ""

for i in range(1,N+1):

    s = ''

    for j in range(1,N+1):

        if j >= i:

            s += '<td style="background-color:' + colorsall[i-1] + '">'+str(i*j)+'</td>'

        else:

            s += '<td style="background-color:' + colorsall[j-1] + '">'+str(i*j)+'</td>'

    s = "<tr>" + s + "</tr>"



    t = t + s + '\n'

    

print('<table>' + t + '</table>')

Taken from https://todaymylearn.blogspot.com/2022/02/multiplication-table-in-html-with-python.html [Disclosure : my blog]

Vinod
  • 4,138
  • 11
  • 49
  • 65