201k views
1 vote
[roll_until_sum.py] Write a program that simulates rolling two 6-sided dice, and repeatedly rolls them until a target sum is reached. A user should input what the target sum is. The program should output the result of rolling each die and the sum, finally reporting how many rolls it took to reach the target sum. For example:

This program rolls two 6-sided dice until their sum is a given target value.
Enter the target sum to roll for: 9

Roll: 5 and 3, sum is 8
Roll: 3 and 1, sum is 4
Roll: 4 and 1, sum is 5
Roll: 4 and 1, sum is 5
Roll: 6 and 3, sum is 9
Got it in 5 rolls!

1 Answer

5 votes

Answer:

The solution code is written in Python:

  1. import random
  2. target = int(input("Enter the target sum to roll for: "))
  3. die1 = random.randint(1,6)
  4. die2 = random.randint(1,6)
  5. print("Roll: " + str(die1) + " and " + str(die2) + ", sum is " + str(die1 + die2))
  6. count = 1
  7. while(die1 + die2 != target):
  8. die1 = random.randint(1,6)
  9. die2 = random.randint(1,6)
  10. print("Roll: " + str(die1) + " and " + str(die2) + ", sum is " + str(die1 + die2))
  11. count += 1
  12. print("Got it in " + str(count) + " rolls!")

Step-by-step explanation:

Since we need to generate random value for die, we import random module (Line 1).

Next, we use input function to prompt user to input a target number (Line 2).

We use randint method in the random module to generate a random integer between 1 - 6 (Line 4-5).

Display the die numbers and the sum (Line 6)

Create one counter variable track the number of rolling and initialize it with one (Line 7).

Create a while loop and set a condition that while the sum of two die numbers are not equal to the target the loop should keep going (Line 9)

In the loop generate two new random die numbers again and display the generated die numbers and the sum (Line 10 - 12). Increment count by one and proceed to the next iteration (Line 13).

At last display the message number of rolls after finishing the loop (Line 15).

User Ngstschr
by
3.0k points