3

In Python I have a function that prints something. I want to print something beforehand on the same line.

So, I use the following code

print 'The hand is', displayHand(hand)

def displayHand(hand):

    for letter in hand.keys():
        for j in range(hand[letter]):
             print letter,              # print all on the same line
    print                               # print an empty line

What happens however is that the print within the function is called by the print outside the function.

How can I print an opening string, and then call my function?

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
user1778351
  • 143
  • 7

3 Answers3

5

Rename displayHand to renderHand and have it return a string.

zmbq
  • 38,013
  • 14
  • 101
  • 171
0

The answer provided by @zmbq with returning is the obvious and proper one but if you still want your way you can use newer print, assuming you are using python >= 2.6

from __future__ import print_function
print("Something", end="")

With that you can print without \n. So basically you can do then:

print("The hand is", end="")
displayHand(hand)

And in the function:

print("letter", end="")
Darek
  • 2,861
  • 4
  • 29
  • 52
0

For 2.x:

print 'The hand is', 
displayHand(hand)
print

For 3.x:

print('The hand is', end="")
displayHand(hand)
print()

The better method is to move printing of 'The hand is' into the function itself.

Lance Helsten
  • 9,457
  • 3
  • 16
  • 16