0

I'm writing a Python exercise that calculates an average from 3 of your school subjects. After the average is calculated I want the program to find subjects that have less than 70 and print "You could improve in 'x' subject".

I know I could do it this way and write it out with specific if statements

if geometry < 70:
      print("Your geometry could be better")
elif algebra < 70: 
      print("Your algebra could be better")
etc etc

But I wondered if there was a more succinct answer, like

if geometry or algebra or physics < 70:
      print("Your", variable, "could be better")

I'm still at a beginners level of Python, is there an easier way to write out if statements and avoid those long lists?

1
  • 4
    Use a dictionary instead of separate variables, then that will be easy. Commented Mar 3, 2018 at 1:57

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

1 Comment

this is a rather trivial question (& answer) but answer is perfectly coded at least
1

Store them in a dictionary:

grades = {'algebra': 57, 'geometry': 82, 'physics': 68}
for subject in grades:
    if grades[subject] < 70:
        print('Your {} could be better'.format(subject))

which can be condensed into a list comprehension using dict.items() in a single line!

[print("Your {} could be better".format(subject)) for subject, grade in grades.items() if grade < 70]

or for multiple subjects in the same sentence:

grades = {'algebra': 57, 'geometry': 82, 'physics': 68}
subjects = ' and '.join([subject for subject, grade in grades.items() if grade < 70]))
print('Your {} could be better'.format(subjects))

3 Comments

yeah, but too late.
Thanks! I should have also asked, if two subjects are less than 70, can i change it to 'geometry and physics need improving'?
Yes, use another to_improve list, as shown in my answer.
0
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')

1 Comment

Please add explanations to your code. Code only is not an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.