1

Hi I'm teaching myself python, have downloaded 3.4 and am working through Think Python. The problem i'm having is printing a grid. I won't put the whole code up but the bit that is a problem.

def do_twice(f):  
    f()  
    f()

def print_beam():   
    print("+ - - - - ", )

def print_beams():  
    do_twice(print_beam)
    print("+")

now this when called is supposed to print a beam like this + - - - - + - - - - +

However, the actual output is
+ - - - -
+ - - - -
+

I've spent a good two hours on this but the version of python i'm using is different from the book I'm working on. Could anyone help me out of this log jam?

4
  • What version are you using? If you aren't sure, try import sys; print(sys.version) Commented Mar 4, 2016 at 19:52
  • You're reading a Python 2 tutorial and running it on Python 3. That's the problem. Commented Mar 4, 2016 at 19:54
  • 3.4.4 but the book is something diff 3.2 maybe Commented Mar 4, 2016 at 19:55
  • 1
    If your book suggested putting a comma at the end of a print statement in order to suppress a newline, then it's almost certainly written for 2.7 or lower. I assume that's why you've got a stray comma in your print_beam function? Commented Mar 4, 2016 at 19:56

3 Answers 3

5

The problem is that, by default, the print function creates a new line at the end of its output. Here's an easy fix.

def do_twice(f):  
    f()  
    f()

def print_beam():   
    print("+ - - - - ", end='') #Don't create a new line.

def print_beams():  
    do_twice(print_beam)
    print("+")
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your help Gareth, that has fixed it immediately. So glad I came here instead of banging my head for another 2 hours. Thanks so much!
@MarkNolan Don't forget to mark this as the answer for others passing by!
1

With python 3 to prevent newline characters being printed set end="" like so:

print("+ - - - -", end="")

You can read the documentation on this here

Comments

0

print statements with argument (end), lets you continue on the next line. i used python 3.8 version

def print_beam():
    print('+',end=' ')
    print('-','-','-','-', end=' ')
    print('+', end=' ')
    print('-', '-', '-', '-', end=' ')
    print('+')

def print_column():
    print('|',end=' ')
    print(' ',' ',' ',' ', end=' ')
    print('|', end=' ')
    print(' ', ' ', ' ', ' ', end=' ')
    print('|')

1 Comment

This does not answer his question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.