Higher or Lower Game in Python

Python game 14 of 20

Beginner⏱ 15 min📄 39 lines of Python★ 3 challenges▶ Plays in your browser

In Higher or Lower you see a number from 1 to 100 and guess whether the next one will be higher or lower. Every right answer adds to your streak; one wrong answer ends the run. It's a short game, which makes it perfect for practising loops, comparisons and keeping a best score.

Tip: think about the middle. If you see 82, "lower" is a much safer bet.

Play Higher or Lower

higher_or_lower_game.py · real Python in your browser
Press ▶ Play to start the game. When it asks you something, type your answer and press Enter.
View and edit the code (39 lines)

How to play

  • You see a number from 1 to 100.
  • Type h if you think the next number is higher, l if lower.
  • Keep your streak going as long as you can. The same number again counts as a free pass.

The complete Higher or Lower code

Here is the whole program (39 lines). It only uses Python's standard library, so it runs anywhere Python 3 is installed.

import random


def judge(current, nxt, guess):
    if nxt == current:
        return "same"
    if (nxt > current) == (guess == "h"):
        return "right"
    return "wrong"


print("HIGHER OR LOWER  -  build the longest streak")
best = 0
playing = True
while playing:
    streak = 0
    current = random.randint(1, 100)
    while True:
        print(f"\nThe number is {current}.")
        guess = input("Higher or lower? (h/l): ").strip().lower()
        if guess not in ("h", "l"):
            print("Type h or l.")
            continue
        nxt = random.randint(1, 100)
        result = judge(current, nxt, guess)
        print(f"The next number is {nxt}.")
        if result == "wrong":
            print(f"Wrong! Your streak was {streak}.")
            break
        if result == "right":
            streak += 1
            print(f"Right! Streak: {streak}")
        else:
            print("Same number - free pass!")
        current = nxt
    best = max(best, streak)
    print(f"Best streak: {best}")
    playing = input("Play again? (y/n): ").strip().lower() == "y"
print("Thanks for playing!")

How the Higher or Lower game works, step by step

01Judge one guess

A neat trick: nxt > current is True or False, and so is guess == "h". If they match, the guess was right.

if (nxt > current) == (guess == "h"):
    return "right"

02A loop inside a loop

The outer loop is one play session (ask "play again?" at the end). The inner loop is one run of guesses that stops with break on the first wrong answer.

while playing:
    streak = 0
    while True:
        ...
        if result == "wrong":
            break

03Keep the best score

max(best, streak) returns the bigger of the two, so best only ever goes up.

best = max(best, streak)

04Ask to play again

Comparing the answer with "y" gives True or False directly, which becomes the outer loop's condition.

playing = input("Play again? (y/n): ").strip().lower() == "y"

What you'll learn

  • Comparing booleans
  • Nested while loops and break
  • max() for high scores
  • Functions that return a word
  • Play-again loops

Python concepts in this game:

Higher or Lower coding challenges

Write the key parts of the game yourself. Press Run to try your code and Check to test it. Each challenge you pass earns a star (saved in this browser).

1/3

Judge a guess

Write judge(current, nxt, guess) returning "same" if the numbers are equal, "right" if the guess ("h" or "l") was correct, otherwise "wrong".

challenge 1 · edit, Run, then Check
Hint

Handle equal numbers first, then the two ways to be right.

Show a solution
def judge(current, nxt, guess):
    if nxt == current:
        return "same"
    if nxt > current and guess == "h":
        return "right"
    if nxt < current and guess == "l":
        return "right"
    return "wrong"

print(judge(40, 75, "h"))
2/3

Longest streak

Write longest(results): results is a list of True/False answers. Return the longest run of True values in a row.

challenge 2 · edit, Run, then Check
Hint

Add 1 to run on True and reset it to 0 on False. Keep best = max(best, run).

Show a solution
def longest(results):
    best = 0
    run = 0
    for r in results:
        if r:
            run += 1
            best = max(best, run)
        else:
            run = 0
    return best

print(longest([True, True, False, True, True, True, False]))
3/3

The smart choice

Write advice(n) for a number from 1 to 100: return "h" if more numbers are above n than below it, otherwise "l".

challenge 3 · edit, Run, then Check
Hint

From 1 to 100 there are 100 - n numbers above n and n - 1 below.

Show a solution
def advice(n):
    above = 100 - n
    below = n - 1
    if above > below:
        return "h"
    return "l"

print(advice(20), advice(80))

Make it your own

Once your challenges pass, try one of these upgrades:

  • Use a bigger range or a shrinking range as the streak grows.
  • Save the best streak to a file.
  • Add an 'auto' mode where the computer plays using advice() and see its average streak.
  • Show the chance of being right before each guess.

Frequently asked questions

How do you make a Higher or Lower game in Python?

Pick a random number, ask the player h or l, pick the next random number and compare. Count correct answers in a streak variable and stop the run at the first wrong guess.

What's the best strategy for Higher or Lower?

Choose higher when the number is 50 or less and lower when it's 51 or more. That always picks the side with more possible numbers.

Can the next number be the same?

Yes, with randint it can repeat. This game treats that as a free pass so you don't lose your streak.

More games like this