這裏是我的代碼:的Python - 猜一個字遊戲
import random
guesses = 0 #Number of tries to guess.
print ("Welcome to Guess Me!")
print ("\nYou have five guesses, choose letter and guess a word.")
print("\nAll of luck!")
def rand_word():
f = open('sowpods.txt', 'r').readlines() #Sowpods is library with some random words
return random.choice(f).strip()
word = rand_word()
print word #I printed a word just so i can test if is working.
correct = word
lenght = len(word) #I want to tell them how many letters a word contain
new_length = str(lenght)
guess = raw_input("The word is " + new_length + " letters long. Guess a letter: ")
while guesses < 5:
if guess not in word:
print("Sorry, this letter is not in word.")
else:
print("Correct, word contain this letter!")
guesses =+ 1
if guesses > 5:
final_answer = raw_input("You ran out of guesses, what is your answer?")
if final_answer == correct:
print("That's correct, congratulations you won!")
else:
print("Sorry, correct word is" + " " + word + " ,you can try again!")
問題是,當我運行我的代碼,比方說,我輸入字母「S」,我的崇高凍結和我得到的消息「崇高3沒有反應..「,我不得不關掉它。也許這是while循環?無窮?
是的,它看起來像有一個無限循環的'而猜測<5:' – davedwards
提示:縮進是Python的關鍵! – eddiewould
在'guesses = + 1'行之前的空行上沒有縮進,所以它不包含在while循環中,將相同的縮進添加到該空行,並改爲'guesses + = 1',應該可以工作。 – davedwards