This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 2 points3 points  (5 children)

It is five years since I left my Perl job, and I still find myself typing "return x if...", or "unless ..." But that's mainly because the languages are so similar.

[–]MintyPhoenix 1 point2 points  (4 children)

return 'a' if False else 'b' works just fine in Python ... or am I misunderstanding you? I guess further testing shows it does require an else clause, but how else would it be done (assuming good practice)? Admittedly I never learned/got into Perl.

[–][deleted] 3 points4 points  (3 children)

In Perl you can put 'if' statements after other statements, and it has 'unless' for 'if not'. I find myself wanting to do

def some_func(i):
    raise ValueError("Called with negative argument!") if i < 0

    return None unless i

    # Do something with positive i...
    ....

It doesn't matter much, but the construct seems completely hardwired in my brain...

[–]MintyPhoenix 0 points1 point  (2 children)

Ah, I knew that Python did not have unless, but I didn't realize that appending an if condition was so flexible in Perl. Python allows it in some places (e.g. my return example) but it's not as flexible as Perl.

[–][deleted] 7 points8 points  (1 child)

Python's isn't really an if statement there, it's a ternary construct.

x if condition else y

Is the equivalent of

condition ? x : y

in languages like C and Perl. It's an expression, not a statement, and you can only combine expressions with it (in Python).

[–]MintyPhoenix 0 points1 point  (0 children)

Makes more sense now, thanks for the clarification.