[英]I just made a simple guessing game, but my 'remaining guesses' var isn't working
我做了一個條件,如果只剩下一個猜測,它顯示“剩余一個猜測”,否則,它顯示“剩余x個猜測”。但無論是否剩余1個猜測,決定條件的變量始終為3。
順便說一句,對不起英語。
import random
words = ("elephant", "giraffe", "dog", "cat", "turtle", "bird")
s_word = random.choice(words)
guess = ""
g_limit = 3
g_count = 0
out_of_g = False
g_remain = g_limit - g_count
while guess != s_word and not out_of_g:
if g_count < g_limit:
if g_remain < 2:
print(str(g_remain) + " guesses remaining")
else:
print(str(g_remain) + " guess remaining")
guess = input("enter a word: ")
g_count += 1
else:
out_of_g = True
if out_of_g:
print("you lose")
else:
print("you won")
打印輸出將始終顯示剩余的 3 個猜測,因為您沒有更新g_remain
。 在檢查計數是否小於限制后,您應該這樣做:
#...
while guess != s_word and not out_of_g:
if g_count < g_limit:
g_remain = g_limit - g_count # <------ UPDATE HERE
if g_remain < 2:
print(str(g_remain) + " guesses remaining")
else:
print(str(g_remain) + " guess remaining")
guess = input("enter a word: ")
g_count += 1
else:
out_of_g = True
#...
或者,如果您進一步考慮,您可能能夠擺脫eather g_count
或g_remain
。
import random
words = ("elephant", "giraffe", "dog", "cat", "turtle", "bird")
s_word = random.choice(words)
guess = ""
g_limit = 3
g_count = 0
out_of_g = False
g_remain = g_limit - g_count
while guess != s_word and not out_of_g:
if g_count < g_limit:
if g_remain > 1:
print(str(g_remain) + " guesses remaining")
g_remain -= 1
else:
print(str(g_remain) + " guess remaining")
g_remain -= 1
guess = input("enter a word: ")
g_count += 1
else:
out_of_g = True
if out_of_g:
print("you lose")
else:
print("you won")
這是解決方案。 也更改 if 語句,以獲得正確版本的“猜測”和“猜測”。
your code has too many unnecessary vars, we should fix it first
import random
words = ("elephant", "giraffe", "dog", "cat", "turtle", "bird")
s_word = random.choice(words)
guess = ""
g_count = 4
for guess in range(3):
print(str(g_count - 1) + " guesses remaining")
guess = input("enter a word: ")
if guess == s_word:
print('You Won')
break
else:
continue
g_remain 設置一次。 您必須在每個階段更新值。 這是解決方案:
while guess != s_word and not out_of_g:
g_remain = g_limit - g_count
嘗試這個:
您只需要更改一行 g_remian 變量應該在 while 循環之后聲明,然后只有它才能正常工作。
這是代碼。
import random
words = ("elephant", "giraffe", "dog", "cat", "turtle", "bird")
s_word = random.choice(words)
guess = ""
g_limit = 3
g_count = 0
out_of_g = False
while guess != s_word and not out_of_g:
g_remain = g_limit - g_count
if g_count < g_limit:
if g_remain < 2:
print(str(g_remain) + " guesses remaining")
else:
print(str(g_remain) + " guess remaining")
guess = input("enter a word: ")
g_count += 1
else:
out_of_g = True
if out_of_g:
print("you lose")
else:
print("you won")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.