【问题标题】:Guessing Game - Looping Problem in Python猜谜游戏 - Python 中的循环问题
【发布时间】:2020-09-17 09:38:18
【问题描述】:

我必须制作一款游戏,根据玩家的猜测来奖励他们。用户猜一个数字,算法将其与随机生成的 2 位数字进行比较,并据此奖励玩家。

问题:玩家需要在游戏结束前玩此游戏 3 次。当我用 while 循环循环 3 次时,它只会通过询问用户的猜测来循环,并且不会打印或返回奖励消息。当我删除 while 循环并使用 for 循环时,它只运行一次并打印消息。

如何解决这个循环问题并运行这个程序三次?

import random

jackpot = 10000
award2 = 3000
award3 = 100
noaward = 0
play = 3
turns = 1

def lottery_game():
    for x in range(play):
        lottery = random.randrange(10,99)
        lot = list(map(int, str(lottery)))
    
        guess = int(input("Choose a 2 digit number: "))
        n_guess = list(map(int, str(guess)))
    
        if guess == lottery:
            return "You won: " + str(jackpot) + " Euros"
        elif n_guess[0] == lot[0] or n_guess[1] == lot[1]:
            return "You won: " + str(award2) + " Euros" 
        elif n_guess[0] == lot[1] or n_guess[1] == lot[0]:
            return "You won: " + str(award3) + " Euros"
        else: 
            return "I am sorry, you won: " + str(noaward) + " Euros" + " try again"

while i <= 3:
    lottery_game()
    i = i + 1

【问题讨论】:

    标签: python loops for-loop while-loop


    【解决方案1】:

    根据您的代码,您没有在 while 之前初始化您的 i 变量,您绝对应该这样做。但是对于你的用例,你不应该使用while,你应该使用for这样的循环:

    for i in range(0,3):

    这将使循环中的代码运行 3 次。

    【讨论】:

    • 所以我应该改变函数中的for循环还是改变它下面的while函数
    【解决方案2】:

    你需要

    • return 替换为print 声明:
    • while i &lt;= 3 替换为for i in range(3)

    这里是更新的代码:

    import random
    
    jackpot = 10000
    award2 = 3000
    award3 = 100
    noaward = 0
    
    
    def lottery_game():
        lottery = random.randrange(10, 99)
        lot = list(map(int, str(lottery)))
    
        guess = int(input('Choose a 2 digit number: '))
        n_guess = list(map(int, str(guess)))
    
        if guess == lottery:
            print(f'You won: {jackpot} Euros')
        elif n_guess[0] == lot[0] or n_guess[1] == lot[1]:
            print(f'You won: {award2} Euros')
        elif n_guess[0] == lot[1] or n_guess[1] == lot[0]:
            print(f'You won: {award3} Euros')
        else:
            print(f'I am sorry, you won: {noaward} Euros. Try again')
    
    
    for i in range(3):
        lottery_game()
    

    样本输出:

    Choose a 2 digit number: I am sorry, you won: 0 Euros. Try again
    Choose a 2 digit number: You won: 100 Euros
    Choose a 2 digit number: You won: 10000 Euros
    

    【讨论】:

      【解决方案3】:

      你还没有初始化i

      在while语句前添加i=1

      【讨论】:

      • 是的,我知道我应该使用“turns”而不是“i”
      猜你喜欢
      • 1970-01-01
      • 2021-11-02
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多