lucky 的学习笔记(用 Python 写一个猜词游戏)

lucky 的学习笔记(用 Python 写一个猜词游戏)
0

欢迎大家指正 :blush:

secret_word = "Lucky"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False

while guess != secret_word and not(out_of_guesses):
    if guess_count < guess_limit:
       guess = input("Enter guess: ")
       guess_count += 1
    else: # guess_count >= 3
       out_of_guesses = True

if out_of_guesses: # 3次以内没对
    print("You lose!")
else:
    print("You win!")

猜了 3 次还是没猜对的时候,guess_count = 3,返回执行 while 里面的条件,这时候 not(out_of_guesses) 都是 True,继续执行 else,not(out_of_guesses) 是 False,while 循环停止。然后开始执行 if,这时候 out_of_guesses 是 True,打印 You lose。

如果不到 3 次就猜对了,那么 out_of_guesses 是 False,就执行 else,打印 You win。

3赞

我复制你的代码运行了一下,没问题 :clap::clap:

试试对比一下你的代码和以下代码的代码大小和执行性能:

guess_limit = 3
secret_word = "Lucky"
guess = ""
guess_count = 0
while guess_count < guess_limit:
    guess = input("Enter guess: ")
    if guess == secret_word:
        print("You win!")
        break
    guess_count += 1
if guess != secret_word:
    print("You lose!")

其实我是照着书上敲的代码,那个 out_of_guesses 都把我绕晕了。
你的代码理解起来逻辑更清晰。