【Lake的Python学习笔记】2020.02.09

【Lake的Python学习笔记】2020.02.09
0

嗨这里是Lake

这两天正好有空重新开始学习Python,跟着

4小时Python教程

一直在学。

目前有个小问题。想写一个猜谜游戏,想在Mike的版本上增添一些内容,主要有以下几点:

  1. 谜底是westlake(西湖)

  2. 用户最多猜测三次

  3. 答对一半:输入lake或者west会提示半对

  4. 答反方向:输入lakewest会提示方向错误

  5. 其他输入:提示错误

代码如下


#Use while loop to create guessing game
secret_word = "westlake"
running = True
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False

print("Hello, my Friend!")
while running:
    if guess_count < guess_limit and not out_of_guesses:
        guess = input("Enter Your Guess: ")
        guess_count += 1
        if guess == secret_word:
           print("Congratulation!")
           running = False
        elif guess == "west":
           print("Wow, you get part of it!")
        elif guess == "lake":
           print("Wow, you get part of it!")
        elif guess == "lakewest":
           print("It seems that you got a wrong direction!")
        else:
           print("Hm, there is happened to get some trouble with you.\nDo it again!")
    else:
        out_of_guesses = True

if out_of_guesses:
    print("YOU ARE OUT OF TIMES!")
else:
    print("YOU DID NOT BAD!")
print("Game Over!")

上述代码的问题在于,

超出猜测上限时,代码停止运行,并不会弹出写好的“YOU ARE OUT OF TIMES!”和“GAME OVER!”

想请教各位有哪些修改的地方。谢谢各位!

1赞

因为如果超出猜测上限还没猜对,你也没有设置running为False,所以不会跳出while循环

2赞

改成这样就成了,谢谢!

# Use while loop to create guessing game
secret_word = "westlake"
running = True
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False

print("Hello, my Friend!")
while running:
    if guess_count < guess_limit and not out_of_guesses:
        guess = input("Enter Your Guess: ")
        guess_count += 1
        if guess == secret_word:
           print("Congratulation!")
           running = False
        elif guess == "west":
           print("Wow, you get part of it!")
        elif guess == "lake":
           print("Wow, you get part of it!")
        elif guess == "lakewest":
           print("It seems that you got a wrong direction!")
        else:
           print("Hm, there is happened to get some trouble with you.\nDo it again!")
    else:
        out_of_guesses = True
        running = False

if out_of_guesses and not running:
    print("YOU ARE OUT OF TIMES!")
else:
    print("YOU DID NOT BAD!")
print("Game Over!")

注:加了两句
“running = False”
以及
“if out_of_guesses and not running:"
就可以了!