How to repeat input line of code until condition is met - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: How to repeat input line of code until condition is met (/thread-18357.html) |
How to repeat input line of code until condition is met - Reta - May-14-2019 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 playerListI 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. RE: How to repeat input line of code until condition is met - michalmonday - May-14-2019 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())
RE: How to repeat input line of code until condition is met - nilamo - May-14-2019 >>> 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'] |