Welcome everybody! Today we will make a simple dice simulator from scratch. If you are just starting to code, this tutorial is for you.
Lets start by opening Python. Go to Windows main menu and select
Now, lets click
File >> New file. Here is where we will write our code.
First we import the library that allows us to choose random numbers.
Now, we generate a random number and save it in a variable. We will call it
This library has a function called
randint(min number, mx number) requires 2 parameters (the lowest number and the highest number between we will pick our number randomly). In this case, our dice goes between 1-6.
selected = random.randint(1,6)
If we want to show our selected number, we must use
print(). Your code should look like this:
import random selected = random.randint(1,6) print(selected)
If we press
F5, a message will ask us to save the code and then it will start running. If everything went as expected, we should see something like this:
In my case, the random chosen number was 5. If we close the console and run the code again pressing
F5, the chosen number will be different.
Nice, we already have our main engine working, now it’s time to make it look more appealing. To do that we will add some improvements:
import random resultado = random.randint(1,6) print("You rolled: ", resultado)
If we run the code again, we should see a little message and the random number. Congratz! but we can improve it even more. Our code runs only once and then it close. What we need is to keep it running. To accomplish this, we will used
import random while True: resultado = random.randint(1,6) print("El dado giro y obtuvo: ", resultado input("Press any key to roll again.")
If you run this code, you will see that the dice will keep rolling as long as you press any key.
We could keep improving the code even more, but lets leave it here until another day. This example is great to start coding in python. Hope you liked it and see you soon!
If you have any trouble, leave me a comment.