Créer un simulateur de lancer de dés en Python

Najwa Riyaz 18 juillet 2021
Créer un simulateur de lancer de dés en Python

Pour créer un simulateur de lancer de dés en Python, nous utilisons la fonction random.randint() qui génère des nombres aléatoires entre la plage de nombres 1 à 6 comme suit.

random.randint(1, 6)

Créer un simulateur de lancer de dés en Python à l’aide de random.randint(1,6)

Nous pouvons créer un simulateur de lancer de dés en Python en utilisant la fonction random.randint(). La syntaxe de la fonction est la suivante.

random.randint(x, y)

En conséquence, il génère un nombre entier aléatoire compris entre x et y. Dans l’exemple du simulateur de dés,

x vaut 1 et y vaut 6.

Ci-dessous un exemple.

import random

print("You rolled the following number", random.randint(1, 6))

Pour laisser l’utilisateur choisir de continuer à lancer les dés ou non, nous pouvons placer random.randint(1,6) dans une boucle while comme suit.

from random import randint

repeat_rolling = True
while repeat_rolling:
    print("You rolled the following number using the Dice -", randint(1, 6))
    print("Do you wish to roll the dice again?")
    repeat_rolling = ("y" or "yes") in input().lower()

Lorsque l’utilisateur choisit d’arrêter de lancer les dés, il doit sortir de la boucle while.

Production:

You rolled the following number using the Dice - 2
Do you wish to roll the dice again?
y
You rolled the following number using the Dice - 4
Do you wish to roll the dice again?
y
You rolled the following number using the Dice - 5
Do you wish to roll the dice again?
n

Article connexe - Python Number