具有嵌套for循环和累加器模式的函数

时间:2018-02-11 22:44:51

标签: python function loops for-loop

我上课的任务是创建一个函数,根据每轮贡献的玩家数量计算总累积奖金。每当一轮过期时,玩家被淘汰并且当仅剩下一个玩家时游戏结束。

我不确定为什么我的代码没有产生所需的输出。

def poker_jackpot(num_players,avg_bet):
    """fuction to calculate jackpot"""
    total_bet=0 #Accumulator used to total the jackpot from avg_bet
    for i in range(avg_bet):
        total_bet=total_bet+avg_bet
    return total_bet #Returning the total for use in the final output

    for i in range(num_players,1,-1): #Range function that counts down the players as each round ends
        print("Total jackpot after" , str(i), "rounds:"+"$",str(total_bet))

poker_jackpot(10,5)

2 个答案:

答案 0 :(得分:0)

您应该将return total_bet放在功能的末尾。所以你的代码看起来像这样:

def poker_jackpot(num_players,avg_bet):
    """fuction to calculate jackpot"""
    total_bet=0 #Accumulator used to total the jackpot from avg_bet
    for i in range(avg_bet):
        total_bet += total_bet+avg_bet

    for i in range(num_players,1,-1): #Range function that counts down the players as each round ends
        print("Total jackpot after" , str(i), "rounds:"+"$",str(total_bet))
    return total_bet #Returning the total for use in the final output

poker_jackpot(10,5)

答案 1 :(得分:0)

我尝试使用一种截然不同的方法解决您的问题。这是脚本:

def poker_jackpot(num_players,avg_bet):
    """fuction to calculate jackpot"""
    total_bet=0 #Accumulator used to total the jackpot from avg_bet
    rounds = 1
    while num_players > 0:      
        total_bet += num_players * avg_bet 
        print("Total jackpot after {} rounds: {} $".format(rounds, str(total_bet)))
        num_players -= 1
        rounds += 1
    return total_bet #Returning the total for use in the final output


poker_jackpot(10,5)

我认为你会理解这个函数中的所有内容,除了可能是print("Total jackpot after {} rounds: {} $".format(rounds, str(total_bet)))模块,它基本上是写print("Total jackpot after" , str(i), "rounds:"+"$",str(total_bet))的更简洁的替代方法(PS:当你试图将多个变量插入到字符串我建议使用.format()