Hopping and Skipping

Here is a simple game: the user starts at position 1, and must advance to the last position. At each step he or she either "hops" (advances one step), or "skips" (advances two steps). One of the positions is "bad": if the user gets there, he or she has lost.

To make this work: we need to know

We will tell the user up-front where the bad position is, so this is just a game of skill (very little skill), not luck. We also ask the user to enter h or s to hop or skip. Here is the code:
current_position = 1
field_length = 10
bad_position = 5
print 'Position', bad_position, 'is bad, avoid it!'

while True:
    print 'You are at position', current_position
    action = raw_input('Next? h to hop 1, s to skip 2: ')
    if action == 'h':
        current_position += 1
    else:
        current_position += 2

    if current_position == bad_position:
        print 'You lost!'
        break
    elif current_position == field_length:
        print 'You won!'
        break
      
Let's make the game more interesting, by adding two variations: To pick a random number, we will import the random library. It has many functions, but will only use these: Here is our revised game:
import random

field_length = 10
current_position = 1
slip_probability = 0.3
bad_position = random.randrange(field_length - 1) + 1
print 'Position', bad_position, 'is bad, avoid it!'

while True:
    print 'You are at position', current_position
    action = raw_input('Next? h to hop 1, s to skip 2: ')
    if action == 'h':
        current_position += 1
    else:
        current_position += 2

    if random.random() < slip_probability:
        print 'You slipped!  Back to the beginning!'
        current_position = 1

    if current_position == bad_position:
        print 'You lost!'
        break
    elif current_position == field_length:
        print 'You won!'
        break
                         
Notice line 6: bad_position = random.randrange(field_length - 2) + 2. What's going on here? Well, I don't want the "bad" position to ever be 1 or 10 (otherwise you can't win the game), so: Notice also line 17: if random.random() < slip_probability: . What's going on here? Well, slip_probability is 0.3, and random.random() can return anywhere between 0.0 and 0.9999..., so the probability that it returns a number less than 0.3 is 30%, as desired.