检查变量以查看它是否不再包含字符串

时间:2013-05-08 16:49:26

标签: python

def main():
    #word = input("Word to guess for player 2:")
    word = ['h','e','l','l','o']
    word2 = "hello"
    #make a list of _ the same length as the word
    display =[]
    for i in range (0,len(word)):
        display.append("_")

    chances = int(input("Number of chances to guess word:"))
    if len(word)== 11:
        print ("Your word is too long. It has to be 10 charecters or less")
    else:
        word = word
    if chances < len(word):
        answer = input("Your word is {0} letters long , are you sure you don't want more chances? Yes or no?". format (len(word)))
        if answer == "no":
            chances= int(input("Number of chances:"))
        else:
            chances = chances
            ("Ok then lets continue with the game")
    print ("Player 2, you have {0} chances to guess the word.". format (chances))
    won = False
    underscore = False
    while chances > 0 and won == False and underscore == False:
        guess = input("Enter your guess: ")
        gC=False

        for i in range (0,len(word)):
            if guess == word[i]:
                gC=True
                display[i]=guess

        if not gC:
            chances = chances - 1

        display2 = ""
        for i in display:
            display2 = display2 + i + " "

由于某些原因,当我说明我的while循环时代码不起作用,因为游戏继续进行直到用户用尽猜测'。有没有人对我如何解决这个问题有任何建议?

2 个答案:

答案 0 :(得分:2)

当用户通过猜测所有字母赢得游戏时,你永远不会将won设置为True。

答案 1 :(得分:0)

这不是您原始问题的答案,而是更多的代码审核,但也许您会觉得它很有用。

word = list('hello')  # replaces manual splitting of string into letters

display = [ '_' ] * len(word)  # replaces build-up using for-loop

chances = input("Number ... ")  # already returns int if the user enters an int
                                # but will evaluate any valid python expression the
                                # user enters; this is a security risk as what
                                # ever is done this way will be done using your
                                # permissions
chances = int(raw_input("Number ..."))  # probably what you wanted

...
else:
    word = word  # does nothing.  remove this line and the "else:" above

chances -= 1  # replaces 'chances = chances - 1' and does the same

display2 = ' '.join(display)  # replaces the for-loop to build display2

此外,我建议使用更好的名字。在此上下文中,display2gC等变量不是很有用。在专业编程中,您始终要记住,您正在为下一位必须维护代码的开发人员编写代码(也包括主要代码)。因此,使其可读和易懂。请改为选择displayStringguessedCorrectly等名称。