Python print without line breaks

I was working on a pseudocode test bank and got caught with one of the differences between Java and Python.

One of the questions was something like this.

x = 3
loop while x < 10
  print x + " "

The expected answer 3 6 9 has the values concatenated. It’s just easier that way when dealing with online testing in Canvas or Moodle.

In Python 2 I could use print x, and the trailing comma would take care of not inserting a line break, although it still inserted a trailing space which wasn’t ideal.

Thanks to Stack Overflow I found the solution. There’s an optional parameter called end in the print method that lets you control the trailing characters. So you just do this.

x = 3
while x < 10:
   print(str(x) + " ", end = '')

Guess I could have searched through the Python documentation for print. But Google brought me to SO first.

CompSci.rocks Newsletter

Want to stay in touch and keep up to date with the latest posts @ CompSci.rocks?

Leave a Reply

Your email address will not be published. Required fields are marked *