Search code examples
pythonpython-3.xternaryf-stringpep

Python Expression that returns a value if condition is met but otherwise continues a for loop


This is going to sound like a dumb and horrible idea and that's probably because it is. Is there a way in Python (preferably a one-liner) to create an expression that resolves to a value if a condition is met but if the condition is not met it will instead execute a statement (such as continue or a method call)?

An example use case below (although this code doesn't actually work):

def print_name_if_even(n):
    print(f"{ name if n % 2 == 0 else print("Uneven!") }")

I know this probably is a bad idea but I'm doing a challenge to cram a function definition in as few lines as possible so I want to avoid muli-line conditional statements.


Solution

  • You mean something like this?

    def f():
        # <your statement>
        return 'yourstatement'
    
    print ([f(), 'Even!'][False])
    

    Replace False by any condition that evaluates to True(=1) or False(=0). (This is fun). For example:

    def f():
        # <your statement>
        return 'yourstatement'
    n=2
    print ([f(), 'Even!'][n%2 == 0])