首页 > 解决方案 > 如何将 input() 集成到迭代循环中?

问题描述

我是 python 的初学者,想尝试一下我的第一个个人项目,这是一个学生科目的分数计算器。我想运行一个 for 循环,要求用户通过 for 循环中的 input() 输入每个科目的分数。但是,它只需要一个单一的字符串参数。

scores = {}
total = 0
years = int(input("How subjects have you completed? "))
for sub in range(0, years):
    scores = input("Score for subject?",x)
    total += int(scores)

任何帮助都会很棒,谢谢!

标签: python-3.x

解决方案


如果您想按科目跟踪分数并找到总分,那么...


subjects = dict( Math = 0, English = 0, Science = 0, History = 0 )

scores = dict()
total = 0
for sub in subjects.keys():
    score = input( f"Score for {sub}? >" )
    if score:
        total += int( score )
        scores[sub] = score

print( total )

for sub,tot in scores.items():
    if tot > 0:
        print( sub, tot )

推荐阅读