0
def reveal():
    guessright = 0
    for letter in secretword:
        if letter == usertry:
            guessright = guessright + 1
            print usertry,
        else:
            print "_",
    return guessright

reveal()

When using reveal() something like _ _ _ _ a _ will be printed by the for loop- is there a way of converting what it prints into a string, or getting the function to return 2 outputs, the integer guessright, and the stuff that was printed while reveal() was running?

4 Answers 4

4

Sure, there are lots of ways -- The simplest is to use a list to hold the data (appending new data rather than printing) and then ''.join it at the end:

def reveal():
    text = []
    guessright = 0
    for letter in secretword:
        if letter == usertry:
            guessright = guessright + 1
            text.append(usertry)
        else:
            text.append('_')
    return guessright, ''.join(text)

reveal()

Here I return a tuple which is python's way of returning multiple values. You can unpack the tuple in assignment if you wish:

guessright, text = reveal()
Sign up to request clarification or add additional context in comments.

Comments

1

getting the function to return 2 outputs

def reveal():
    guessright = 0
    show = []
    for letter in secretword:
        if letter == usertry:
            guessright = guessright + 1
            show.append(usertry)
        else:
            show.append("_")
    return guessright, ''.join(show)

reveal()

Comments

1
def reveal():
  guessright = 0
  result = ""
  for letter in secretword:
    if letter == usertry:
      guessright = guessright + 1
      result += usertry
    else:
      result += "_"
  return guessright,result

reveal()

Comments

0

In python you can return two outputs by using a tuple.

In your code, you could return in by doing something like:

def reveal():
    guessright = 0
    text = ''
    for letter in secretword:
        if letter == usertry:
            guessright = guessright + 1
            text += usertry,
        else:
            text += "_",
    print text
    return (guessright, text)

(guessright, text) = reveal()

Then you can access guessright and text outside of the scope of `reveal()'.

1 Comment

You're right, but I've always liked the way it looks.

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.