Last active
June 11, 2018 20:02
-
-
Save rkie/1a770eccaa76aa090b760d93716d07b7 to your computer and use it in GitHub Desktop.
A simple program for a guessing game I wrote with my children to begin teaching them to write code. See my blog post about the experience at http://failedtofunction.com/coding-with-children/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from random import randint | |
import re | |
def ask_for_a_number_with(question): | |
number = input(question) | |
while (re.match(r'^[0-9]+$', number) == None): | |
print('That is not a valid number. Try again.') | |
number = input(question) | |
return int(number) | |
def get_yes_or_no(prompt): | |
response = input(prompt) | |
while (re.match(r'^[ynYN]$', response) == None): | |
print('Enter "y" to play again or "n" to quit.') | |
response = input(prompt) | |
return response | |
def guess_is_not_correct(answer, guess): | |
return answer != guess | |
def guess_is_too_high(answer, guess): | |
return guess > answer | |
def ask_to_play_again(): | |
response = get_yes_or_no('Do you want to play again (y/n): ') | |
return 'y' == response or 'Y' == response | |
def play_game(answer): | |
guess = ask_for_a_number_with('Enter your first guess: ') | |
guesses = 1 | |
while ( guess_is_not_correct(answer, guess) ): | |
if guess_is_too_high(answer, guess): | |
print('Wrong! Guess lower.') | |
else: | |
print('Wrong! Guess higher.') | |
guess = ask_for_a_number_with('Have another go: ') | |
guesses = guesses + 1 | |
print('You got it!', guesses, 'guesses') | |
playagain = True | |
while (playagain): | |
game_range = ask_for_a_number_with('Enter the highest number to choose from: ') | |
answer = randint(1, game_range) | |
play_game(answer) | |
playagain = ask_to_play_again() | |
print('Goodbye') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment