Python Forum
better way to return a selected value
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
better way to return a selected value
#1
which is better or more Pythonic?

A:
...
if s1 < s2:
    return -1
if s1 > s2:
    return 1
return 0
B:
...
if s1 < s2:
    x = -1
elif s1 > s2:
    x = 1
else:
    x = 0
return x
or, which way would you do it?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
The second way is probably better because there is only one return statement. However I would implement it like
>>> def cmp(x, y):
...     return -1 if x < y else (0 if x == y else 1)
... 
Note that this won't work exactly like the old Python 2's cmp() function because the latter allowed comparison of objects having incompatible types.
Reply
#3
i read long ago that if...else was generally disliked and considered not very pythonic, though i like it (from my C background, i guess).
(Nov-20-2022, 11:33 AM)Gribouillis Wrote: Note that this won't work exactly like the old Python 2's cmp() function because the latter allowed comparison of objects having incompatible types
i'm mostly coding for only Python3, anymore.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020