Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJASON PETERSEN
14,266 PointsIs >= 1 better than > 0?
In masterticket.py, the instructor chose to use:
while tickets_remaining >= 1:
while I chose to use:
while tickets_remaining > 0:
Is one better than the other? Why/why not?
Thanks!
1 Answer
Chris Freeman
Treehouse Moderator 68,454 PointsHey JASON PETERSEN, great question. I believe that both cases are optimized by the parser. Using timeit a performance analysis says theyβre are equivalent:
import timeit
def gt_zero():
for x in range(100):
if x > 0:
pass
def ge_one():
for x in range(100):
if x >= 1:
pass
print(timeit.timeit("gt_zero()", setup="from __main__ import gt_zero"))
print(timeit.timeit("gt_zero()", setup="from __main__ import gt_zero"))
print(timeit.timeit("ge_one()", setup="from __main__ import ge_one"))
print(timeit.timeit("ge_one()", setup="from __main__ import ge_one"))
# yields after 1_000_000 calls
# 28.21725383333296
# 28.741845541666407
# 28.536575374999757
# 28.496736958332804
In this StackOverflow post it demonstrates that gt and gte both execute in equal time since they both have a single opcode representation.
Disassembled Python says theyβll execute in the same number of instructions:
import dis
def gt0():
if x > 0:
pass
def ge1():
if x >= 1:
pass
print("dis gt0")
dis.dis(gt0)
print("dis ge1")
dis.dis(ge1)
yields
dis gt0
21 0 LOAD_GLOBAL 0 (x)
3 LOAD_CONST 1 (0)
6 COMPARE_OP 4 (>)
9 POP_JUMP_IF_FALSE 15
22 12 JUMP_FORWARD 0 (to 15)
>> 15 LOAD_CONST 0 (None)
18 RETURN_VALUE
dis ge1
25 0 LOAD_GLOBAL 0 (x)
3 LOAD_CONST 1 (1)
6 COMPARE_OP 5 (>=)
9 POP_JUMP_IF_FALSE 15
26 12 JUMP_FORWARD 0 (to 15)
>> 15 LOAD_CONST 0 (None)
18 RETURN_VALUE
So, there is no practical difference. Use the one that would give the better readability.
Post back if you need more help. Good luck!!!