How to run these games

Every game below is complete and uses only Python's standard library, so there is nothing to pip install. You have three ways to run one:

  1. In your browser: press the Run in the online compiler button under a game. It opens in the online Python compiler on this site, which runs real Python 3 in the page and asks for your input() answers in the console.
  2. On your phone: paste the code into the Coding Python app for Android and tap Run.
  3. On a computer: save it as a .py file and run python guess.py in a terminal (use python3 on macOS and Linux).

The games are ordered roughly from easiest to hardest. Every example run on this page was produced by actually running the code, so what you see is what the program prints.

#GameDifficultyLinesRuns in a browser / phone
1Number Guessing GameEasy16Yes
2Rock, Paper, ScissorsEasy24Yes
3HangmanEasy27Yes
4Higher or Lower Card GameEasy20Yes
5Math Quiz GameEasy18Yes
6Tic-Tac-Toe (Two Players)Medium37Yes
7Text Adventure GameMedium35Yes
8Blackjack (21)Medium37Yes
9Word ScrambleEasy18Yes
10Snake Game (Turtle Graphics)Medium73No — needs a window

1. Number Guessing Game

Difficulty: Easy · You practise: while loops, if/elif/else, random.randint, counting

The classic first game. The computer picks a number and tells you whether each guess is too high or too low.

import random

secret = random.randint(1, 100)
tries = 0
print("I'm thinking of a number between 1 and 100.")

while True:
    guess = int(input("Your guess: "))
    tries += 1
    if guess < secret:
        print("Too low!")
    elif guess > secret:
        print("Too high!")
    else:
        print(f"Got it in {tries} tries!")
        break

▶ Run Number Guessing Game in the online compiler

Example run (your numbers will differ — they are random):

I'm thinking of a number between 1 and 100.
Your guess: 50
Too high!
Your guess: 25
Too low!
Your guess: 37
Too low!
Your guess: 43
Too high!
Your guess: 40
Too low!
Your guess: 42
Got it in 6 tries!

Make it your own: Limit the player to seven guesses, reject input that is not a number with try/except ValueError, or let the player choose the range.

2. Rock, Paper, Scissors

Difficulty: Easy · You practise: dictionaries as lookup tables, random.choice, continue and break

Play as many rounds as you like against the computer. The dictionary beats stores which move beats which, so there is no long chain of if statements.

import random

beats = {"rock": "scissors", "paper": "rock", "scissors": "paper"}
score = {"you": 0, "computer": 0}

while True:
    you = input("rock, paper or scissors (q to quit): ").lower().strip()
    if you == "q":
        break
    if you not in beats:
        print("Please type rock, paper or scissors.")
        continue
    computer = random.choice(list(beats))
    print(f"Computer chose {computer}.")
    if you == computer:
        print("Draw!")
    elif beats[you] == computer:
        print("You win this round!")
        score["you"] += 1
    else:
        print("Computer wins this round!")
        score["computer"] += 1

print(f"Final score - you {score['you']} : {score['computer']} computer")

▶ Run Rock, Paper, Scissors in the online compiler

Example run (your numbers will differ — they are random):

rock, paper or scissors (q to quit): rock
Computer chose rock.
Draw!
rock, paper or scissors (q to quit): paper
Computer chose scissors.
Computer wins this round!
rock, paper or scissors (q to quit): banana
Please type rock, paper or scissors.
rock, paper or scissors (q to quit): rock
Computer chose scissors.
You win this round!
rock, paper or scissors (q to quit): q
Final score - you 1 : 1 computer

Make it your own: Add lizard and Spock (each move then beats two others, so store a set), or stop at best of five.

3. Hangman

Difficulty: Easy · You practise: sets, string building with join, the while/else clause

Guess the hidden word one letter at a time before you run out of lives. The else on the while loop only runs when the loop ends without break — here, when the lives run out.

import random

words = ["python", "variable", "function", "keyboard", "loop", "string"]
word = random.choice(words)
guessed = set()
lives = 6

while lives > 0:
    shown = " ".join(c if c in guessed else "_" for c in word)
    print(f"\n{shown}   lives: {lives}")
    if "_" not in shown:
        print("You saved the hangman!")
        break
    letter = input("Guess a letter: ").lower()
    if len(letter) != 1 or not letter.isalpha():
        print("One letter, please.")
    elif letter in guessed:
        print("You already tried that.")
    elif letter in word:
        guessed.add(letter)
        print("Yes!")
    else:
        guessed.add(letter)
        lives -= 1
        print("Nope.")
else:
    print(f"\nOut of lives. The word was {word}.")

▶ Run Hangman in the online compiler

Example run (your numbers will differ — they are random):

_ _ _ _ _ _ _ _   lives: 6
Guess a letter: e
Yes!

_ _ _ _ _ _ _ e   lives: 6
Guess a letter: o
Nope.

_ _ _ _ _ _ _ e   lives: 5
Guess a letter: a
Yes!

_ a _ _ a _ _ e   lives: 5
Guess a letter: r
Yes!

_ a r _ a _ _ e   lives: 5
Guess a letter: i
Yes!

_ a r i a _ _ e   lives: 5
Guess a letter: v
Yes!

v a r i a _ _ e   lives: 5
Guess a letter: b
Yes!

v a r i a b _ e   lives: 5
Guess a letter: l
Yes!

v a r i a b l e   lives: 5
You saved the hangman!

Make it your own: Read the word list from a text file, draw an ASCII gallows that grows with each mistake, or give a hint after three misses.

4. Higher or Lower Card Game

Difficulty: Easy · You practise: comparisons, booleans, keeping a streak

A card from 1 to 13 is shown; guess whether the next one will be higher or lower. One wrong guess ends the run. Note the neat trick (new > card) == (guess == "h"): it is true exactly when the guess matched what happened.

import random

card = random.randint(1, 13)
streak = 0
print("Will the next card be higher or lower? Cards go from 1 to 13.")

while True:
    print(f"\nCurrent card: {card}")
    guess = input("higher or lower (h/l): ").lower()
    new = random.randint(1, 13)
    print(f"Next card: {new}")
    if new == card:
        print("Same card - free pass!")
    elif (new > card) == (guess == "h"):
        streak += 1
        print(f"Correct! Streak: {streak}")
    else:
        print(f"Wrong! You finished with a streak of {streak}.")
        break
    card = new

▶ Run Higher or Lower Card Game in the online compiler

Example run (your numbers will differ — they are random):

Will the next card be higher or lower? Cards go from 1 to 13.

Current card: 8
higher or lower (h/l): h
Next card: 9
Correct! Streak: 1

Current card: 9
higher or lower (h/l): h
Next card: 13
Correct! Streak: 2

Current card: 13
higher or lower (h/l): l
Next card: 8
Correct! Streak: 3

Current card: 8
higher or lower (h/l): h
Next card: 8
Same card - free pass!

Current card: 8
higher or lower (h/l): h
Next card: 9
Correct! Streak: 4

Current card: 9
higher or lower (h/l): l
Next card: 10
Wrong! You finished with a streak of 4.

Make it your own: Keep a best streak across games, or use a real 52-card deck with random.shuffle so cards cannot repeat.

5. Math Quiz Game

Difficulty: Easy · You practise: the operator module, functions stored in a dictionary, for loops with range

Five random sums. Instead of the risky eval(), each symbol maps to a real function from the operator module.

import operator
import random

ops = {"+": operator.add, "-": operator.sub, "*": operator.mul}
score = 0

for n in range(1, 6):
    a, b = random.randint(2, 12), random.randint(2, 12)
    symbol = random.choice(list(ops))
    answer = ops[symbol](a, b)
    reply = input(f"Q{n}: {a} {symbol} {b} = ")
    if reply.strip() == str(answer):
        score += 1
        print("Correct!")
    else:
        print(f"Not quite - it's {answer}.")

print(f"You scored {score}/5")

▶ Run Math Quiz Game in the online compiler

Example run (your numbers will differ — they are random):

Q1: 11 * 6 = 66
Correct!
Q2: 7 * 12 = 84
Correct!
Q3: 2 + 9 = 11
Correct!
Q4: 12 + 2 = 15
Not quite - it's 14.
Q5: 3 - 7 = -4
Correct!
You scored 4/5

Make it your own: Time each answer with time.perf_counter(), add division with whole-number answers only, or raise the difficulty after every correct answer.

6. Tic-Tac-Toe (Two Players)

Difficulty: Medium · You practise: lists as a game board, functions, tuples, checking win conditions

Two players share the keyboard. The board is a list of nine squares, and the eight possible winning lines are listed once as tuples of positions.

board = [" "] * 9
lines = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6),
         (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]

def show():
    for row in range(3):
        print(" " + " | ".join(board[row * 3:row * 3 + 3]))
        if row < 2:
            print("---+---+---")

def winner():
    for a, b, c in lines:
        if board[a] != " " and board[a] == board[b] == board[c]:
            return board[a]
    return None

player = "X"
turns = 0
print("Squares are numbered 1-9, left to right, top to bottom.")

while True:
    show()
    move = input(f"Player {player}, choose a square (1-9): ")
    if not move.isdigit() or not 1 <= int(move) <= 9 or board[int(move) - 1] != " ":
        print("That square isn't free - try again.")
        continue
    board[int(move) - 1] = player
    turns += 1
    if winner():
        show()
        print(f"Player {player} wins!")
        break
    if turns == 9:
        show()
        print("It's a draw.")
        break
    player = "O" if player == "X" else "X"

▶ Run Tic-Tac-Toe (Two Players) in the online compiler

Example run (your numbers will differ — they are random):

Squares are numbered 1-9, left to right, top to bottom.
   |   |  
---+---+---
   |   |  
---+---+---
   |   |  
Player X, choose a square (1-9): 5
   |   |  
---+---+---
   | X |  
---+---+---
   |   |  
Player O, choose a square (1-9): 2
   | O |  
---+---+---
   | X |  
---+---+---
   |   |  
Player X, choose a square (1-9): 5
That square isn't free - try again.
   | O |  
---+---+---
   | X |  
---+---+---
   |   |  
Player X, choose a square (1-9): 1
 X | O |  
---+---+---
   | X |  
---+---+---
   |   |  
Player O, choose a square (1-9): 9
 X | O |  
---+---+---
   | X |  
---+---+---
   |   | O
Player X, choose a square (1-9): 7
 X | O |  
---+---+---
   | X |  
---+---+---
 X |   | O
Player O, choose a square (1-9): 3
 X | O | O
---+---+---
   | X |  
---+---+---
 X |   | O
Player X, choose a square (1-9): 4
 X | O | O
---+---+---
 X | X |  
---+---+---
 X |   | O
Player X wins!

Make it your own: Add a computer player — start with random free squares, then make it take a winning square or block yours when it can.

7. Text Adventure Game

Difficulty: Medium · You practise: nested dictionaries, game state, parsing commands

Explore three rooms, find a key and open the chest. The whole map is one dictionary, so adding a room means adding one entry — no new code.

rooms = {
    "hall": {"text": "A dusty hall. Doors lead north and east.",
             "north": "library", "east": "kitchen"},
    "library": {"text": "Tall shelves of old books.",
                "south": "hall", "item": "key"},
    "kitchen": {"text": "A cold kitchen with a chest in the corner.",
                "west": "hall"},
}
room = "hall"
bag = []
print("Commands: north, south, east, west, take, open, quit")

while True:
    here = rooms[room]
    print("\n" + here["text"])
    if "item" in here:
        print(f"You see a {here['item']}.")
    cmd = input("> ").lower().strip()
    if cmd == "quit":
        break
    elif cmd in ("north", "south", "east", "west"):
        if cmd in here:
            room = here[cmd]
        else:
            print("You can't go that way.")
    elif cmd == "take" and "item" in here:
        bag.append(here.pop("item"))
        print(f"You take the {bag[-1]}.")
    elif cmd == "open" and room == "kitchen":
        if "key" in bag:
            print("The chest creaks open. Treasure! You win.")
            break
        print("It's locked. Maybe there is a key somewhere?")
    else:
        print("Nothing happens.")

▶ Run Text Adventure Game in the online compiler

Example run (your numbers will differ — they are random):

Commands: north, south, east, west, take, open, quit

A dusty hall. Doors lead north and east.
> east

A cold kitchen with a chest in the corner.
> open
It's locked. Maybe there is a key somewhere?

A cold kitchen with a chest in the corner.
> west

A dusty hall. Doors lead north and east.
> north

Tall shelves of old books.
You see a key.
> take
You take the key.

Tall shelves of old books.
> south

A dusty hall. Doors lead north and east.
> east

A cold kitchen with a chest in the corner.
> open
The chest creaks open. Treasure! You win.

Make it your own: Add an inventory command, a monster that blocks a door, or save the game with the json module.

8. Blackjack (21)

Difficulty: Medium · You practise: functions that return values, lists that grow, aces worth 1 or 11

Get closer to 21 than the dealer without going over. The total() function counts an ace as 11, then drops it to 1 while the hand would otherwise bust.

import random

def draw():
    return random.choice([2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11])

def total(hand):
    points, aces = sum(hand), hand.count(11)
    while points > 21 and aces:
        points -= 10
        aces -= 1
    return points

you = [draw(), draw()]
dealer = [draw(), draw()]
print(f"Dealer shows {dealer[0]}")

while total(you) < 21:
    print(f"Your cards: {you} (total {total(you)})")
    if input("hit or stand (h/s): ").lower() != "h":
        break
    you.append(draw())

mine = total(you)
print(f"Your cards: {you} (total {mine})")
if mine > 21:
    print("Bust! Dealer wins.")
else:
    while total(dealer) < 17:
        dealer.append(draw())
    theirs = total(dealer)
    print(f"Dealer's cards: {dealer} (total {theirs})")
    if theirs > 21 or mine > theirs:
        print("You win!")
    elif mine == theirs:
        print("Push - it's a tie.")
    else:
        print("Dealer wins.")

▶ Run Blackjack (21) in the online compiler

Example run (your numbers will differ — they are random):

Dealer shows 3
Your cards: [5, 6] (total 11)
hit or stand (h/s): h
Your cards: [5, 6, 8] (total 19)
hit or stand (h/s): s
Your cards: [5, 6, 8] (total 19)
Dealer's cards: [3, 10, 9] (total 22)
You win!

Make it your own: Add a betting balance that carries between rounds, or deal from a real shuffled deck.

9. Word Scramble

Difficulty: Easy · You practise: random.shuffle, converting between strings and lists, slicing

Unscramble three words. The inner while loop reshuffles in the rare case the letters come out in the original order.

import random

words = ["planet", "python", "garden", "rocket", "silver", "castle"]
random.shuffle(words)
score = 0

for word in words[:3]:
    letters = list(word)
    while "".join(letters) == word:
        random.shuffle(letters)
    guess = input(f"Unscramble: {''.join(letters).upper()} > ").lower()
    if guess == word:
        score += 1
        print("Correct!")
    else:
        print(f"No - it was {word}.")

print(f"You scored {score}/3")

▶ Run Word Scramble in the online compiler

Example run (your numbers will differ — they are random):

Unscramble: AGDERN > garden
Correct!
Unscramble: TCKORE > rocket
Correct!
Unscramble: PYHTON > typhon
No - it was python.
You scored 2/3

Make it your own: Give a hint (the first letter) after a wrong answer, or award more points for longer words.

10. Snake Game (Turtle Graphics)

Difficulty: Medium · You practise: the turtle module, keyboard events, a game loop with ontimer, collision checks

The arcade classic, drawn with Python's built-in turtle module — no Pygame to install. Use the arrow keys; each apple adds a body segment, and hitting a wall or yourself restarts the game.

import random
import turtle

screen = turtle.Screen()
screen.setup(600, 600)
screen.bgcolor("black")
screen.title("Snake - score 0")
screen.tracer(0)

head = turtle.Turtle("square")
head.color("lime")
head.penup()
food = turtle.Turtle("circle")
food.color("red")
food.penup()
food.goto(0, 100)

segments = []
direction = "stop"
score = 0

def turn(new, opposite):
    global direction
    if direction != opposite:
        direction = new

screen.listen()
screen.onkeypress(lambda: turn("up", "down"), "Up")
screen.onkeypress(lambda: turn("down", "up"), "Down")
screen.onkeypress(lambda: turn("left", "right"), "Left")
screen.onkeypress(lambda: turn("right", "left"), "Right")

def restart():
    global direction, score
    head.goto(0, 0)
    direction = "stop"
    for seg in segments:
        seg.hideturtle()
    segments.clear()
    score = 0
    screen.title("Snake - score 0")

def tick():
    global score
    for i in range(len(segments) - 1, 0, -1):
        segments[i].goto(segments[i - 1].position())
    if segments:
        segments[0].goto(head.position())

    x, y = head.position()
    step = {"up": (0, 20), "down": (0, -20), "left": (-20, 0), "right": (20, 0)}
    dx, dy = step.get(direction, (0, 0))
    head.goto(x + dx, y + dy)

    hit_wall = abs(head.xcor()) > 290 or abs(head.ycor()) > 290
    hit_self = any(seg.distance(head) < 10 for seg in segments)
    if hit_wall or hit_self:
        restart()
    elif head.distance(food) < 20:
        food.goto(random.randrange(-280, 281, 20), random.randrange(-280, 281, 20))
        seg = turtle.Turtle("square")
        seg.color("green")
        seg.penup()
        seg.goto(head.position())
        segments.append(seg)
        score += 1
        screen.title(f"Snake - score {score}")

    screen.update()
    screen.ontimer(tick, 100)

tick()
screen.mainloop()

This one opens a graphics window, so run it with Python on a computer (save it as snake.py and run python snake.py). Browser and phone Python editors cannot open a turtle window.

Make it your own: Speed up as the score rises, keep a high score in a file, or add walls inside the arena.

Where to go after these games

Once you can read and change every game here, you are past the beginner stage. Good next steps:

Run these games on your phone — the Coding Python app runs real Python 3 on your phone, with examples, quizzes and challenges built in.
Get it free

Frequently asked questions

What is the easiest game to make in Python?

A number guessing game. It needs about fifteen lines — random.randint, a while loop, input() and an if/elif/else — and it is the first game in this list.

Can I copy and paste these Python games?

Yes. Each game is complete, uses only the standard library and runs as-is. Copy it into a .py file, the online compiler on this site, or the Coding Python Android app.

Do I need Pygame to make games in Python?

No. Nine of these games run in a plain terminal, and the snake game uses the turtle module that ships with Python. Pygame is worth installing later for sprites, sound and faster graphics.

Can I run Python games on my phone?

The text games, yes — paste them into the Coding Python app or the online compiler. The snake game needs a desktop window, so run it on a computer.

Why do I get a ValueError in the number guessing game?

int() fails when the text is not a whole number, for example if you press Enter on an empty line. Wrap the conversion in try/except ValueError and ask again.