【问题标题】:May someone help me figure out how to update my dashes on my python hangman code有人可以帮我弄清楚如何在我的 python hangman 代码上更新我的破折号
【发布时间】:2018-07-31 13:26:10
【问题描述】:

我应该能够更新这些破折号,以便当有人输入“a”时,破折号看起来像 a---a-。如果用户猜到字母“l”,破折号将看起来像 a---al。

magic_word = "animal"  

dashes = "--------"   

def get_guess()   

while True:  
print dashes  
    guess = str(input("Guess a letter: "))  
 if len(guess)>1:    
        print "Too long"     
        continue    
 elif not guess.islower():  
        print "Your guess must be one lowercase letter"  
        continue  
    if guess in magic_word :  
        print "That is in the word"  
        continue  
    else:  
        print "That is not in the word"  
        continue  
        return guess  
        break  
get_guess() 

【问题讨论】:

    标签: python python-3.x python-2.7 python-requests


    【解决方案1】:

    您可能想使用不同的方法来查看猜测是否在魔术词中。

    一种这样的方法是遍历字符串,每当在魔术词中找到猜测时,更新破折号字符串中的相应空格:

    for x in range(len(magic_word)):
        if guess == magic_word[x]:
            dashes[x] = guess
    

    这将为您更新破折号

    【讨论】:

    • 在这个作业中,我应该使用“while True”循环,所以我会用“for x in range...”替换它吗
    • 你可以把它放在“if guess in magic_word :”语句下
    【解决方案2】:

    您应该使用“index()”方法来查找字符的索引,然后使用“replace()”方法将破折号替换为该单词。

    indexOfGuessChar = magic_word.index(guess)
    dashes = dashes.replace(dashes[indexOfGuessChar], guess)
    

    这样的事情就可以解决问题,只需让这些功能发挥作用并使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      • 2021-02-12
      • 2022-12-28
      • 1970-01-01
      • 2020-09-25
      • 2022-11-22
      相关资源
      最近更新 更多