Wednesday, 27 September 2017

Importing Modules and Random Stuff

So far all the functions we have covered have been part of Python's core.
However, to increase the range of functions we can import modules. Modules can be thought of as extensions to Python, bringing along new functions and capabilities. There are a huge number of modules available, some bundled with the Python interpreter so you know they are ready to be imported, including
  • random (generates random numbers and outputs)
  • math (allows advanced maths, including trigonometry & logarithms)
  • os (lets the python program interact with your computer's operating system
  • re (lets the programmer use Regular Expressions in the code)
  • time (provides date, time and similar functions)
  • sys (allows modification at the level of Python interpreter)
The full list is here.
Some other modules (usually third party) need to be downloaded and installed, typically using a program called pip (Python Installation Program? The acronym is not explained).

Importing modules is best done at the very start of a program, and the simplest way is import modulename.
Here is an example script that uses the random module:
#!/usr/bin/python3
import random
print ('Example of random float between 0 and 1')
print (random.random())
print ('Example of random integer between 1 and 100')
print (random.randrange(100) +1)
print ('Example of random element from a list')
samplelist = ['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta']
print ('Sample list = ', samplelist)
print (random.choice(samplelist))
print ('Random shuffle of list')
shuffledlist = samplelist
random.shuffle(shuffledlist)
print (shuffledlist)
And the results are
 RESTART: C:/Users/John/Dropbox/Misc Programming/Python/python3/test05_randomtest.py
Example of random float between 0 and 1
0.3802338941554101
Example of random integer between 1 and 100
95
Example of random element from a list
Sample list =  ['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta']
beta
Random shuffle of list
['delta', 'epsilon', 'zeta', 'gamma', 'eta', 'beta', 'alpha', 'theta']

>>>
 Of course, should you run it yourself, you won't get exactly the same results, otherwise it wouldn't be random.
A few point that I found out for myself while doing this
For the randrange() function, I included the +1 for it to be from 1 to 100 rather than 0 to 99.
shuffle() function works in a kind of opposite to sort() (it sorts the list in a random rather than logical way). But similar to sort(), it changes the list in-place and returns None, so if I change the line at the end of the script
print (random.shuffle(samplelist))
what I get printed is not a shuffled samplelist but None
 RESTART: C:/Users/John/Dropbox/Misc Programming/Python/python3/test05_randomtest.py
Example of random float between 0 and 1
0.7661205325736707
Example of random integer between 1 and 100
74
Example of random element from a list
Sample list =  ['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta']
theta
Random shuffle of list
None

>>>
In business, randomness is not really wanted - its main use is in testing and sampling from large sets of data. However, it can provide some amusement. For example, this silly program
#!/usr/bin/python3
import random
print("Quick Murder Mystery Generator")
suspectlist = ['Cook', 'Butler', 'Colonel', 'Doctor', 'Detective', 'Disinherited Son', 'Divorcee', 'Failed Actress', 'Mad Scientist', 'Python Programmer']
weaponlist = ['Revolver', 'Garrotte', 'Dagger', 'Candlestick', 'Spanner', 'Hatchet', 'Voodoo Curse', 'Submachinegun', 'Shotgun', 'Poisoned drink']
locationlist = ['Conservatory','Vegetable Patch', 'Kitchen', 'Dining Room', 'TV Room', 'Bedroom', 'Bathroom', 'Wine Cellar', 'Study', 'Library', 'Flower Garden']
print('A murder has been committed - the lord of the manor has been found dead. But who did it, with what, and where?')
print ('Miss Marbles the amateur sleuth has come along and after asking some awkward questions, has decided')
suspectchoice = random.choice(suspectlist)
weaponchoice = random.choice(weaponlist)
locationchoice = random.choice(locationlist)
print ('It was the', suspectchoice, 'using the', weaponchoice, 'in the', locationchoice,'!!')
give the output
>>>
 RESTART: C:/Users/John/Dropbox/Misc Programming/Python/python3/test05b_cluedo.py
Quick Murder Mystery Generator
A murder has been committed - the lord of the manor has been found dead. But who did it, with what, and where?
Miss Marbles the amateur sleuth has come along and after asking some awkward questions, has decided
It was the Disinherited Son using the Dagger in the Flower Garden !!

>>>
 And unlike some murder mysteries, this one is quite difficult to predict how it will turn out....

No comments:

Post a Comment