【问题标题】:Making and storing different variables in python with user input使用用户输入在 python 中创建和存储不同的变量
【发布时间】:2016-04-11 12:00:54
【问题描述】:

我有一个问题,我必须输入一个数字,并根据该数字向用户询问 x 次问题并将信息存储在稍后将输出的变量中 EG:

询问用户他们需要多少 x

for i in range(x)
  what is the number {} player name ? .format(i)
  i += 1

打印出类似的东西:

names :
john - 1 
max - 2
etc - 3

【问题讨论】:

  • 你的第二段不是正确的英文,我无法理解。
  • 第二段?你的意思是打印出类似的东西?好的,我解释一下,我的意思是,在我得到输入并最终存储变量后,我将能够将它们打印出来

标签: python


【解决方案1】:

您的程序可能看起来像这样:-

lsNames = []
print "How many players do you have ?"
iPlayers = raw_input()

for i in range(int(iPlayers)):
    playerName = raw_input("Enter  {} player name".format(i + 1))
    lsNames.append(playerName)

print ",".join(lsNames)

【讨论】:

  • 有时间我会看看你的答案,我现在无法测试你给我的东西,但提前谢谢你:)
  • 不是问题@Taka
【解决方案2】:
answers = {} # an answers dictionary
for i in range(x): # note the trailing : needed for a loop
    question = "what is the number {} player name ?".format(i)
    name = input(question)
    answers[i] = name

注意,在 python 2 中,您需要 raw_input 而不是 input

稍后,类似-

for key in answers:
    print('player {} is {}'.format(key, answers[key])

【讨论】:

    猜你喜欢
    • 2020-11-04
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多