Home > Back-end >  Printing issues when moving from Python 2 to 3 with code
Printing issues when moving from Python 2 to 3 with code

Time:11-16

I have a code that I am trying to convert but it's written in Python 2 and I would like to print this code in Python 3. However, it's not able to print in matrix format. I am getting output in an unrecognizable table format.

The code is following:

 for n in cols:
    print('/t',n),
print
cost = 0

for g in sorted(costs):
    print('\t', g)
    for n in cols:
        y = res[g][n]
        if y != 0:
            print (y),
        cost  = y * costs[g][n]
        print ('\t'),
    print
print ("\n\nTotal Cost = ", cost)

The expected output is in the following format:

|0 |A |B |C |D |E |
|- |- |- |- |- |- |
|W |  |  |20|  |  |        
|X |  |40|10|  |20|  
|Y |  |20|  |  |30|      
|Z |  |  |  |  |60|  


Total Cost =  1000

Could you suggest what changes I need to make in this code?

CodePudding user response:

In py 2 print did not have parenthesis, in py3 is a must.

python3 simple print
# in py3 a print must be like
print("my text")
python3 print with no newline / carriage return

Also in your py2 code you have print ('\t'), please mind the comma after print => which means do not add a newline after print. In python3 would translate to

print('\t', end='')

CodePudding user response:

Your print calls must always be enclosed in parenthesis like this:

print("\t", n)

CodePudding user response:

Another thing - whenever you see the Python 2 print command with a comma at the end, such as

print y,  

you need to change that line to:

print(y,end="")

This will print the variable without a new line.

  • Related