【问题标题】:How do I successfully close the While loop in this code? It seems to not recognize my break condition?如何成功关闭此代码中的 While 循环?它似乎不承认我的休息条件?
【发布时间】:2021-04-15 08:25:09
【问题描述】:

问题提示如下:

创建交互式学生记录系统。
提示用户输入学生姓名。
然后提示用户输入数字等级
重复此操作,直到用户输入“完成”来代替名称。
然后打印每个学生和他们的平均成绩

我想出了以下代码(我是初学者,如果这很明显很抱歉)

# I am creating a dictionary so I can store multiple values that are associated with one name
lst = []
dict = {}

while True:
  try:
    name = str(input("Please enter student's name."))
    grade = int(input("Please enter grade student recieved."))
    
    if (name not in list(dict.keys()) and name != "done"):
      lsst = []
      lsst.append(grade)
      dict[name] = lsst
      print(lsst)
      continue

      
    
    elif name in list(dict.keys()):
      lsst.append(grade)
      print(lsst)
      continue
    
    elif name == "done":
      break
  
  except ValueError:
    print("Try Again")
    pass

for i in range(list(dict.keys())):
  print(f"{name}: {grade}")

我在输入姓名输入“完成”后尝试打印平均值,但它只是继续进行下一个输入查询。为什么会这样,我该如何解决?

【问题讨论】:

  • break 只是打破了try-块,然后程序继续while-循环。将 except-block 直接移动到 try-block 下方,然后将 if-elif-elif 块缩进,使其超出 try-except 块。顺便说一句,python缩进标准是每级4个空格,见PEP8 - Indentation
  • 您提供的代码存在一些问题。最明显的问题是它没有正确运行(这一行抛出错误for i in range(list(dict.keys())):)。请修复您的代码并确保它正确运行并且行为与您描述的完全一致。

标签: python


【解决方案1】:

代码中有很多错误,但我会在更正的版本中分解它们。

names_and_grades = {} # I renamed this variable because there is a built in type called dict in Python.

while True: # Using while True is usually discouraged but in this case, it's hard to avoid that.
    try:
        name = input("Please enter student's name.") # No need to convert to string as it takes the input as a string by default.

        if name == "done": # After you prompted for a name immediately check whether the user entered done. This way, you can break right after that.
            break

        grade = int(input("Please enter grade student recieved."))

        if name not in names_and_grades.keys():
            names_and_grades[name] = [grade] # We don't actually need a separate list as the entry in the dictionary will be the list itself (that's why it's put between brackets).
        elif name in names_and_grades.keys():
            names_and_grades[name].append(grade) # Once the list was declared, you can simply append it.

        print(names_and_grades[name]) # No need to repeat this twice in the if-else statements, you can just write it after them. And a very important thing, there is no need to use continue, since you are using if-elfe. When you are using if-else, only one of the blocks will be used, the first block where the condition evaluates as true.

    except ValueError:
        print("Try Again")

for k in names_and_grades.keys():
    print(f"{k}: {names_and_grades[k]}") # This is the simplest way to iterate through a dictionary (if you want to format the entries), by iterating through the keys of the dictionary and with the help of the keys, calling the appropriate values.

我希望这会有所帮助,如果有不清楚的地方请告诉我。

【讨论】:

  • 1) str(input(... 有效,但 input() 已经返回一个字符串 - 无需转换为字符串。 2) 无需再次检查name != "done,在上面几行的条件下有一个break
  • 这太棒了!非常感谢您解决我的错误并帮助我使我的代码更清晰。这真是太有帮助了!
  • 谢谢@ack,我不小心把它留在了原始代码中,现在我编辑了我的答案。
【解决方案2】:

@I8ACooky - 有一些逻辑和语法错误,所以我建议你运行它,看看你是否能得到一些想法来解决你自己的问题:


from collections import defaultdict


grades = defaultdict(list)   # in case for multiple scores for a student
print('Welcome to the simple Scoring program. ')

while True:
    
    try:
        
        name = input("Please enter student's name.")
        score = int(input("Please enter grade student recieved: "))

        if name == 'done' and score == 0:
            break
        
        grades[name].append(score)

    except ValueError:
        print('Try Again....?')
      
print(dict(grades))

#------------------------
# average scores leave as an exercise...

输出:

Welcome to the simple Scoring program. 
Please enter student's name.Adam
Please enter grade student recieved: 100
Please enter student's name.Bob
Please enter grade student recieved: 60
Please enter student's name.Cindy
Please enter grade student recieved: 80
Please enter student's name.Adam
Please enter grade student recieved: 80
Please enter student's name.Bob
Please enter grade student recieved: 100
Please enter student's name.Cindy
Please enter grade student recieved: 90
Please enter student's name.done
Please enter grade student recieved: 0
{'Adam': [100, 80], 'Bob': [60, 100], 'Cindy': [80, 90]}

【讨论】:

  • done 不应被假定为有效的学生姓名。
  • 它只是遵循原始 PO 作为信号 done 的一种方式。它当然可以而且应该改进——供作者努力。对吗?
  • OP 在输入 done 后试图立即中断 - 仔细看看。为done 评分是没有意义的。
  • 好笔记 - PO 应该做笔记并在以后的工作中修复。我们只是为他提供一些“想法”让他继续努力......(不是最终的解决方案~)
猜你喜欢
  • 2019-07-15
  • 2022-01-23
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 2019-03-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多