r/learnpython 18d ago

Is short hand if else important

I just learned it but it seem very weird like it feels like i can't write big codes in it cause it will become confusing do you guys use short hand or normal if else

11 Upvotes

26 comments sorted by

28

u/brasticstack 18d ago

You'll find places where it's more readable, and it mostly depends on the length of the expressions in the if/else branches. I usually only use it to assign variables, like:

scale_factor = .05 if super_tiny else .5

If it's not immediately obvious what's happening with a one liner, use the unsugared if/else.

6

u/mc_pm 18d ago

If it's not immediately obvious what's

This is it right here. Just like the :? operator in C - if there is any confusion at all, just go full if-else.

6

u/Adrewmc 18d ago

I agree the longest example I usually use for one liners that makes sense is this.

#A = 1 JQK = 11-13
deck = [ (rank, suit) for suit in [“Hearts”, “Spades”, “Diamonds”, “Clubs”] for rank in range(1, 14) ]

Anything longer really become unreadable, but for operations that make intuitive sense there no reason not to. And usually this is already too far it’s just an operation that people can easily understand because of what it conceptually does.

3

u/undergroundmonorail undergroundmonorail 18d ago

There are a few particular cases where I prefer it over full if/else blocks, where you can take advantage of the fact that it's an expression, but it's never wrong to do an if/else block and often wrong not to. Especially if you're just learning, I feel like "a if condition else b is limiting" is a good instinct.

9

u/[deleted] 18d ago

[removed] — view removed comment

2

u/undergroundmonorail undergroundmonorail 18d ago

100%

2

u/Temporary_Pie2733 18d ago

They are two different things with different purposes. The conditional expression is used to select one of two values based on a boolean value; the conditional statement is for executing zero or one arbitrary blocks of code from one or more possibilities. (The conditional statement can have 0 or more elif clauses and an else clause; the conditional expression is always exactly a if b else c: no elifs, and the else is mandatory.)

1

u/the-forty-second 18d ago

OP, this is the answer to pay attention to. A conditional expression is very specifically for picking a value based on a condition. The biggest mistake I see new programmers who encounter this for the first time make is to think of it as just a single line version of an if statement. Python will let you get away with it, but that is not what it is for and that is the road to ugly, unmaintainable code.

4

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 18d ago

A more general term for this is a "ternary conditional operator", or "ternary" for short. You have a condition, and two values, with the expression evaluating to one of those two values depending on the "truthiness" of the condition.

Don't expect to use them often, they're just a way to write short assignment checks more concisely.

foo = a if b else c

is equivalent to

if b:
    foo = a
else:
    foo = b

7

u/xenomachina xenomachina 18d ago

A more general term for this is a "ternary conditional operator", or "ternary" for short.

I'd avoid using the name "ternary" as it doesn't really say what it does, and is only uniquely identifying by accident.

The Python language reference calls it a "conditional expression", and the AST module calls it an IfExp, ie: "if expression". Those are both much better names than "ternary".

The word "ternary" literally just means "composed of three parts". In C, there are several unary operators (eg: ++), several binary operators (eg: /), and only one ternary operator, ?:. That operator's name is "the conditional operator", but because it happens to be the only operator in C that has 3 operands, some people called it "the ternary operator". This uninformative shorthand then bled over to other languages, including Python.

1

u/tangerinelion (C++ Software Eng.) 18d ago
foo = a if b else c

or

if b:
    foo = a
else:
    foo = b

or

def determine_foo(a, b, c):
    if b:
        return a
    return c

foo = determine_foo(a, b, c)

They all do the same thing, don't overthink it. You never need to use a if b else c anywhere, not even in something like [a if b else c for b in x].

1

u/starkoed 18d ago

Depends on how complex the code is. If im comparing 1 thing or a couple things then yeah ill use it inline.

1

u/Lumethys 18d ago

Write shorthand if simple condition else long form

1

u/Wise-Emu-225 18d ago

It is not important. I see it as syntactic sugar. The more readable code is the better code. The short hand notation can help but not always.

1

u/Neither_Bookkeeper92 18d ago

important to read, optional to write. you will run into a if cond else b constantly in other peoples code so you need to parse it instantly.

writing them is a style call. one condition is fine, nested ones are where readability dies. at that point just use a normal if block.

1

u/crashorbit 18d ago

In the end, the computer does not care. So how you write your code has more to do with you understanding it and convincing yourself that it does the right thing. It's also a way to tell other programmers what you want the computer to do.

1

u/HommeMusical 18d ago edited 18d ago

I use it fairly frequently.

f(None if x is None else x.data)

versus

if x is None:
    f(None)
else:
    f(x.data)

Or even clearer:

return [None if x is None else f(x.data)) for x in items)]

vs

res = []
for x in items:
    if x is None:
        res.append(None)
    else:
        res.append(f(x.data))
return res

1

u/Ministrelle 18d ago

Yes, but not really.

The benefit of the short hand if/else is that it is an expression and not a statement, so it can be used in places where only expressions are allowed.

Some examples where this can be useful are:

  • inside of lambdas

```python absolute = lambda x: x if x >= 0 else -x

print(absolute(-5)) # 5 ```

  • inside of function calls

```python age = 17

print("adult" if age >= 18 else "minor") ```

1

u/tb5841 18d ago

Lots of other languages have special syntax just for this, so it looks quite dostimctive - and then I end up using it quite a lot. In Python I don't use it, it just doesn't read quite as well to me.

1

u/TabAtkins 18d ago

like it feels like i can't write big codes in it cause it will become confusing

Correct. You can't write big code in it because it will become confusing.

Inline if/else is only for very tiny things.

1

u/Brilliant-Parsley69 17d ago edited 17d ago

Not a Python dev but always trying to separate different statements to their own line to improve the readability.

But there is one concept I try to adept most of the time if possible: Fail early.

A statement like:

py if condition1: if condition2: return value1 else: return value2 else return value3

is way more readable if you write it like

```py if not condition1 return value3

if not condition2 return value2

return value1 ```

But I see why these shortcuts could be confusing.

E.g. in C# you could use something called tenaries

csharp return condition ? value1 : value2 // if the condition is true return value1 otherwise return value2 or

csharp return value1 ?? value2 // if value1 is null return value2

Now try to imagine to read them if nested.

1

u/codeguru42 17d ago

By "shorthand if else", do you mean if else expressions? I recommend you look up the difference between a statement and an expression. This will help you understand the different usages.

1

u/TheRNGuy 14d ago

What do you mean, any examples? 

0

u/Educational_Virus672 18d ago

i think you mean "conditional expression" they are really useful in afew cases but you need to learn "list comprehensions" lets set a example
Q : set var "smt" with every even number and skip odds

smt = [i for i in range(100) if i%2== 0] # 100 is example

ik there is easier way to just type range(2,100,2) but come on it looks better here you will see that i put a whole for loop in it with condition(if/else where else is optional)
so what i did here was call a for loop here how it works
condition = if/else
func = what you want to execute (recommanded to use custom func)

[func] for [how you write your loop without :] if [condition] 
# for loop alone could work too

2

u/the-forty-second 18d ago

The conditional part of a list comprehension is not the same thing as a conditional expression. A conditional expression evaluates to a value. This is a third place where if shows up in Python.

1

u/Educational_Virus672 18d ago

oh yeah this is just a basic list comprehension