Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Challenge Solution

tomtrnka
tomtrnka
9,780 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
231,271 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()

Hi Steven Parker, I have a question regarding your code.

So if the user input is equal to 'yes' then the returned value to the function will be true, hence, making the while loop = while True. and if 'no' then the returned value will be False and the while loop never loops. did I understand that correctly?

Steven Parker
Steven Parker
231,271 Points

You're exactly right about what would happen the first time. And if the loop does run, it calls the function again each time to see if it should run again or not.

Awesome! thank you!