在不同的时间打印出for循环的不同迭代


if hint1 in ["yes", "y", "Y"]:
secretword = ""
for letter in Player1_secretword:
secretword += letter
print (secretword)
break

我目前是一个构建猜谜游戏的初学者,这是我编写的代码,以便程序根据玩家的要求给出提示。第一次玩家需要提示时,单词的第一个字母应该出现,第二次玩家要求提示时,第二个字母出现,依此类推。

当我运行代码时,这是输出:

enter cwould you like a hint? (Y/N): yes
c
ca 
cat 

我希望程序只给出";c";当玩家第二次要求提示时;ca";等等,有什么可能让我做到这一点吗?

为什么不创建一个名为attempt的变量,每次用户请求提示时都会增加该变量?

然后可以使用这个变量来控制要输出的字符串的长度。

假设Player1_secretword是包含秘密单词的字符串,您可以简单地选择:

attempt=0
if hint1 in ["yes", "y", "Y"]:
attempt+=1
print(Player1_secretword[:attempt])

不用for循环,只需一行代码即可轻松完成:

def addHint(secret_word, hint):
hint+= secret_word[len(hint)+1]
## and somewhere in your main
if input("do you want a hint") in ['Yes','y','Y']:
addHint(secret, hint)

最新更新