List comprehensions are great but there is another great syntax available in Python for dealing with
if-elseconditions on a single line. Imagine if you would like to assign a result of
Excellentif the score is above or equal to 50, and
Averageif 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
resultswill be either
Averagedepending on the value of
Note that this is different from filtering in a list comprehension. For filtering, the if condition appears after the
forloop. Here the
elsestatements appear in the part of the generated element.
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
FAILif the student failed, and
PASS, if they passed the exam.
Try to implement the whole program in a single line.
30 80 90 34 66 100
FAIL PASS PASS FAIL PASS PASS
Time limit: 1 seconds
Memory limit: 512 MB
Output limit: 1 MB