Random Values

Random Values

Python can generate random numbers and choose random items from list/strings.

It is not really random but something so close to random (pseudo-random) that you can treat it as random.

Random Values

import random

In order to use the built-in random functions you must have the following line at the start of your program.

from random import randint

If you only want to use one particular function from the random module you can also use.

Example I

Use random floating point numbers

import random

num = random.random()
num = num * 100
print(num)

Example II

Use random integer numbers

import random

num = random.randint(0, 9)
print(num)

Example III

Use random numbers with steps (e.g. multiples of five)

import random

num = random.randrange(0, 100, 5)
print(num)

Example IV

Use random item from a list

import random

names = [
  'Albert',
  'Bradley',
  'Charles',
  'David',
  'Edward',
  ]

name = random.choice(names)
print(name)

Example V

Use random letter from a string

import random

alphabet = 'abcdefghijklmnopqrstuvwxyz'

letter = random.choice(alphabet)
print(letter)

Tasks I

  1. Display a random integer between 1 and 100 inclusive.
  1. Display a random fruit from a list of five fruits.
  1. Randomly choose either heads or tails (‘h’ or ‘t’). Ask the user to make their choice. If their choice is the same as the randomly selected value, display the message ‘You win’, otherwise display ‘Bad luck’. At the end, tell the user if the computer selected heads or tails.

Tasks II

  1. Randomly pick a whole number between 1 and 10. Ask the user to enter a number and keep entering numbers until they enter the number that was randomly picked.
  1. Update program 5 so that it tells the user if they are too high or too low before they pick again.
  1. Randomly choose a number between 1 and 5. Ask the user to pick a number. If they guess correctly, display the message ‘Well done’, otherwise tell them if they are too high or too low and ask them to pick a second number. If they guess correctly on their second guess, display ‘Correct’, otherwise display ‘You lose’.

Tasks III

  1. Make a maths quiz that asks five questions by randomly generating two whole numbers to make the question (e.g. [num1] + [num2]). Ask the user to enter the answer. If they get it right add a point to their score. At the end of the quiz, tell them how many they got out of five.
  1. Display five colours and ask the user to pick one. If they pick the same as the program has chosen, say ‘Well done’, otherwise display a witty answer which involves the correct colour, e.g. ‘I bet you are GREEN with envy’ or ‘You are probably feeling BLUE right now’. Ask them to guess again: if they have still not got it right, keep giving them the same clue and ask the user to enter a colour until they guess it correctly.

G Random Values

By David James

G Random Values

Python - Random Values

  • 523