首页 > 解决方案 > 一旦条件返回 True 就重新启动函数

问题描述

在学习 Python 课程的同时,尝试在 Codecademy 上编写一个非常简单的 Game of Chance 游戏。我有一段时间做得很好(我认为),代码返回了我的预期,但现在感觉我被卡住了,疯狂地谷歌搜索并没有真正帮助我,我不只是想看看实际的解决方案,因为它的乐趣在哪里,所以就到这里了。

我的想法是,游戏最初应该要求玩家输入他们的猜测和出价,然后在 game() 中运行代码并打印结果。然后将其锁定在一个 while 循环中,以检查用户是否想继续玩,如果答案为“是”以再次重新启动 game() 函数。这就是我卡住的地方,因为在“是”检查返回 True 之后,我无法弄清楚在第 26 行中放入什么。

我想我的实际问题的 TL/DR 版本是你如何(不放弃实际代码)在 while 循环中调用一个函数?想知道我是否只是在这里走错了方向,需要再次查看 while 循环。

谢谢!

# Import stuff
import random
# Generate random number from 1 - 9
num = random.randint(1, 10)
# The actual game, asking user for input and returning the outcome
def game():
    guess = int(input("Guess the number: "))
    bid = int(input("Bet on the game: "))
    money = 100
    
    if guess == num:
        money = (money + bid)
        print("You Won")
        print("You now have: " + str(money) +" money")
        return money
    else:
        money = (money - bid)
        print("You lost, you will die poor")
        print("You now have: " + str(money) +" money")
        return money
# Run game() while there's still money left in the pot
def structure():
    while money > 0:
        another_go = input("Would you like to play again? Yes or No: ")
        if another_go == "Yes":
            game() # This is where I'm stuck 
        elif another_go == "No":
            print("Oh well, suit yourself")
            break
        else:
            print("Pick Yes or No")
            print(another_go)

game()

标签: pythonwhile-loop

解决方案


欢迎来到 SO。您的代码总体上很好。这是稍微更改代码以使其工作的一种方法:

... Most of the code ... 

money  = 10

def structure():
    another_go = "Yes" # initialize to 'Yes', so we'll 
                       # always have a first game. 
    while money > 0:
        
        if another_go == "Yes":
            game() # This is where I'm stuck 
        elif another_go == "No":
            print("Oh well, suit yourself")
            break
        else:
            print("Pick Yes or No")
            print(another_go)
        # move 'another go' to the end of the loop
        another_go = input("Would you like to play again? Yes or No: ")            

structure() # call this function to start 

推荐阅读