fb pixel

Introduction to Python

  • Profound Academy

    • Status
      • 1
        Input and Output
      • 2
        Variables and Integer Arithmetic
      • 3
        Conditional Operators
      • 4
        Advanced Conditions - Nesting
      • 5
        Types and Variables
      • 6
        Strings
      • 7
        Lists
      • 8
        For Loops
      • 9
        While Loops
      • 10
        continue, break, while...else
      • 11
        String and List methods
      • 12
        Nested Loops
      • 13
        List Comprehension
      • 14
        Tuples and Sets
      • 15
        dict
      • 16
        Functions
      • 17
        Functions 2
      • 18
        Lambda and higher-order functions
      • 19
        Files

  • Single-line conditions

    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.
    Input
    Output
    30 80 90 34 66 100
    FAIL PASS PASS FAIL PASS PASS
     
    To check your solution you need to sign in
    Sign in to continue