NumPy Random

Random numbers and sampling.

✍️ 3 exercises + code challenge in this lesson

Create a random generator with rng = np.random.default_rng(seed). A fixed seed gives the same numbers every time, which is useful for testing.

  • rng.integers(low, high, size)
  • rng.random(size): floats from 0 to 1
  • rng.choice(list), rng.shuffle(arr), rng.normal(mean, std, size)

Key Takeaways: NumPy Random

Mastering NumPy Random helps you write clean and reliable NumPy code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

NumPy Random Code Example

NumPy
import numpy as np

rng = np.random.default_rng(42)
print(rng.integers(1, 7, size=5))
print(rng.choice(["Ali", "Sara", "Usman"]))
values = rng.normal(50, 10, size=1000)
print(round(values.mean()))
Output
[1 5 4 3 3]
Usman
50
Free sign-in required · Google login available

NumPy Random Practice Exercises

Check what you learned in “NumPy Random”.

/ 3 solved
Fill in the blank

Create a random generator with a fixed seed.

rng = np.random.(42)
✓ Correct! Not quite. Try again.
Multiple choice

Why set a seed?

✓ Correct! Not quite. Try again.
Code challenge

Create rng with seed 0, generate 5 integers from 1 to 10 with rng.integers(1, 11, size=5), and print how many values there are.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services