Python列表名称导致语法错误

时间:2017-11-17 14:05:18

标签: python list syntax-error

在第二个函数中,我在listExpenseNames列表中不断收到语法错误。我尝试将变量的名称更改为ExpenseNamesList,但是我得到了同样的错误。对于这两个变量名称,我也测试了0作为索引,但这也没有区别。任何帮助,将不胜感激。此外,请不要尝试纠正我的代码中可能存在的任何其他错误,我想通过自己犯错来学习。 (这可能看起来很矛盾,因为我刚刚发布了要求修复的内容,但这只是因为我感到难过而且它阻止我继续前进。)

def inputExpenseNames():
    listExpenseNames =[]
    loopExpenseNames = y
    while loopExpenseNames == y:
        listExpenseNames.append = input('Please enter the expense name.')
        loopExpenseNames=input('Would you like to enter another expense? If so, please enter \'y\'')
    print(listExpenseNames)

def inputExpenseAmounts():
    listExpenseAmounts =[]
    loopExpenseAmounts = 0
    while loopExpenseAmounts <= len(inputExpenseNames) :
        listExpenseAmounts.append = input('How much was spent on' listExpenseNames[int(loopExpenseAmounts)]'?')
        loopExpenseAmounts += 1
    print(listExpenseAmounts)

3 个答案:

答案 0 :(得分:3)

此代码有几个问题:

  1. listExpenseNames将不会在inputExpenseAmounts中定义。 See Here获得解释
  2. l.append = ...会更改append属性的值,但实际上并未附加任何内容。要附加某些内容,请l.append(...)
  3. 正如其他人所指出的,使用+来连接字符串:'spent on' + listExpenseNames[int(loopExpenseAmounts)] + '?'
  4. `

答案 1 :(得分:2)

我假设您要打印存储在listExpenseNames [int(loopExpenseAmounts)]中的字符串作为输入显示文本。您需要将字符串与+到一个字符串连接起来,而不仅仅是将它们列在彼此之后:

listExpenseAmounts.append = input('How much was spent on' + listExpenseNames[int(loopExpenseAmounts)] + '?')

答案 2 :(得分:1)

您正尝试在以下行连接字符串,但事实并非如此。请尝试使用以下代码。

listExpenseAmounts.append(input('How much was spent on'+ listExpenseNames[int(loopExpenseAmounts)]'?'))