0

I'm trying print an elif inline of print().

I've seen some examples like this.

print (True if a else False)

but I really need this

for i in range (0,3):
    for j in range(0,4):
        print(f'Ecuation{i}')
        print(f'X if j==1 Y elif j==2 Z elif j==3' else RESULT)

I'm not sure if it's right or possible.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • `f'X if j==1 Y elif j==2 Z elif j==3'` is a string, not a statement. and only expressions can go into the a =b if x else c syntax, not statements. – TomServo Jan 21 '22 at 02:25
  • It is far better to define ```X```, ```Y``` and ```Z``` as a variable if a condition is met, and then printing said variable, this way you can use them elsewhere once allocated. – ChaddRobertson Jan 21 '22 at 02:25

3 Answers3

1

Put the info into a var like this:

show = """ if whatever : it """
print(show)
Lucas Vale
  • 19
  • 4
1

Possible using dicts and format string but probably not the best idea.

for i in range(0, 3):
    for j in range(0, 4):
        print(f"Execution {i}")
        print(f'{ {1: "X", 2: "Y", 3: "Z"}.get(j, "RESULT") }')

I would recommend Lucas' approach and do a variable outside.

lookups = {1: "X", 2: "Y", 3: "Z"}
for i in range(0, 3):
    for j in range(0, 4):
        print(f"Execution {i}")
        print(f'{ lookups.get(j, "RESULT") }')

Note a dictionaries .get(key, default) method will attempt to get the key. If the key is not in the dict then it will return the default value. Thus your else.

0

There are no inline elif statements in python. If you need a one-liner, you should use if...else statements:

for i in range(0, 3):
    for j in range(0, 4):
        print(f'Ecuation{i}')
        print(f'{"X" if j == 1 else ("Y" if j == 2 else ("Z" if j == 3 else "RESULT"))}')

Oleksii Tambovtsev
  • 2,666
  • 1
  • 3
  • 21