如果在Python中声明错误

时间:2015-06-19 11:00:07

标签: python

我的Python代码中似乎有一个反复出现的错误......我认为问题出在if声明中,您是否有可能帮助我?我正在学校做作业,看来如果用户猜到这个词,他们会得到祝贺,如果他们没有得到它,他们必须再试一次。

我的代码:

import time
import random
import os

words = open("Words.txt","r")
WordList = []

for lines in words:

 WordList.append(lines)
 WordList=[line.rstrip('\n')for line in WordList]


print(WordList[0:3])
print(WordList[3:6])
print(WordList[6:9])
time.sleep(2)
os.system(['clear','cls'][os.name == 'nt'])

random.shuffle(WordList)

print(WordList[0:3])
print(WordList[3:6])
print(WordList[6:9])

removedword = (WordList[9])

print("---------------------------")

guesses = 0

while guesses <3:
guess = input("What is the removed word?")
guesses = guesses + 1

  if guess == removedword:
      print("You have guessed correctly!")

  else:
      print("Fail")

在shell中:

['NIGHT', 'SMOKE', 'GHOST']
['TOOTH', 'ABOUT', 'CAMEL']
['BROWN', 'FUNNY', 'CHAIR']
['TOOTH', 'BROWN', 'CHAIR']
['PRICE', 'SMOKE', 'FUNNY']
['ABOUT', 'NIGHT', 'CAMEL']
---------------------------
What is the removed word?GHOST
You have guessed correctly!
What is the removed word?GHOST
You have guessed correctly!
What is the removed word?GHOST
You have guessed correctly!

3 个答案:

答案 0 :(得分:2)

guesses = 0
flag = 0
while guesses <3:
 guess = input("What is the removed word?")
 guesses = guesses + 1

 if guess == removedword:
     print("You have guessed correctly!")
     flag = 1
     break
  else:
     print("Fail")

if flag == 0:
  print("Game over")

答案 1 :(得分:1)

guesses = 0

while guesses <3:
    guess = input("What is the removed word?")
    guesses = guesses + 1

    if guess == removedword:
      print("You have guessed correctly!")
      break
    else:
      if guesses == 3:
        print("Game over")
      else:
        print("Try again")

答案 2 :(得分:1)

你的while循环计数到3并且即使你的答案是正确的也不会停止。为避免这种情况,您需要检查答案是否正确并打破循环。

以下是更改后的代码:

import time
import random
import os

words = open("Words.txt","r")
WordList = []

for lines in words:
    WordList.append(lines)
    WordList=[line.rstrip('\n')for line in WordList]


print(WordList[0:3])
print(WordList[3:6])
print(WordList[6:9])
time.sleep(2)
os.system(['clear','cls'][os.name == 'nt'])

random.shuffle(WordList)

print(WordList[0:3])
print(WordList[3:6])
print(WordList[6:9])

removedword = (WordList[9])
#printed this so I could win every time
#print(removedword)

print("---------------------------")

guesses = 0
#Added flag 
unanswered = True

#while guesses less than 3 and question is unanswered 
while guesses <3 and unanswered:
    guess = input("What is the removed word?")
    guesses = guesses + 1
    if guess == removedword:
        print("You have guessed correctly!")
        #correct answer, changes flag
        unanswered = False
    else:
        print("Fail")

if unanswered:
    print("Game over!")