如何修复Python中的循环或函数相关问题?

问题描述 投票:0回答:1

我首先是一个初学者。我刚刚写了这段简单的代码,但有一个问题。每当您猜错一次数字并尝试停止播放时,它就不会响应您并继续您写的任何内容。如果您愿意,可以尝试代码并看看我在说什么。

import random

def main() :
    while True :
        if True :
            try :
                numbers = int(input("Choose a positive number : "))
                mine = random.randint(0, numbers)
            except ValueError :
                print ("Write correctly please.")
                continue

        print ("I've chosen a number between 0 and " + str(numbers) + ".")
        guess = int(input("Take a guess : "))

        if guess == mine :
            print ("Nice guess !")
            choice = input ("Play agian (y/n) ? ")

            if choice == "y" :
                main()

            if choice == "n" :
                break
        else :
            print ("Sorry, wrong guess.")
            print ("I choose " + str(mine) + ".")
            choice2 = input ("Try agian (y/n) ? ")
            
            if choice2 == "y" :
                main()

            if choice2 == "n" :
                break

main ()

我尝试使用 continue 和 pass 以及其他一些工作人员,但我不太了解相关的函数和循环,所以我希望任何人也能给我一些视频或课程来训练这些代码。

python function if-statement continue
1个回答
0
投票

您遇到的问题是您的代码在其内部调用相同的函数。这会造成一种情况,当您想要完成游戏时,您的游戏无法正确停止。为了解决这个问题,您可以通过使用循环来控制游戏的方式组织代码。这样,当您想停止玩游戏时,您可以说“我完成了”,游戏就会停止。

循环可能非常棘手,所以我修改了你的代码:

import random

def main():
    while True:
        try:
            numbers = int(input("Choose a positive number: "))
            mine = random.randint(0, numbers)
        except ValueError:
            print("Write correctly please.")
            continue
        
        print("I've chosen a number between 0 and " + str(numbers) + ".")
        
        while True:
            guess = int(input("Take a guess: "))
            
            if guess == mine:
                print("Nice guess!")
                choice = input("Play again (y/n)? ")
                if choice == "y":
                    break  # Exit the inner loop and start a new game
                else:
                    return  # Exit the main function to end the game
                
            else:
                print("Sorry, wrong guess.")
                print("I chose " + str(mine) + ".")
                choice2 = input("Try again (y/n)? ")
                if choice2 == "n":
                    return  # Exit the main function to end the game

if __name__ == "__main__":
    main()
© www.soinside.com 2019 - 2024. All rights reserved.