【问题标题】:Guessing game does not stop猜谜游戏不会停止
【发布时间】:2021-12-29 21:02:47
【问题描述】:
import random
level = input("Easy gets 10 attempt Hard getse 5 attempt choose a level --> ").lower()
number = random.choice(range(101))
attempt = 0
if level == "easy":
    attempt = 10
else:
    attempt = 5

def check_number(guess,num):
    if guess == num:
        return "Correct You Won :)"
        win = True

    elif guess > num:
        return "Too high :("
    elif guess < num:
        return "Too low :("
win = False
while attempt > 0 and win == False:
    guess = int(input("Guess the number "))
    print(check_number(guess,number))
    attempt -= 1
    print(f"You have {attempt} attempt left")

if win == True:
    print(f"GOOD JOB YOU HAVE {attempt} LEFT")
else:
    print("NEXT TİME :(")

当你猜数字时它不会停止,仍然要求新的猜测。 我找不到问题。我刚开始学习python。

【问题讨论】:

  • 你函数中的win是一个局部变量,没有连接到win全局变量。当然,这没关系,因为在您返回之前,您不会将 win 设置为 True。我会在下面发布一个更好的设计。
  • 不要使用globals,它们可能会导致更新变量时出错。

标签: python python-3.x


【解决方案1】:

这完全避免了使用全局变量:

import random
level = input("Easy gets 10 attempt Hard getse 5 attempt choose a level --> ").lower()
number = random.choice(range(101))
attempt = 0
if level == "easy":
    attempt = 10
else:
    attempt = 5

def check_number(guess,num):
    if guess > num:
        return False, "Too high :("
    elif guess < num:
        return False, "Too low :("
    return True, "Correct You Won :)"

win = False
while attempt > 0 and not win:
    guess = int(input("Guess the number "))
    win, msg = check_number(guess,number)
    print(msg)
    if not win:
        attempt -= 1
        print(f"You have {attempt} attempt left")

if win:
    print(f"GOOD JOB YOU HAVE {attempt} LEFT")
else:
    print("NEXT TİME :(")

【讨论】:

    【解决方案2】:

    你的代码有两个问题:

    1. win 返回后分配,不会运行
    2. win 在函数内部,就像您在函数内部定义了一个新变量 win 并且无法从外部访问它

    所以你可能想这样做:

    import random
    level = input("Easy gets 10 attempt Hard getse 5 attempt choose a level --> ").lower()
    number = random.choice(range(101))
    attempt = 0
    if level == "easy":
        attempt = 10
    else:
        attempt = 5
    
    def check_number(guess,num):
        if guess == num:
            return 0
        elif guess > num:
            return 1
        elif guess < num:
            return -1
    win = False
    while attempt > 0 and win == False:
        guess = int(input("Guess the number "))
        state = check_number(guess,number)
        if(state==0):
            win = True
            print("won")
        elif(state==1):
            print("is high")
        elif(state==-1):
            print("is low")
        attempt -= 1
        print(f"You have {attempt} attempt left")
    
    if win == True:
        print(f"GOOD JOB YOU HAVE {attempt} LEFT")
    else:
        print("NEXT TİME :(")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-15
      • 2020-11-22
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多