if语句在函数内部表现不同

时间:2016-04-20 20:10:50

标签: python if-statement

好吧,所以我需要为python制作一个简单的刽子手游戏。我的功能和变量都有问题。猜测和替换"空白"当我尝试一个简单的if循环时会起作用,但是一旦我把所有东西都放到一个合适的函数中,它就会给我带来问题。

例如,当一个单词有超过1个字母的实例时,它会在函数外部尝试if循环时显示,但是使用该函数它只显示1.我删除了我的旧程序并重新重新启动,但我&# 39; m仍然遇到这个功能的问题(这是令人抓狂的)。在我遇到问题之前更新starCopy和尝试。这样一个简单的程序有这么多麻烦有点让我失望。 :\

这是在函数外部工作的循环:

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

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

现在,当我尝试调用函数时:

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)

它返回:

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

老实说,我不确定为什么我会用这个打砖墙。感觉我错过了一些超级简单的东西。

1 个答案:

答案 0 :(得分:1)

输出会发生变化,因为在基于函数的示例中,您返回变量starCopy。它在遇到匹配" guess"的第一个字母后立即返回,因此只有第一个字母被替换。将return命令移动到最后应该起作用:

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)