我不明白我的代码出了什么问题。有人能帮我理解为什么它不起作用吗?

2024-04-19 06:18:43 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我正在制作一个程序,你捕获一个口袋妖怪并设置它们的等级,当你查询它们时,它会返回它们的等级,但当我查询它时,它不会返回所选的口袋妖怪,只返回字典中的最后一个口袋妖怪

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)

Tags: nameininputiflinenotcommandparts
1条回答
网友
1楼 · 发布于 2024-04-19 06:18:43
qparts = line.split()
tempname = parts[1]

您创建了qparts,但从不使用它。相反,您将引用parts,它是在else块中创建的,包含在上一个非查询命令中命名的pokemon的信息

试着从qparts改为tempname

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 .

相关问题 更多 >