Lesson-11:Python Random Module
Python Random Module
In this course, we will process the python Random module nudes. This module, which comes as standard in the Python programming language, allows you to generate random numbers. It is used in Python versions 1.4 and higher.
random( ) Fonksiyonu:
This function generates a random float number between 0 and 1. Its usage is as follows.
import random
a= random.random()
print (a)
screen shot:
0.08777456189916566
Process finished with exit code 0
a = random.random () this line of code may confuse you. It means the random function in the random module. They have the same names.
uniform( ) Fonksiyonu:
This focus produces a random decimal number in the float type between the Min and max values that it takes in parentheses. Its usage is as follows.
import random
a= random.uniform(1,80)
print (a)
screen shot:
54.66940174241958
Process finished with exit code 0
When examining the above codes, random float type numbers between 1 and 80 can be generated.
randint( ) Fonksiyonu:
This function is very often used and generates a random integer number between the min and max values written in parentheses. Below is its use.
import random
a= random.randint(1,200)
print (a)
screen shot:
146
Process finished with exit code 0
As can be seen from the example, it produces a random integer between 1 and 200.
randrange( ) Fonksiyonu:
This function is very similar to the randint function, but takes a third parameter. This third parameter that it receives is described below, for example.
import random
a= random.randrange(1,50,5)
print (a)
screen shot:
41
Process finished with exit code 0
This function also selects random integers from 1 to 50. But its difference from the randint function is its third parameter. It randomly selects the numbers that give the rest of the 1 section to the number written here.
sample (list,q) Fonksiyonu:
Q is used to randomly select the values in a list. See the example below for details.
import random
liste=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
a= random.sample(liste,4)
print (a)
screen shot:
[17, 4, 10, 13]
Process finished with exit code 0
In the above example, we randomly selected 4 elements from the list named list.
shuffle (list) Fonksiyonu:
It is used to mix the list entered as a parameter. The following example gives the code structure.
import random
liste=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
random.shuffle(liste)
print (liste)
screen shot:
[3, 7, 11, 10, 1, 17, 8, 13, 12, 4, 2, 6, 16, 15, 5, 14, 9]
Process finished with exit code 0
As you can see, we printed the list on the screen in a mixed way.
choice (list) Fonksiyonu:
It serves to draw a random element from a list. See the following example.
import random
liste=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
a=random.choice(liste)
print (a)
screen shot:
12
Process finished with exit code 0
As can be seen, a random element was selected from the list above.