首页 > 解决方案 > Implement a bottle spin

问题描述

I want to create a spin the bottle game because I'm bored and what to test my coding skills (they're not that great ngl). I got this far and wanted to add a feature where the program asks how many people are playing and then it will change the output to that. For example, it asks how many players and if you respond with '8', it will then ask for 8 names and pick from those said names.

I have tried doing:

players = input('How many people are playing?')

if player == '2':
 name1 = input(Who is player 1?')
 name2 = input('Who is player 2?')

elif player == '3'
 name1 = input(Who is player 1?')
 name2 = input('Who is player 2?')
 name3 = input ('Who is player 3?')

and so forth

import random
import time
print ('Hello and welcome to spin the bottle generator')
name1 = input('Who is player 1?')
name2 = input ('Who is player 2?')
name3 = input('Who is player 3?')
name4 = input ('Who is player 4?')


names = [name1, name2, name3, name4]
print (names)
print ('Spinning')
time.sleep(1)
print (random.choice(names))

I submitted this code and it asked for the number of players and when I inputted '4' as a test it didnt go any further :/

标签: python

解决方案


Any time you are tempted to use an undetermined number of variables like name1, name2, it's a big clue that you should not be using individual variables, but should be storing the values in a list like names then use names[0] etc. to access individual items.

In your case you can get the number of players and append to a list in each loop iteration. In the end you'll have a list of player names:

num_players = int(input('How many people are playing?'))
players = []

for i in range(num_players):
    p = input(f'Who is player {i+1}?')
    players.append(p)

print(players) 

推荐阅读