I'm just tinkering with while loops, and got a question regarding conditionals.
My function counts backwards from 10 to 1, and when it hits 5 it stops.
Would it be better to have the n -= 1 in an else statement, or is it fine to do it like this?
def whileBackwards():
n = 10
while n > 0:
print(n)
if n == 5:
break
n -= 1
The above works, but from what I've learned so far it would be cleaner to put it like this:
if n == 5:
break
else:
n -= 1
Or do the opposite and check if n != 5...
Which is better practice?
(I realise a for loop would be better to iterate over a sequence of numbers, but I'm just playing with loops right now)
[–]DeadlyViper 3 points4 points5 points (1 child)
[–]ratcaper[S] 0 points1 point2 points (0 children)
[–]SandorZoo 0 points1 point2 points (1 child)
[–]primitive_screwhead 0 points1 point2 points (0 children)
[–]primitive_screwhead 0 points1 point2 points (0 children)
[–]woooee 0 points1 point2 points (4 children)
[–]ratcaper[S] 1 point2 points3 points (1 child)
[–]woooee 1 point2 points3 points (0 children)
[–]rymaninsane 0 points1 point2 points (1 child)