Intro .1 .2 .3 .4 .5 .6 .7 .8 .9 .10 .11 .12 .13 .14 .15 .16 .17 .18

Random Values

Introduction

Random values are widely used in programming for various applications such as simulations, games, security, and testing. Randomness introduces variability and helps create unpredictable outcomes.

Objectives

By the end of this lesson, students will be able to:

  1. Understand what random values are.
  2. Write pseudocode using random value generation.
  3. Apply random values in practical scenarios.

Key Concepts

  1. Random Values: Values generated in such a way that each value within a specified range has an equal chance of being selected.
  2. Random Number Generators (RNGs): Algorithms or functions that produce random values.

Example Syntax (College Board Pseudocode)

College Board pseudocode uses the following structure for generating random values:

RANDOM(a, b)

Where a and b are the lower and upper bounds of the range (inclusive).

<span style="color:blue">Example 1: Rolling a Die</span>
Pseudocode
Let's write pseudocode to simulate rolling a six-sided die:


```python
result ← RANDOM(1, 6)
DISPLAY result

Example 2: Random Decision Making Pseudocode Let’s consider a scenario where we make a random decision between “yes” and “no”:

decision  RANDOM(1, 2)
IF decision = 1
{
    DISPLAY "Yes"
}
ELSE
{
    DISPLAY "No"
}

Python

Here is the equivalent Python code:

import random

decision = random.randint(1, 2)
if decision == 1:
    print("Yes")
else:
    print("No")

No

Example 3: Write pseudocode to simulate drawing a random card from a standard deck of 52 cards:

Generate a random number between 1 and 52. Display the card number.

card  RANDOM(1, 52)
DISPLAY "Card number: " + card

Python

Here is the equivalent Python code:

import random

card = random.randint(1, 52)
print("Card number:", card)

Card number: 52

Summary Random values introduce variability and unpredictability into programs, making them essential for various applications. By understanding how to generate and use random values, you can enhance your programs with elements of randomness.

Hacks

Review each of the sections above and produce …

  • Write pseudocode to simulate flipping a coin 10 times and display the result of each flip.
  • Write a python segment to generate a random password of 8 characters, using uppercase letters, lowercase letters, and digits.