from random import randint
from sys import exit
def higher_lower(guesses=[],mynum=[]):
if not guesses: #if no previous guesses are in the list
user_guess = int(input("Please guess my number.\n It is from 0 to 9: "))
mystery_num = randint(0,9)
turn = compare_nums(user_guess,mystery_num) #call compare_nums
#only do the following if guess is wrong
guesses.append(user_guess)
mynum.append(mystery_num)
higher_lower(guesses,mynum) #recursion
else:
user_guess = int(input("Try again.\n It is from 0 to 9: "))
if user_guess in guesses:
print("You already guessed that number.")
higher_lower(guesses,mynum) #recursion
else:
turn = compare_nums(user_guess,mynum[0]) #call compare_nums
#only do the following if guess is wrong
guesses.append(user_guess)
higher_lower(guesses,mynum) #recursion
def compare_nums(your_guess,my_num):
if your_guess == my_num:
for x in "YOU GOT IT!":
print(x)
print("GOOD JOB!")
exit()
else:
return
higher_lower() #must call the function or nothing will happen
A simple game based on a recursive function higher_lower() that keeps track of user guesses and of a random integer that generates the first time the function is called. The game ends when the user eventually guesses the correct number. A feature could be added to count and display how many guesses the user made before getting the answer right.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.