Code Explanation:
1. import random
Loads the random module.
This allows us to use random.randint(1, 6) to simulate a dice roll.
2. Define the generator function dice_rolls(n)
def dice_rolls(n):
for _ in range(n):
yield random.randint(1, 6)
This function doesn't execute until it's called.
When called, it yields n random values between 1 and 6, one at a time.
3. Execute dice_rolls(4)
list(dice_rolls(4))
Calls the generator to get 4 dice rolls.
Example output from dice_rolls(4) might be: [3, 6, 1, 5]
Note: Dice rolls are random, so the exact numbers will vary.
4. len(...) counts the rolls
len([3, 6, 1, 5]) # Example result
The length of the list is 4 because we rolled the dice 4 times.
5. print(...) prints the count
print(4)
So the final output is:
Final Output
4
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment