Loop and a Half

Python doesn't have anything like a do-while loop. So this is a technique you can do in any language called "loop and a half". It's pretty cool. I use them a lot.

coinflip.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from __future__ import print_function
import random
input = raw_input

def main():
    streak = 0
    while True:
        gotHeads = random.random() < 0.5
        if gotHeads:
            coin = "HEADS"
        else:
            coin = "TAILS"

        print("You flip a coin and it is... " + coin)

        if gotHeads:
            streak += 1
            print("\tThat's {} in a row...".format(streak))
            again = input("\tWould you like to flip again (y/n)? ")
        else:
            print("\tYou lose everything!")
            print("\tShould've quit while you were aHEAD....")
            streak = 0
            again = "n"

        if again != "y":
            break

    print("Final score: {}".format(streak))


if __name__ == "__main__":
    main()

What You Should See

You flip a coin and it is... HEADS
    That's 1 in a row...
    Would you like to flip again (y/n)? y
You flip a coin and it is... HEADS
    That's 2 in a row...
    Would you like to flip again (y/n)? n
Final score: 2

Basically you make an infinite loop on purpose. Then, at the bottom of the loop, you test whatever condition you want. If it's true, you break out of the loop.

Study Drills

  1. No study drills?!? Gasp!



©2017 Graham Mitchell