【问题标题】:I am trying to write a code for something similar to hangman, but it is not working我正在尝试为类似于 hangman 的东西编写代码,但它不起作用
【发布时间】:2020-04-18 12:24:09
【问题描述】:

我正在尝试编写一个刽子手之类的东西,但即使在正确猜到单词之后,循环仍在继续。 似乎不起作用的位是最后的if word == ("".join(userword)) 位,但我不知道我做错了什么。

import random
word = random.choice(["apple", "orange", "pineapple"])
word = list(word)
life = 5
userword = []

for i in range (len(word)):
    userword.append("_")

while life > 0: 
    print("".join(userword))
    print("enter a letter")
    letter = input()
    letterinword = False
    for i in range(len(word)):
        if word[i] == letter:
            userword[i] = letter
            letterinword = True

    if letterinword == False:
        life = life - 1

    if word == ("".join(userword)):
        break

【问题讨论】:

    标签: python list if-statement conditional-statements


    【解决方案1】:

    这是因为“word”在第 3 行被转换为列表。

    所以你在比较

    ['a','p','p','l','e'] == 'apple'
    

    最简单的解决办法是

    if "".join(word) == "".join(userword):
    

    【讨论】:

      【解决方案2】:

      您不需要将随机选择的单词转换为列表:

      word = random.choice(["apple", "orange", "pineapple"])
      word = list(word)
      

      删除上面的第二行,您的退出子句将起作用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-23
        • 2021-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-14
        相关资源
        最近更新 更多