Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

print() go wrong when multiple a string by any number, why does that happen?

when I use print() for string multiplication, it prints out an extra space (" ") at the beginning of each line. Strange. Anyone could explain why?

I was writing a Mario program with python. The program should run like this

$ python mario.py
Height: 4
   #
  ##
 ###
####

And this is my code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import cs50

while True:
    height = cs50.get_int("Height: ")
    if height > 0 and height < 9:
        break

for i in range(1, height + 1):
    print( " " * (height - i), "#" * i)


while the result gives me this

~/ $ python mario.py
Height: 4
    #
   ##
  ###
 ####

As you can see, each line has additional space in the front which shouldn’t even exist.

>Solution :

print separates its arguments with space, your calculations are right but there’s an added space.
change it to this:

import cs50

while True:
    height = cs50.get_int("Height: ")
    if height > 0 and height < 9:
        break

for i in range(1, height + 1):
    print( " " * (height - i), "#" * i, sep="")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading