Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- >>> while False:
- ... break
- ... else:
- ... print(1)
- ...
- 1
- >>> while False:
- ... break
- ... else:
- ... print("asdf")
- ...
- asdf
- # So I know the "1" is coming from the else block, and not some return value
- >>> while True:
- ... break
- ... else:
- ... print(1)
- ...
- >>> for i in range(0):
- ... break
- ... else:
- ... print(1)
- ...
- 1
- >>> for i in range(1):
- ... break
- ... else:
- ... print(1)
- ...
- >>> for i in range(100):
- ... break
- ... else:
- ... print(1)
- ...
- # Seems useless so far
- >>> i = 100
- >>> while i: # Test while 100 -> 0 (first i is true)
- ... i -= 1
- ... else:
- ... print(1)
- ...
- 1
- >>> while i: # test while 0 (first i is false)
- ... pass
- ... else:
- ... print(1)
- ...
- 1
- >>> while i < 100: # test while 0 -> 99 (first i < 100 is true)
- ... i += 1
- ... else:
- ... print(1)
- ...
- 1
- >>> while 1: # (always true)
- ... break
- ... else:
- ... print(1)
- ...
- # So with while, it always executes else blocks, unless you're specifically breaking out of an infinite loop?
- >>> i = 0
- >>> while i < 100:
- ... i+=1 # let the loop complete
- ... else:
- ... print(1)
- ...
- 1
- >>> i = 0
- >>> while i < 100:
- ... break # kill the loop while condition is still true
- ... else:
- ... print(1)
- ...
- >>> for i in range(100):
- ... pass # let it run
- ... else:
- ... print(1)
- ...
- 1
- >>> for i in range(100):
- ... break # kill it while true
- ... else:
- ... print(1)
- ...
- # Now it makes sense. When it gets to the else statement, it checks the loop's condition one last time, and decides, based on that, whether to run the else block.
- # I can't really see a use for this. In fact, when trying to come up with something, I found that an if..else did MORE than the single else block was able to.
- >>> i = 0
- >>> while i < 100:
- ... i += 1
- ... else:
- ... print("completed successfully")
- ...
- completed successfully
- >>> i = 0
- >>> while i < 100:
- ... break
- ... else: # uh oh
- # Aside from the use of an else block to say "success" being logically questionable, this only allows to debug a success/failure assuming you are willing to print just before every break. This is fine if you want to be specific, so that you can single out an error among many, but if the only thing you need to know is that it failed, and you want to do that with a single print line, this method cannot provide the means, whereas a simple if..else...
- if not i < 100:
- print("success")
- else:
- print("failure")
- # ...can.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement