random

Random allows you to choose a random item from lots of sources.
To use random you need to inport it at the top of your program

Simple random whole number
import random
randomnumber = random.randint(1,5) #Random whole number between 1 and 5
print(randomnumber)

This could output as 1, 2, 3, 4 or 5
>>>
3
>>>

Random Numbers used in a quiz
You can try this code by downloading randomnumbertest.py below
Other useful areas contained in this code variables print if else Maths Operations

Random Item from a list
Clearest way to do this is
import random
kids=["Mary","Raj","Jon"]
yourturn=random.choice(kids)
print("It is your turn",yourturn)
#import random library
#Make a list called kids
#make a random choice from kids and put #it into yourturn variable
Or you could create the list inside the yourturn variable
import random
yourturn = random.choice(["John","Mary","Sheila","Mark"])
print("It is your turn",yourturn)

This could output as
>>>
It is your turn Mary
>>>
Mary could be replaced by John, Sheila or Mark
Find out more about a list

Random item from a file
Make sure the file you have created is in the same folder as the Python program you are writing.
Make sure each object is on a separate line.
Save the file as a .txt file.
In this example the file is films.txt
This would output as a random film from the file
Note you must open and close the text file
You can download this file as files.py and the films.txt below (You must place them in the same folder)
ċ
files.py
(0k)
Philip Bagge,
15 Jul 2012, 12:49
ċ
films.txt
(2k)
Philip Bagge,
15 Jul 2012, 12:49
ċ
randomnumbertest.py
(1k)
Philip Bagge,
11 Jul 2012, 13:41
Comments