Python Challenge Solution

tomtrnka
tomtrnka
8,692 Points

Is using a method as condition for while loop, a good practice??

Hi, I wanted to ask you if its a good practice to type methods as a condition for the while loop. Or if thats not something we should be doing. (instead hold it in some variable and store the return value from method in the variable). I'm talking about the "askToAddPlayer()"

playerNames = []
def askToAddPlayer():
    return input("Would you like to add a player to the list? (yes/no)  ").lower()

def addNewPlayer():
    name = input("Enter the name of the player to add to the team:  ")
    playerNames.append(name)

while askToAddPlayer() == "yes":
    addNewPlayer()

player_number = 1
for name in playerNames:
    print("Player {}: {}".format(player_number, name))
    player_number += 1

keeper = int(input("Choose goalkeeper from the roster(1-{}): ".format(len(playerNames))))
print("The goalkeaper is: {}".format(playerNames[keeper-1]))

1 Answer

Steven Parker
Steven Parker
195,376 Points

If you don't need to do anything else with the result of a method, there's no need to assign it to a variable and you can just test it directly. In this case you could even go a step further and have the method return the result of testing the value instead of the input itself:

def askToAddPlayer():
    return input("Would you like to add a player to the list? (yes/no)  ").lower() == "yes"

while askToAddPlayer():
    addNewPlayer()