[英]if statement behaving differently inside function
好吧,所以我需要为python创建一个简单的子手游戏。 而且我的函数和变量有问题。 当我尝试一个简单的if循环时,猜测并替换“空白”是可行的,但是一旦我将所有内容放入适当的函数中,它就会给我带来问题。
例如,当一个单词有一个以上的字母实例时,尝试在函数外执行if循环时会同时显示两个字母,但是使用该函数时它只会显示1。我删除了旧程序并重新启动,但是我仍然有此功能的麻烦(这很令人发疯)。 在我遇到问题之前,还更新了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
* * 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
老实说,我不确定为什么要用这种方式撞到这样的砖墙。 感觉就像我缺少了一些超级简单的东西。
输出更改,因为在基于函数的示例中,您返回了变量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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.