Python Forum

Full Version: How to repeat input line of code until condition is met
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So right now, I'm trying to loop a line that requires input until a condition is met, but I can't seem to do so.

Essentially, what I want is:

Code asks user how many players are playing: Var (playerAmt)
From there, set a while loop that while 'playerAmt'!= actualPlayers
Ask user for names of each player in relation to playerAmt: Var (playerNames) - e.g. if 3 players are playing, code will repeat input code until it's been asked 3 times, then break out of loop
Which will then added to a list using playerList.append(playerNames)

def playerNames():
    userNun=int(input("Number of players?"))
    while userAmount != userNun:
        userNames=input("Please input your names")
        playerList.append(userNames)
        random.shuffle(playerList)
        return playerList
I know this code isn't working, as I can't seem to find a way to arrange it in a way as stated above, any help will be appreciated, thanks!
Edit: The "userAmount" variable was asked before this function runs, which is obviously incorrect, but I have no idea how to remedy this.
import random

def playerNames():
    playerList = []
    userNun=int(input("Number of players?\n> "))
    while len(playerList) != userNun:
        userNames=input("Please input name of player number {}/{}\n> ".format(len(playerList)+1, userNun))
        playerList.append(userNames)
    random.shuffle(playerList)
    return playerList

print(playerNames())
Output:
Number of players? > 2 Please input name of player number 1/2 > Michal Please input name of player number 2/2 > Monday ['Monday', 'Michal'] >>>
>>> def input_with_cond(display, condition):
...   while True:
...     value = input(display)
...     yield value
...     if condition():
...       break
...
>>> num_players = int(input("How many? "))
How many? 3
>>> players = []
>>> for player in input_with_cond("Next player: ", lambda: len(players) >= num_players):
...   players.append(player)
...
Next player: joe
Next player: fred
Next player: moe
>>> players
['joe', 'fred', 'moe']