List comprehensions are great but there is another great syntax available in Python for dealing with if-else conditions on a single line. Imagine if you would like to assign a result of Excellent if the score is above or equal to 50, and Average if it’s below 50. This can be done in a single line:
if score >= 50:
result = 'Excellent'
else:
result = 'Average'
result = 'Excellent' if score >= 50 else 'Average'
The single-line conditions are especially useful in list comprehensions. They can be used to generate list elements conditionally - have one value under one condition and another under a different condition. The same scoring program can be done in a list comprehension as well:
scores = [...]
results = ['Excellent' if s >= 50 else 'Average' for s in scores]
print(results)
Each element in the results will be either Excellent or Average depending on the value of s.
Note that this is different from filtering in a list comprehension. For filtering, the if condition appears after the for loop. Here the if and else statements appear in the part of the generated element.
Challenge
Given a single line of exam scores, you are asked to tell if the student has failed or passed the exam. All the scores are separated by a space. Students fail the exam if they score less than 40, and pass otherwise.
The input contains a single line of scores separated by a space.
The program should print a single line where for each student it should print FAIL if the student failed, and PASS, if they passed the exam.
Try to implement the whole program in a single line.