我正在编写一个Python练习,计算3个学校科目的平均值。计算平均值后,我希望程序找到小于70的主题并打印“你可以改进'x'主题”。
我知道我可以这样做并用特定的if statements
if geometry < 70:
print("Your geometry could be better")
elif algebra < 70:
print("Your algebra could be better")
etc etc
但我想知道是否有更简洁的答案,比如
if geometry or algebra or physics < 70:
print("Your", variable, "could be better")
我还处于Python的初学者级别,是否有更简单的方法来编写if语句并避免使用那些长列表?
答案 0 :(得分:3)
>>> subjects = {
... 'geometry': 80,
... 'algebra': 85,
... 'physics': 68
... }
... for subject, score in subjects.items():
... if score < 70:
... print('Your {} could be better'.format(subject))
...
Your physics could be better
答案 1 :(得分:1)
scores = {'geometry': 80, 'algebra': 85, 'physics': 68, 'chemistry': 50, 'biology': 69 }
to_improve = []
for subject, score in scores.items():
if score < 70:
to_improve.append(subject)
print ('Your', ' and '.join(to_improve), 'could be better')