0

How do we generate random numbers in python?

How do we generate random numbers in python?

27th Jan 2017, 6:03 PM
mahdi_abdollahpour
mahdi_abdollahpour - avatar
3 ответов
+ 1
here's a simple example of generating random numbers between 0 and 100 as long as a condition is satisfied: import random x = 0 while x < 10: print(random.randint(0,100)) x+=1
27th Jan 2017, 6:37 PM
Cristi Vlad
Cristi Vlad - avatar
+ 1
you can use random function from random module Here is a link for random documentation: https://docs.python.org/3.4/library/random.html import random >>> random.random() # Random float x, 0.0 <= x < 1.0 0.37444887175646646 >>> random.uniform(1, 10) # Random float x, 1.0 <= x < 10.0 1.1800146073117523 >>> random.randrange(10) # Integer from 0 to 9 7 >>> random.randrange(0, 101, 2) # Even integer from 0 to 100 26 >>> random.choice('abcdefghij') # Single random element 'c' >>> items = [1, 2, 3, 4, 5, 6, 7] >>> random.shuffle(items) >>> items [7, 3, 2, 5, 6, 4, 1] >>> random.sample([1, 2, 3, 4, 5], 3) # Three samples without replacement [4, 1, 5]
28th Jan 2017, 12:27 AM
Vlad
Vlad - avatar
+ 1
If you wanted to simulate a dice roll: import random x = random.randint(1, 6)
28th Jan 2017, 2:34 AM
syn
syn - avatar