Python Programming

Dive into Python programming, a versatile and powerful language used for web development, data analysis, artificial intelligence, and more. Learn the fundamentals of Python, from syntax and variables to advanced concepts like multi-dimensional lists.


Contents
  1. Random Numbers
  2. Random Library

Random numbers are incredibly useful to programmers. They allows us to add variation to our programs to make them more interesting.

Every video game makes use of random numbers to make different actions less predictable:

  • Shooting a weapon in a FPS will be impacted by random numbers to perhaps make the weapon jam, or impact how accurate your shot it
  • Any action or attack in an RPG game will be influenced by random numbers to determine how much damage is dealt

Random numbers are also essential to security and keeping our data safe through encryption.

How "random" are random numbers?

Random numbers are actually really hard for computers to generate, most the numbers we get from them aren’t actually random, and rely on measurable quantities the computer can access such as time, mouse movement, keyboard key presses. We often refer to random numbers that computers generate as pseudo-random - this is because with enough knowledge of a system that generates the number it would be possible to predict it.

To generate true random numbers we have to get creative. The internet company Cloudflare generates random numbers for use in encryption by taking regular photographs of 100 lava lamps. The real world is full of systems which can generate random and chaotic numbers which cannot be predicted.

KS3 Computing

Python does not contain all the functions we could possibly want to use, if it did it would run slowly and take up all the computer's memory.

Instead we use libraries to add extra features to python.

When we want to use a library we can import them to access the functions we need

In order to use the random library we need to ensure all of our programs have the following line at the top of our code:

import random

Once we have imported the random library we can generate random numbers using the following line of code

random.randint(1,6)

The brackets in this function must contain two numbers separated by a comma, these are the numbers between which the random number will be generated. The above will generate a number between 1 and 6 (including 1 and 6).

We can store the number inside a variable too if we need to use it later, or check which number has been generated

dice = random.randint(1,6)

KS3 Computing