首页 > 解决方案 > 不明白我的代码有什么问题。谁能帮我理解为什么它不起作用?

问题描述

因此,我正在制作一个程序,您可以在其中捕获口袋妖怪并设置它们的级别,当您查询它们时,它会返回它们的级别,但是当我查询时,它不会返回所选的口袋妖怪,而只是字典中的最后一个口袋妖怪。

pk = {}

line = input('Command: ')
while line:
  tempq = 2
  if "Query" in line:
    tempq = 1
    qparts = line.split()
    tempname = parts[1]
    if tempname in pk:
      print(tempname, "is level", pk.get(tempname),".")
    elif tempname not in pk:
      print("You have not captured" + tempname + "yet.")
  else:
    parts = line.split()
    name = parts[1]
    lvl = parts[tempq]
    pk[name] = int(lvl)
  line = input('Command: ')

print(pk)

标签: pythonpython-3.x

解决方案


qparts = line.split()
tempname = parts[1]

您创建qparts,但从不使用它。相反,您指的parts是在您的else块中创建的,并包含在最后一个非查询命令中命名的任何 pokemon 的信息。

尝试tempnameqparts代替。

pk = {}

line = input('Command: ')
while line:
  tempq = 2
  if "Query" in line:
    tempq = 1
    qparts = line.split()
    tempname = qparts[1]
    if tempname in pk:
      print(tempname, "is level", pk.get(tempname),".")
    elif tempname not in pk:
      print("You have not captured" + tempname + "yet.")
  else:
    parts = line.split()
    name = parts[1]
    lvl = parts[tempq]
    pk[name] = int(lvl)
  line = input('Command: ')

print(pk)

结果:

Command: catch pikachu 50
Command: catch bulbasaur 10
Command: Query pikachu
pikachu is level 50 .

推荐阅读