【问题标题】:Unable to add item to dictionary [closed]无法将项目添加到字典 [关闭]
【发布时间】:2021-10-20 19:16:04
【问题描述】:

我正在制作一个小型计算器程序,因为我很无聊,我遇到了一个问题,我无法添加名为 Test 和值 awnser 的项目,我不确定为什么,请帮助

question = []
awnslog = {
  'None': 0
}

while True:
  Inp = int(input('>> '))
  Inp2 = str(input('>> '))
  Inp3 = int(input('>> '))
  question.insert(0, Inp3)
  question.insert(0, Inp2)
  question.insert(0, Inp)
  if '*' or 'x' in question:
    print('*')
    print(question[0]*question[2])
    awnser = question[0]*[question[2]
    awnslog['Test'] = awnser # <--- Issue
    print(awnslog) 

【问题讨论】:

  • if '*' in question or 'x' in question:
  • 您缺少右括号:awnser = question[0]*[question[2]
  • awnser = question[0]*[question[2] 中看起来像一些语法错误
  • if '*' or 'x' in question: 是错误的,条件是始终为真。 Python 不是英语,in question 不会分布在逻辑连接上。您需要使用if '*' in question or 'x' in question: ...
  • 我不明白你为什么使用.insert。为什么不只是question = [Inp, Inp2, Inp3]

标签: python python-3.x dictionary


【解决方案1】:

失败的原因大概是这里的SyntaxError

awnser = question[0]*[question[2]

它应该是awnser = question[0]*question[2](注意question[2]之前的[。另外insert是一个昂贵的操作,因为它将list中的所有元素移动了一个位置。而且你在@中什么也不做987654328@,因为每次使用Test 添加新条目时,旧条目都会被覆盖,所以我不确定拥有awsnlog 的目的是什么。这是其中一种方法;

awnslog = {
  'None': 0
}

while True:
    question = []
    Inp = question.append(int(input('First Number: ')))
    Inp2 = question.append(str(input('Operation: ')))
    Inp3 = question.append(int(input('Second Nummber: ')))
    if question[1] in ['*', 'x', 'X']:
        print(question[0]*question[2])
        awnser = question[0]*question[2]
        awnslog['Test'] = awnser
        print(awnslog)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 2019-08-12
    相关资源
    最近更新 更多