python - 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 :/
解决方案
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)
推荐阅读
- c++ - gcc 仪表 - 是否可以自动输出函数的参数?
- mysql - Mysql.data 实体在 Visual Studio 2019 中不起作用
- html - 如何更改 wiki Fossil (fossil-scm) 中单元格的背景颜色?
- uinavigationbar - 在 ios 13 中设置后退按钮箭头色调的正确方法是什么
- angular - 如何获取本地存储数据并设置为角度 7 中的默认重定向路由?
- javascript - 如何将api数据保存到本地存储中?
- python - 如何在 30 秒内获取多个用户输入并将其保存到列表中?
- java - Java:带有ANSI转义码的Json字符串到对象
- asp.net - 如何在 Application_Error 事件处理程序中呈现视图而不重定向用户?
- php - 如何使用 Slim 在一个响应中发送数据流和字符串