![](/img/trans.png)
[英]Why is my simple else statement not working correctly in my while loop?
[英]Why is my while/if statement not working?
我正在制作自己的 Hangman Python 程序,我仍然是 python 編程的新手,所以我不太明白我做錯了什么。 我已經指定生命限制為 6,但是當輸入錯誤的輸入時,生命可以 go 下降到 -2,正如控制台所說..
import random
words = ["stone"]
word = words[random.randint(0, (len(words)) - 1)]
wordToLetters = list(word)
gaps = ["_"] * len(word)
lives = 6
gameOver = False
while not gameOver:
for num, x in enumerate(wordToLetters):
print(lives)
print(gaps)
eingabe = input("Buchstaben eingeben: ")
if lives < 0:
gameOver = True
print("spiel verloren...\n")
if gaps == wordToLetters:
print("Spiel gewonnen!\n")
print("Das Wort war: " + word)
gameOver = True
if eingabe in wordToLetters:
if eingabe in gaps:
lives -= 1
print("Buchstabe schon geraten!")
else:
gaps[num] = eingabe
print("Buchstabe vorhanden!\n")
else:
lives -= 1
print("Buchstabe nicht vorhanden! :(\n")
當其中一個條件為真時,您必須使用 elif 不測試其他條件:
import random
words = ["stone"]
word = words[random.randint(0, (len(words)) - 1)]
wordToLetters = list(word)
gaps = ["_"] * len(word)
lives = 6
gameOver = False
while not gameOver:
for num, x in enumerate(wordToLetters):
print(lives)
print(gaps)
eingabe = input("Buchstaben eingeben: ")
if lives < 0:
gameOver = True
print("spiel verloren...\n")
elif gaps == wordToLetters:
print("Spiel gewonnen!\n")
print("Das Wort war: " + word)
gameOver = True
elif eingabe in wordToLetters:
if eingabe in gaps:
lives -= 1
print("Buchstabe schon geraten!")
else:
gaps[num] = eingabe
print("Buchstabe vorhanden!\n")
else:
lives -= 1
print("Buchstabe nicht vorhanden! :(\n")
在這里,如果第一個“if”為真,那么我們不會檢查其他的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.