Can not assign value to a variable

Question:

def simulate_tournament(teams):
    """Simulate a tournament. Return name of winning team."""
    # If only one team left
    if len(teams) == 1:
        # Assigns the only element of type dictionary of the list to a variable
        winner = teams[0]
        # Gets value of the firs key(name a team)
        i = list(winner.values())[0]
        # Returns name of the team type <'class str'>
        return i

    else:
        # Calls function to simulate a game between each pair of teams and returns list of winners
        winners = simulate_round(teams)
        # Using recursion to simulate all games in order to get the base case
        simulate_tournament(winners)

Example of a dictionary element

team = {
    "name": "Germany"
    "rating": 1000
}

But when I try no assign a return value to a variable in my main function and try to print it:

winner = simulate_tournament(teams)
print(winner)

It prints None

Asked By: HeaveN

||

Answers:

You need to return your recursive call. Without return, you’re just calling the function and discarding the value returned.

def simulate_tournament(teams):
    """Simulate a tournament. Return name of winning team."""
    # If only one team left
    if len(teams) == 1:
        # Assigns the only element of type dictionary of the list to a variable
        winner = teams[0]
        # Gets value of the firs key(name a team)
        i = list(winner.values())[0]
        # Returns name of the team type <'class str'>
        return i

    else:
        # Calls function to simulate a game between each pair of teams and returns list of winners
        winners = simulate_round(teams)
        # Using recursion to simulate all games in order to get the base case
        return simulate_tournament(winners)
Answered By: Freddy Mcloughlan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.