logo

Module Python aléatoire

Le module Python Random est un module intégré permettant de générer des entiers aléatoires en Python. Ces nombres apparaissent de manière aléatoire et ne suivent aucune règle ou instruction. On peut donc utiliser ce module pour générer des nombres aléatoires, afficher un élément aléatoire pour une liste ou une chaîne, etc.

La fonction random()

La fonction random.random() donne un nombre flottant compris entre 0,0 et 1,0. Aucun paramètre n'est requis pour cette fonction. Cette méthode renvoie la deuxième valeur aléatoire à virgule flottante comprise entre [0,0 et 1].

Code

 # Python program for generating random float number import random num=random.random() print(num) 

Sortir:

paramètres du navigateur Web
 0.3232640977876686 

La fonction randint()

La fonction random.randint() génère un entier aléatoire à partir de la plage de nombres fournie.

Code

 # Python program for generating a random integer import random num = random.randint(1, 500) print( num ) 

Sortir:

 215 

La fonction randrange()

La fonction random.randrange() sélectionne un élément de manière aléatoire dans la plage donnée définie par les paramètres de début, d'arrêt et d'étape. Par défaut, le début est défini sur 0. De même, le pas est défini sur 1 par défaut.

Code

 # To generate value between a specific range import random num = random.randrange(1, 10) print( num ) num = random.randrange(1, 10, 2) print( num ) 

Sortir:

np où
 4 9 

La fonction choix()

La fonction random.choice() sélectionne au hasard un élément d’une série non vide. Dans le programme ci-dessous, nous avons défini une chaîne, une liste et un ensemble. Et en utilisant la méthode Choice() ci-dessus, un élément aléatoire est sélectionné.

Code

 # To select a random element import random random_s = random.choice('Random Module') #a string print( random_s ) random_l = random.choice([23, 54, 765, 23, 45, 45]) #a list print( random_l ) random_s = random.choice((12, 64, 23, 54, 34)) #a set print( random_s ) 

Sortir:

 M 765 54 

La fonction shuffle()

La fonction random.shuffle() mélange la liste donnée de manière aléatoire.

oups, des concepts

Code

 # To shuffle elements in the list list1 = [34, 23, 65, 86, 23, 43] random.shuffle( list1 ) print( list1 ) random.shuffle( list1 ) print( list1 ) 

Sortir:

logo java
 [23, 43, 86, 65, 34, 23] [65, 23, 86, 23, 34, 43] 

Programme Pierre-Papier-Ciseaux utilisant le module aléatoire

Code

 # import random module import random # Function to play game def start_game(): # Print games rules and instructions print(' This is Javatpoint's Rock-Paper-Scissors! ') print(' Please Enter your choice: ') print(' choice 1: Rock ') print(' choice 2: Paper ') print(' choice 3: Scissors ') #To take the user input choice_user = int(input(' Select any options from 1 - 3 : ')) # randint() Function which generates a random number by computer choice_machine = random.randint(1, 3) # display the machines choice print(' Option choosed by Machine is: ', end = ' ') if choice_machine == 1: print(' Rock ') elif choice_machine == 2: print('Paper') else: print('Scissors') # To declare who the winner is if choice_user == choice_machine: print(' Wow It's a tie! ') elif choice_user == 1 and choice_machine == 3: print(' Congratulations!! You won! ') elif choice_user == 2 and choice_machine == 1: print(' Congratulations!! You won! ') elif choice_user == 3 and choice_machine == 2: print(' Congratulations!! You won! ') else: print(' Sorry! The Machine Won the Game? ') # If user wants to play again play_again = input(' Want to Play again? ( yes / no ) ').lower() if play_again == ' yes ': start_game() else: print(' Thanks for playing Rock-Paper-Scissors! ') # Begin the game start_game() 

Sortir:

 This is Javatpoint's Rock-Paper-Scissors! Please Enter your choice: choice 1: Rock choice 2: Paper choice 3: Scissors Select any options from 1 - 3 : 1 Option choosed by Machine is: Rock Wow It's a tie! Want to Play again? ( yes / no ) yes This is Javatpoint's Rock-Paper-Scissors! Please Enter your choice: choice 1: Rock choice 2: Paper choice 3: Scissors Select any options from 1 - 3 : 2 Option choosed by Machine is: Scissors Congratulations!! You won! Want to Play again? ( yes / no ) no Thanks for playing Rock-Paper-Scissors! 

Diverses fonctions du module aléatoire

Voici la liste des fonctions disponibles dans le module aléatoire.

Fonction Description
seed(a=Aucun, version=2) Cette fonction crée un nouveau nombre aléatoire.
obtenir un état() Cette méthode fournit un objet reflétant l'état actuel du générateur. Fournissez l'argument à setstate() pour récupérer l'état.
setstate(état) Fournir l'objet d'état réinitialise l'état de la fonction au moment où getstate() a été invoqué.
obtenir des bits(k) Cette fonction fournit un entier Python ayant k bits aléatoires. Ceci est important pour les algorithmes de production de nombres aléatoires comme randrange(), qui peuvent gérer des plages arbitrairement énormes.
randrange(début, arrêt[, étape]) À partir de la plage, il produit un entier aléatoire.
retour (a, b) Fournit un entier compris entre a et b au hasard (tous deux inclus). Si a > b, une ValueError est levée.
choix (suite) Produire aléatoirement un élément de série non vide.
mélanger (séquence) Changez l'ordre.
échantillon (population, k) Affichez une liste d’entrées uniques de taille k de la série de population.
aléatoire() Cette fonction crée un nouveau nombre aléatoire.
uniforme (a, b) Cette méthode fournit un objet reflétant l'état actuel du générateur. Fournissez l'argument à setstate() pour récupérer l'état.
triangulaire (bas, haut, mode) Fournir l'objet d'état réinitialise l'état de la fonction au moment où getstate() a été invoqué.
guass ( mu , sigma ) Avec la moyenne et l'écart type, un nombre flottant est généré de manière aléatoire.
bêtavariée (alpha, bêta) Avec alpha et bêta, un nombre flottant est généré aléatoirement entre 0 et 1. - Distribution bêta expovarié (lambda) Le numéro flottant est généré en utilisant l'argument lambda. - Distribution exponentielle variable normale (mu, sigma) Avec la moyenne et l'écart type, un nombre flottant est généré de manière aléatoire. - Distribution normale gamavariate (alpha, bêta) Avec alpha et bêta, un nombre flottant est généré de manière aléatoire. - Distribution gamma

Conclusion

Pour conclure, nous avons découvert diverses méthodes que le module aléatoire de Python nous fournit pour traiter les entiers, les nombres à virgule flottante et d'autres séquences telles que les listes, les tuples, etc. Nous avons également examiné comment la graine affecte le modèle de nombres pseudo-aléatoires.