“You can blow on the dice all you want, but whether they come up ‘seven’ is still a function of random luck”
Random, Rndmao, Nardom. Arbitrary spellings of the same word. First I’m going to talk a little bit about the random module in python and then some ways we can use it with few lines of code.
We will be using the function shuffle(x).
First we import our random module and import its shuffle module.
import random
from random import shuffle
Then we will take our password string, reshuffle the letters and then put them back together.
def password_scramble(string):
string = list(string)
shuffle(string)
print(‘’.join(string))
password_scramble('learnlovecode')
Output: rdloeovcneeal[Finished in 0.689s]
What was the wifi code again?
2. Letting Python decide what you eat tonight
We will use the random.choice( ) function. It randomly chooses an element from a list.
I multiplied each element in the list by a weighted number according to my preferences. Then I let the random module choose for me.
import random
types_of_rests = [‘Indian’] * 30 + [‘Italian’] * 30 + [‘Thai’] * 40
print(random.choice(types_of_rests))
Output: Indian[Finished in 0.579s]
3. Choosing Mega Millions numbers (5 numbers between 1 & 70 and 1 Megaball between 1 & 25)
We will use the random.randint(x, y) function which generates numbers between ‘x’ and ‘y’, and the .choice( ) function from before.
We want to create a new list for our generated lottery numbers. We set ‘x’ = 0 because we will be using a ‘while’ loop to keep our returned list capped. Finally creating a lucky number variable between 1 and 70.
import random
lotterynumbers = []
megaball = range(1,26)
x = 0
The randint and choice generated numbers are all compiled into the lottery numbers list.
while x < 5:
lotterynumbers.append(random.randint(1, 71))
x += 1lotterynumbers.append(random.choice(megaball))
Output: [47, 58, 16, 54, 62, 13][Finished in 1.392s]
//.
Sources:
https://docs.python.org/3/library/random.html