I Haz Codes

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Menu
random numbers

Syntax

print
random
.
randint
(
low
,
high
)

About random numbers

Note – You must import random before using random numbers.

Random numbers are produced in python by using the random module. The video below demonstrates how to use one function from the random module, randint(a,b). Random numbers on a computer are actually the product of a repeatable algorithm  As such they can not produce truly random numbers. However they are random enough for most programs.

The code below is from the video –

import random

dice = random.randint(1,6)

if dice == 1:
	print ("you win")
else:
	print ("you lost with the roll of ", dice)

 

Key terms

function – A named block of code which can be called to perform another task. They can be pre-written in modules or created by the programmer.

Module – A pre-written selection of related functions collected together for use by other programmers.

 

Helpful links

Python docs for the random module

Random seeds

More detail on random functions

Test your skill

1. Write a program which will display a random number between 20 and 30.

Task 1: Answer SelectShow

2. Write a program which will roll two six-sided die and display their totals.

Task 2: Answer SelectShow

3. Write a program which will allow the user to pick a number between 1 and 1000. The computer will then select a random number between 1 and the number entered.

Task 3: Answer SelectShow

Leave a Reply

Your email address will not be published. Required fields are marked *

Information