Search⌘ K
AI Features

Solution: Dice Roller

Explore how to create a Python program that simulates rolling two dice using the random module. This lesson helps you understand function creation, random integer generation, and formatted output to build your coding skills with hands-on practice.

We'll cover the following...

This program simulates rolling two dice using Python’s random module. The roll_two_dice() function generates two random integers between 1 and 6, representing the outcome of each die. It uses random.randint(1, 6) to ensure each die roll has an equal chance of landing on any number from 1 to 6. After both dice are rolled, the program prints the results clearly in a single sentence, showing both numbers.

When the function is called at the end, it executes once and displays the two random dice rolls. This example is a simple way to practice writing functions, using random number generation, and printing formatted output in Python.

Python
import random
# Function to roll two dice
def roll_two_dice():
die1 = random.randint(1, 6) # Roll the first die
die2 = random.randint(1, 6) # Roll the second die
print("We rolled a", die1, "and a", die2)
# Call the function to see the result
roll_two_dice()