如何使用相同的变量名称将项目附加到列表?

时间:2014-08-13 22:39:20

标签: python list input append

如果我的代码写得不好,请提前抱歉。我试图创建一个允许您向列表中添加数字的程序,然后让用户在同一个列表中添加更多数字。这就是我所拥有的:

inputgameoption="y"

while inputgameoption=="y":

    ###this is where the user inputs the first number
    creepscore=eval(input("Finished a game? Type your creep score first then press enter.     Next, enter the duration of your game and press enter "))

    ###this is where the user inputs the second number
    gameduration=eval(input("Game duration should be rounded to the nearest minute, [ex. 24:25 becomes 24] "))

    cs=[]

    times=[]

    cs.append(creepscore)

    times.append(gameduration)

    inputgameoption=input("Enter another game?")

第一次工作正常,但是如果你想输入更多数字(输入另一个游戏输入),它会用你的第二个输入替换你的第一个输入,并且列表中只剩下一个数字。谢谢,我是一个蟒蛇新手。

3 个答案:

答案 0 :(得分:3)

使用while循环。另外,只需将其输入转换为int,而不是使用eval

# initialize the arrays outside the loop
cs = []
times = []

# loop for input until the user doesn't enter 'y'
inputgameoption = 'y'
while(inputgameoption == 'y'):
    creepscore = int(input("Finished a game? Type your creep score first then press enter.     Next, enter the duration of your game and press enter "))
    gameduration = int(input("Game duration should be rounded to the nearest minute, [ex. 24:25 becomes 24] "))

    # add their current inputs
    cs.append(creepscore)
    times.append(gameduration)

    # prompt to continue
    inputgameoption=input("Enter another game?")

print 'creepscores : ', cs
print 'times : ', times

答案 1 :(得分:2)

您的行cs=[]times=[]正在替换那些空列表中的内容。在循环之前移动那些。

答案 2 :(得分:2)

代码的格式很不明确,但是你只需要在while循环之前定义列表,如下所示:

inputgameoption="y"

cs=[]
times=[]

while inputgameoption=="y":

    ###this is where the user inputs the first number
    creepscore=int(input("Finished a game? Type your creep score first then press enter.     Next, enter the duration of your game and press enter "))

    ###this is where the user inputs the second number
    gameduration=int(input("Game duration should be rounded to the nearest minute, [ex. 24:25 becomes 24] "))



    cs.append(creepscore)
    times.append(gameduration)

    inputgameoption=input("Enter another game?")
相关问题