mimi454
mimi454

Reputation: 9

Convert for loop/print output to string? Python

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?

Upvotes: 0

Views: 246

Answers (4)

Adam
Adam

Reputation: 4683

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()'.

Upvotes: 0

Andrej
Andrej

Reputation: 7504

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

reveal()

Upvotes: 1

mgilson
mgilson

Reputation: 310079

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()

Upvotes: 4

inspectorG4dget
inspectorG4dget

Reputation: 114035

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()

Upvotes: 1

Related Questions