0

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.

  • 2
    The challenge you are in is called code golf, be sure to check out the page with tips for golfing in python: https://codegolf.stackexchange.com/questions/54/tips-for-golfing-in-python – sdcbr Jun 16 '20 at 10:57
  • Wrap "Uneven" with single quotes 'Uneven' and remove the nested print `print(f"{ name if n % 2 == 0 else 'Uneven!' }")` – lazos Jun 16 '20 at 10:58
  • @lazos Sorry I gave a bad example using the print method. My question is more referring to another case where I wanted to run the `continue` method if the condition was false. – Max Phillips Jun 16 '20 at 11:02
  • 1
    continue isn't a method. – juanpa.arrivillaga Jun 16 '20 at 11:31
  • you're not iterating over anything - how would continue even be used here? – acushner Jun 16 '20 at 17:08

1 Answers1

0

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])
Ronald
  • 2,930
  • 2
  • 7
  • 18