Project: Refactor the "Guess the number" game
Lesson 21 of 26 · Basic Python
In this project take the earlier code of the "Guess the number" game and split it into functions and at least two files:
game.py— contains the main flow of the game (starting it, the loop).logic.py— contains functions such ascheck_guessandgenerate_number.
An example of the code structure
# logic.py
import random
def generate_number(low=1, high=100):
return random.randint(low, high)
def check_guess(secret, guess):
if guess < secret:
return "higher"
elif guess > secret:
return "lower"
else:
return "correct"
# game.py
from logic import generate_number, check_guess
def main():
secret = generate_number()
print("Guess a number between 1 and 100!")
while True:
try:
g = int(input("Enter your number: "))
except ValueError:
print("Enter a whole number!")
continue
status = check_guess(secret, g)
if status == "higher":
print("The number is higher!")
elif status == "lower":
print("The number is lower!")
else:
print("You guessed it!")
break
if __name__ == "__main__":
main()
Exercises and challenges
- Add a counter of attempts and show the total number of steps at the end.
- Add an option for the player to change the range (for example 1–50 / 1–200).
- Save the results to a file (for example the player's name and the number of attempts).
