Question & Answer

Write a Python program that simulates rolling two dice until you get "snake eyes" (when both dice show a value of 1)

Write a Python program that simulates rolling two dice until you get “snake eyes” (when both dice show a value of 1). Each round, roll two dice using the randint function from the random module and print the values of both dice. If the values of both dice are 1, print how many rolls it took to get snake eyes and exit the loop. Format your output to match the following sample:

Rolled: 6 5
Rolled: 3 2
Rolled: 5 6
Rolled: 6 2
Rolled: 1 4
Rolled: 1 1
It took you 6 rolls to get snake eyes.

2 Answers

Verified archive
Quizzma TeamNovember 18, 2024

import random

# Initialize variables
roll_count = 0
snake_eyes = False

# Loop until snake eyes is rolled
while not snake_eyes:
# Roll two dice
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
roll_count += 1 # Increment roll count

# Print the result of the roll
print(f”Rolled: {die1} {die2}”)

# Check if it’s snake eyes (both dice are 1)
if die1 == 1 and die2 == 1:
snake_eyes = True

# Print the total rolls it took to get snake eyes
print(f”It took you {roll_count} rolls to get snake eyes.”)

Quizzma TeamNovember 18, 2024

Explanation:

  1. Dice Rolling Logic:
    • Use the random.randint(1, 6) function to simulate rolling a die.
    • Roll two dice and store their values in die1 and die2.
  2. Snake Eyes Check:
    • If both dice values are 1, the loop ends.
  3. Count Rolls:
    • Keep a roll_count variable to track the total number of rolls.
  4. Output Format:
    • Match the format in the sample output by printing the dice rolls and the final message.