That’s Numberwang!

GCC was *packed* last week and it was great! We covered a lot of ground with many key elements of coding that we will find ourselves using time and time again.

The key things we discusses were:

  • Repeating sections of code – the while loop
  • Decisions – if, elif, else & the while loop logic
  • Converting data types – str() & int()
  • The ‘main game loop’ structure

I will run through these again in our next session, but in the meantime here is  Nick’s code in its entirety for you to look at. Can you follow the flow of the code and pick out each element from the list above?

import random

answer = random.randint(1, 100)

print('I have selected a number between 1 and 100.')

lives = 3
while lives > 0:
      guess = int(input('Your guess? '))
      if answer == guess:
            lives = lives - 1
            print('Incorrect, try again')
            if guess < answer:
                  print('Too low!')
                  print('Too high!')

if lives == 0:
      print('Sorry, you have no more guesses.')

For comparison, here is a near identical game created with slightly different underlying logic. Can you follow the flow of this code? Can you highlight the differences and the similarities between the two approaches to the same problem? It is interesting to see that there can be many different code solutions to the same problem.

import random

tries = 6
attempts = 0
secret = random.randint(1, 99)
guess = 0

print("Access DENIED: This system is locked with a code between 1-99")

while guess != secret and attempts < tries:
    remaining = tries - attempts
    print("You have " + str(remaining) + " remaining attempts") 
    guess = int(input("Enter Code Now..."))
    if guess < secret:
        print("Code FAIL: Too low. Don't you know any bigger numbers?")
    if guess > secret:
        print("Code: FAIL: Too high. Calm yourself & try a smaller number")
    attempts = attempts + 1

if guess==secret:
    print("Access ENABLED: Please proceed to Nuclear Missile launch control. Have fun...")
    print("Access LOCKED: Black helicopters have been dispatched to your location.")
    print("Before you are terminated, you may as well know that the code was " + str(secret))

Next session we will look at competing against our first computer opponent!


Comments powered by Disqus