Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Simulate Events (Solution)

00:00 So, write a function that simulates the role of a die, and there’s some randomness involved. So you’re going to use the Python random module.

00:08 I’m going to import random. Then I should write a function. So, I’m going to say def roll() because I think this is what we said it should be called. Doesn’t really need to take any input, but what it does is it should return a number from 1 to 6.

00:24 I’m just going to say return random.randint(1, 6) The start and the stop are both included in the possible results, so I can just say 1 to 6, and that is already the solution.

00:39 Let’s give it a go. Run it. Well, okay, I guess I’ve got to print something too. I need to first call the function and then also print something. So I will print() a call to roll.

00:54 Let’s do a couple of them to see whether the randomness works.

01:00 So, we’ll save this, run it, and we get 4, 2, 2, 4, 5. So, these are possible outcomes of rolling the dice one, two, three, four, five times.

01:10 Great. A slightly different way of doing this is you could, instead of importing the whole random module, we could say from random import just the randint function, and then you could cut it out here and just return a call to randint(). Exactly the same otherwise.

01:27 So, let’s run it again. No, InvalidSyntax from fron, or fron is not exactly the same. from. There we are.

01:39 5, 3, 5, 6, 1, and 4. Looks like our die is fair. Yippee! Okay. And you practice importing randomness and then also defining function, which are both things that you’re going to need for the upcoming challenge.

01:57 Here, you’ve got the solution again, and I’ve also added a little docstring to the function that just describes what this function does. from random import randint and then define the roll() function.

02:08 And then you’re essentially just returning a random number between 1 and 6. All right, that’s it for the review exercises. Let’s do a quick recap and then afterwards move on to the challenges.

Become a Member to join the conversation.