为什么我的python程序没有以正确的顺序运行代码?

时间:2015-03-21 03:38:48

标签: python

我刚开始使用python,我正在编写一本关于书籍的刽子手游戏。我可以知道为什么下面的代码没有按照我希望它运行的顺序运行?

当我执行该程序时,guess中猜到的字母应该进入used以指示玩家已经猜到哪些字母找出正确的单词。但是,这只发生在每2圈而不是每1圈。我在程序开头用一个图像文件表示了刽子手ACSII艺术作为参考,图像下面是代码。很乐意感谢任何帮助。谢谢!

enter image description here

MAX_WRONG = len(HANGMAN)-1

WORDS = ("book","toy","paper","school","house","computer","television")
word=random.choice(WORDS)
so_far = "-"*len(word)
wrong = 0
used = []

print "Welcome to hangman! Guess the the word before the the man is hang      dead!"
print "You can only guess one letter at a time!"

while wrong < MAX_WRONG and so_far!=word:
    print HANGMAN[wrong]
    print "\nYou've used the following letters:\n",used
    print "\nSo far, the word is:\n", so_far
    guess = raw_input("\n\nEnter your guess:")
    guess = guess.lower()

    if guess in word:
        used+=guess
        print "\nYou've used the following letters:\n",used
        print"\nYes!",guess,"is in the word!"
        new=""
        for i in range(len(word)):
            if guess == word[i]:
                new+=guess
            else:
                new+=so_far[i]
        so_far=new

    else:
        used+=guess
        print "\nYou've used the following letters:\n",used
        print "\nSo far, the word is:\n", so_far
        print"\nSorry,",guess,"isn't in the word."
        guess = raw_input("\n\nEnter your guess:")
        wrong+=1

    while guess in used:
        print "You've already guessed the letter:",guess
        print "\nYou've used the following letters:\n",used
        print "\nSo far, the word is:\n", so_far
        guess = raw_input("Enter your guess:")
        guess = guess.lower

if wrong == MAX_WRONG:
    print HANGMAN[wrong]
    print "\nYou've been hanged!"
else:
    print "\nYou guessed it!"

print "\nThe word was",word

raw_input("\n\nPress the enter key to exit.")

1 个答案:

答案 0 :(得分:0)

似乎发生了2回合,但事实并非如此。问题是您的程序在一个回合中提示用户两次。在循环开始时,您要求用户提供一封信。如果它告诉我这是错的,那么你要求另一封信。然后你的循环重复,你再次要一封信。

问题是你在循环中要求两次,而不是一次。在编程中,我们有所谓的DRY principle,这意味着不要重复自己。您的代码显示了不重复自己的众多原因之一。您认为您的循环运行了两次,但实际上您只是在循环中多次运行相同的代码。