Sliverr
Sliverr

Reputation: 25

if statement behaving differently inside function

Alright, so I need to make a simple hangman game for python. and I'm having problems with my function and variables. Guessing and replacing "blanks" works when I try a simple if loop, but once I put everything into a proper function it gives me issues.

For example, when a word has more than 1 instance of a letter it shows both while trying the if loop outside the function, but using the function it only shows 1. I deleted my old program and restarted anew, but I'm still having trouble with this function (which is extra maddening). Before I was getting issues with it updating starCopy and attempts as well. Having this much trouble with such a simple program is kinda bumming me out. :\

Here's the loop that works while outside the function:

import random
#declare variables
guess="a"
choice="barnyard"
starredUp=len(choice) * "*"
starCopy=starredUp
attemptedLetters=[]
running=True
attempts=0

if guess in choice:
    starCopy=list(starCopy)
    for i, x in enumerate(choice):
        if x == guess:
            starCopy[i]=guess
            print(" ".join(starCopy));
            print("Letter in word! " + "Wrong Attempts: " + str(attempts))

Returns * * r * * * r * Letter in word! Wrong Attempts: 0

Now, when I try calling the function:

def guessMan(guess, choice, attempts, starCopy):
    if guess in choice:
        starCopy=list(starCopy)
        for i, x in enumerate(choice):
            if x == guess:
                starCopy[i]=guess
                print(" ".join(starCopy))
                print("Letter in word! " + "Wrong Attempts: " + str(attempts))
                return(starCopy)
    elif guess not in choice:
          attempts+=1
          print("yo fix it")
    elif guess in attemptedLetters:
          print("already guessed")
guessMan("r", choice, attempts, starCopy)

it returns:

* * r * * * * *
Letter in word! Wrong Attempts: 0

Honestly not sure why I'm hitting such a brick wall with this. Feel like I'm missing something super simple.

Upvotes: 0

Views: 47

Answers (1)

Thomite
Thomite

Reputation: 741

The output changes because in your function-based example, you return the variable starCopy. It returns immediately after it hits the first letter that matches "guess", so only the first letter gets replaced. Moving the return command to the end should work:

def guessMan(guess, choice, attempts, starCopy):
    if guess in choice:
        starCopy=list(starCopy)
        for i, x in enumerate(choice):
            if x == guess:
                starCopy[i]=guess
                print(" ".join(starCopy))
                print("Letter in word! " + "Wrong Attempts: " + str(attempts))

    elif guess not in choice:
          attempts+=1
          print("yo fix it")
    elif guess in attemptedLetters:
          print("already guessed")

    return(starCopy)

Upvotes: 1

Related Questions