Beginning classes Printing a string on multiple lines

3.3k views Asked by At

in python

I am taking edx courses at home to expand my skill set into programming. One of the assignments I have run into has me stumped. The goal is to be able to insert a integer and have a times table printed out for it.

This table is to be broken into columns and rows. I can assemble the values I need into a string for all of the numbers times each other given variable input. I added the tabs that are called for between integers.

Now this is in one string and I can't get it to break into different sized chinks and print based on different values entered initially.

I tried text wrap but got errors no matter how i put it based off of different examples.

Please help me to find a solution and explain why it works. I am trying to learn this not have a spoonfed line of code that will solve the problem but leave me ignorant still.

None of the hints i found in the slack for this class contained terms or commands listed in the course so far. Lots that weren't listed though.

Here is what I have and please ignore the extras left from trying different solutions.

   mystery_int = 5

#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.

#This is a tough one! Stick with it, you can do it!
#
#Write a program that will print the times table for the
#value given by mystery_int. The times table should print a
#two-column table of the products of every combination of
#two numbers from 1 through mystery_int. Separate consecutive
#numbers with either spaces or tabs, whichever you prefer.
#
#For example, if mystery_int is 5, this could print:
#
#1  2   3   4   5
#2  4   6   8   10
#3  6   9   12  15
#4  8   12  16  20
#5  10  15  20  25
#
#To do this, you'll want to use two nested for loops; the
#first one will print rows, and the second will print columns
#within each row.
#
#Hint: How can you print the numbers across the row without
#starting a new line each time? With what you know now, you
#could build the string for the row, but only print it once
#you've finished the row. There are other ways, but that's
#how to do it using only what we've covered so far.
#
#Hint 2: To insert a tab into a string, use the character
#sequence "\t". For example, "1\t2" will print as "1    2".
#
#Hint 3: Need to just start a new line without printing
#anything else? Just call print() with no arguments in the
#parentheses.
#
#Hint 4: If you're stuck, try first just printing out all
#the products in one flat list, each on its own line. Once
#that's working, then worry about how to organize it into
#a table.


#Add your code here!
import textwrap
a = mystery_int
b = 1
c = 0
d = 1
e = ""
f = ""
g = "" 
h = "\t"
j = 1
k = a*2

for b in range(1,a + 1):
    for c in range(1,a+1):
        d = b * c
        e +=str(d)+","
        f = str(e)

g = str.replace(f,"," ,"\t")

#textwrap.wrap(g,10)
#print(g[0:int(k)])
print(g[:k])
2

There are 2 answers

2
andrew_reece On BEST ANSWER

You're almost there, you just need to collect the values for each row in a list, and then print row values after each iteration of the inner loop.

Given that you basically already have a full solution, barring a few small bugs, I'm going to provide a complete walkthrough of the solution, with explanations.

Notation: We'll use mystery_int instead of a, and we'll change b (outer loop increment) to i, and c (inner loop increment) to j, in keeping with convention:

mystery_int = 5

for i in range(1, mystery_int+1):
    row = [str(i)]
    for j in range(2, mystery_int+1):
        row = row + [str(i*j)]
    print('\t'.join(row))

Output:

1   2   3   4   5
2   4   6   8   10
3   6   9   12  15
4   8   12  16  20
5   10  15  20  25

The outer loop (i) iterates over rows, and the inner loop (j) over columns.
At each new row, we want a new list, row, that starts out having only one element. That first element is the number we'll be making multiples of (so the first element of row 1 is 1, the first element of row 2 is 2, and so on).

Note that we're converting all our integers to strings (i --> str(i)), as we'll eventually want to print out each row as a whitespace-separated sequence.

  • Anytime you're printing with whitespace, even if the content you want to print is made up of numbers, you need to convert that content into a string representation. (You've already done this in your code, but the point is worth reiterating as it's a common stumbling block.)

Now, in the inner loop (j), compute the product for each column after the first (i*2, i*3, ..., i*mystery_int). For each pass over the inner loop, add the new product to row. By the time we finish the inner loop, we'll have a complete list of the multiplication series for the row starting with integer i.

At this point, before moving to the next row, print out the current row. The join() method is a common way of connecting elements in a list, using the separator specified before the ..

  • For example, ' '.join(row) will create a string of single-space-separated values:

    ' '.join(["1","2","3","4","5"])
    # '1 2 3 4 5'
    
  • I chose to use tab-separated strings, as the printed output has nicer formatting. (Since some rows have double-digit numbers and others only have single-digit numbers, a single-space separator makes the columns appear misaligned.)

Notes:

  • From an instructional standpoint, it seems more intuitive to initialize each new row with the "base" integer i: row = [str(i)]. That provides a visual anchoring for the rest of the row computations that follow, inside the inner loop. However, it's also valid (and maybe a bit "cleaner") to simply initialize an empty list, row = [], and then begin the inner loop with j = 1:

    for i in range(1, mystery_int+1):
        row = []
        for j in range(1, mystery_int+1):
            row = row + [str(i*j)]
        print('\t'.join(row))
    
  • With additional modules, it's possible to accomplish the same goals with simpler, and often faster, code. It appears you're working with the Python standard library, which is why I kept to basics in the main solution. But considering that a multiplication table is really the outer product of two identical vectors, we could also use the Numpy module, which provides lots of speedy mathematical operations:

    import numpy as np
    print(np.array2string(np.outer(np.arange(1, mystery_int+1), 
                                   np.arange(1, mystery_int+1)), 
                          separator='\t'))
    

Point being, as you start to use Python more to accomplish a given task, rather than simply learning programming basics, it's reasonable to assume that there's a module out there that is custom-suited to your needs, which can be a real time-saver. There's a Python module for just about everything!

0
Glenn Chamberlain On
for i in range(1, mystery_int + 1):
    row_string = ""
    for j in range(1, mystery_int + 1):
        product = i * j
        row_string += str(product) + "\t"
    print(row_string)