""" number_guess.py A tiny guess-the-number game. How it works: 1. The computer picks a secret number between 1 and 100. 2. You type a guess. 3. It tells you 'Higher!' or 'Lower!' until you get it. Run: $ python3 number_guess.py — Mohamed Hassan, age 9 1/2 """ # --------------------------------------------------------------------------- # Hi Mohamed! This is a Python program. Python reads top to bottom, like a # recipe. The grey text above (between the three quotes """ """) is a # "docstring" — a note that describes the file. Lines starting with a # are # comments: little notes for humans that Python completely ignores. # --------------------------------------------------------------------------- # "import" brings in extra tools. "random" lets us pick random numbers — that's # how the computer chooses a secret number you can't predict. import random # "def" DEFINES a function: a named bundle of steps we can run whenever we want. # This one is called play(). Defining it doesn't run it yet — see the bottom. def play(): # Pick a secret number from 1 to 100 (randint includes BOTH ends). target = random.randint(1, 100) # A "counter" that starts at 0 and goes up by 1 each guess. guesses = 0 print("I'm thinking of a number between 1 and 100.") # "while True:" is a loop that repeats forever — until we choose to stop it # (with "return" or "break"). We keep asking until you guess right. while True: # input() shows the message and waits for you to type and press Enter. # Whatever you type comes back as TEXT (a "string"), not a number. raw = input("Your guess: ") # .isdigit() is True only if the text is all digits (like "42"). # "not" flips it, so this means "if it ISN'T a plain number...". if not raw.isdigit(): print("Numbers only, please.") # "continue" jumps back to the top of the loop to ask again. continue # int(...) turns the text "42" into the actual number 42 so we can compare. guess = int(raw) guesses += 1 # same as: guesses = guesses + 1 # Compare the guess to the secret number and give a hint. if guess < target: print("Higher!") elif guess > target: # "elif" = "else if": only checked if the first was False print("Lower!") else: # The f"..." is an "f-string": Python swaps {guesses} for its value. print(f"You got it in {guesses} guesses!") # "return" ends the function — you won, so we stop the loop & the game. return # This line means: "only run play() if this file was started directly (not # imported by another file)." It's a very common Python pattern — get used to # seeing it! "__name__" is a built-in variable Python sets for you. if __name__ == "__main__": play()