▶ Random Everything - 100+ Free Generators // v2.1.6
root@generate-random:~/random-number-code$ _

Random Number Code Generator

Ready-to-paste code for a random number in any range - Python, JavaScript, Java, C#, Go, PHP and Bash, secure or not

Need a random number in code? Pick a language and a range above and copy a correct, ready-to-run snippet - the fast version for games and tests, or the cryptographically secure one for tokens and draws.

Random Number Between 1 and 10 in Every Language

The fast way and the secure way, side by side. Each language page has full examples: floats, picking from a list, shuffling and common mistakes.

Language Fast (not secure) Cryptographically secure
Pythonrandom.randint(1, 10)secrets.randbelow(10) + 1
JavaScriptMath.floor(Math.random() * 10) + 1crypto.getRandomValues()
JavaThreadLocalRandom.current().nextInt(1, 11)new SecureRandom().nextInt(10) + 1
C#Random.Shared.Next(1, 11)RandomNumberGenerator.GetInt32(1, 11)
Go random number coderand.IntN(10) + 1 // math/rand/v2crypto/rand: rand.Int(rand.Reader, big.NewInt(10))
PHPmt_rand(1, 10)random_int(1, 10)
Bashecho $(( RANDOM % 10 + 1 ))shuf -i 1-10 -n 1 --random-source=/dev/urandom

Secure vs Non-Secure Random Numbers

Every language ships a fast pseudo-random generator (Mersenne Twister, xorshift, PCG...) that is perfect for games, simulations and tests - and predictable: seen enough outputs, an attacker can work out the next ones. For passwords, tokens, session IDs, invite codes or prize draws, use the language's cryptographically secure generator (CSPRNG), which reads from the operating system. It is a little slower and just as easy to call.

Inclusive or Exclusive Upper Bound?

The most common bug in random-number code is an off-by-one on the maximum. Python's randint, PHP's random_int and mt_rand include it; Java's nextInt, C#'s Next and GetInt32, Go's IntN, Node's randomInt and Python's randrange exclude it, so you add 1. The generator above always produces an inclusive range and says so in a comment.

Random Numbers in Python

How to generate a random number in Python: import random for games and simulations, secrets for anything security-related.

Python: Random Integer in a Range

Both functions are in the standard library - nothing to install. randint includes both ends; randrange excludes the stop value, like range().

import random

random.randint(1, 10)      # 1..10, both ends included
random.randrange(0, 10)    # 0..9, stop is excluded
random.randrange(0, 100, 5)  # 0, 5, 10 ... 95

Python: Random Float

random() returns a float in [0.0, 1.0); uniform(a, b) scales it to your range.

import random

random.random()          # 0.0 <= x < 1.0
random.uniform(1.5, 4.5)  # float between 1.5 and 4.5

Python: Pick and Shuffle

choice picks one item, sample picks several without repeats, shuffle reorders a list in place.

import random

items = ["red", "green", "blue", "yellow"]
random.choice(items)       # one item
random.sample(items, 2)    # two different items
random.shuffle(items)      # shuffles the list in place, returns None

Python: Secure Random Numbers with secrets

The random module is a Mersenne Twister: fast and reproducible, but predictable. For passwords, tokens, invite codes or prize draws use secrets, which reads from the operating system CSPRNG.

import secrets

secrets.randbelow(10) + 1   # 1..10
secrets.choice(["a", "b"])  # secure pick
secrets.token_hex(16)       # 32 hex characters
secrets.token_urlsafe(16)   # URL-safe token
secrets.SystemRandom().shuffle(items)  # secure shuffle

Python: Common Mistakes

Naming your own file random.py shadows the module, so import random loads your file and random.randint fails with an AttributeError - rename the file and delete __pycache__. Use random.seed(42) only when you want the same sequence every run (tests, simulations).

import random

random.seed(42)       # reproducible sequence
print(random.randint(1, 6))

Python Questions

How do I import random in Python?

Write import random at the top of your file. It is part of the standard library, so there is nothing to install; then call random.randint(1, 10), random.random() or random.choice(list).

How do I generate a random number between 1 and 10 in Python?

Use random.randint(1, 10) - both 1 and 10 can come up. For a secure value use secrets.randbelow(10) + 1.

What is the difference between randint and randrange?

random.randint(a, b) includes b; random.randrange(a, b) excludes b, like range(), and also accepts a step.

Is Python random secure?

No. The random module is predictable and must not be used for passwords or tokens; use the secrets module instead.

Random Numbers in JavaScript

How to generate a random number in JavaScript: Math.random() for UI and games, the Web Crypto API for anything security-related.

JavaScript: Random Integer Between Min and Max

Math.random() returns a float in [0, 1). Multiply by the number of possible values, floor it, and add the minimum.

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min; // min..max inclusive
}

randomInt(1, 10);

JavaScript: Random Float

Scale Math.random() to any range of decimals.

Math.random();                       // 0 <= x < 1
const x = Math.random() * (5 - 1.5) + 1.5; // 1.5 <= x < 5

JavaScript: Random Array Element and Shuffle

Pick an index at random, or shuffle with Fisher-Yates - sorting with () => Math.random() - 0.5 gives a biased order.

const items = ["red", "green", "blue", "yellow"];
const pick = items[Math.floor(Math.random() * items.length)];

// Fisher-Yates shuffle (in place)
for (let i = items.length - 1; i > 0; i--) {
  const j = Math.floor(Math.random() * (i + 1));
  [items[i], items[j]] = [items[j], items[i]];
}

JavaScript: Secure Random Numbers

Math.random() is not cryptographically secure. For tokens, IDs and draws use the Web Crypto API (browsers and Node 19+), or crypto.randomInt in Node.

const bytes = crypto.getRandomValues(new Uint8Array(16)); // 16 random bytes
const id = crypto.randomUUID();                            // random UUID v4

// Node.js
const { randomInt } = require("node:crypto");
randomInt(1, 11); // 1..10 (upper bound exclusive)

JavaScript: Common Mistakes

Math.round(Math.random() * 10) makes 0 and 10 half as likely as the other values; Math.floor(Math.random() * 10) never returns 10. Use the floor formula with max - min + 1.

JavaScript Questions

How do I generate a random number between 1 and 10 in JavaScript?

Math.floor(Math.random() * 10) + 1 returns 1 to 10 inclusive. For a secure value use crypto.getRandomValues with rejection sampling, as in the generator above.

Is Math.random() secure?

No. Its output can be predicted, so never use it for passwords, tokens or session IDs; use crypto.getRandomValues or crypto.randomUUID.

How do I get a random element from an array?

items[Math.floor(Math.random() * items.length)].

How do I shuffle an array in JavaScript?

Use the Fisher-Yates algorithm shown above; sorting with a random comparator does not give every order the same probability.

Random Numbers in Java

How to generate a random number in Java: ThreadLocalRandom or java.util.Random for everyday use, SecureRandom for anything security-related.

Java: Random Int Between Min and Max

Upper bounds are exclusive in Java's random APIs, so add 1 to include the maximum.

import java.util.concurrent.ThreadLocalRandom;

int n = ThreadLocalRandom.current().nextInt(1, 11); // 1..10

import java.util.Random;

Random random = new Random();
int m = random.nextInt(10) + 1;                       // 1..10

Java: Random Double

nextDouble() returns a value in [0.0, 1.0).

double d = ThreadLocalRandom.current().nextDouble();          // 0.0 <= d < 1.0
double e = ThreadLocalRandom.current().nextDouble(1.5, 4.5);   // 1.5 <= e < 4.5

Java: Random Element and Shuffle

Pick by index, or shuffle a list with Collections.shuffle.

List<String> items = new ArrayList<>(List.of("red", "green", "blue"));
String pick = items.get(ThreadLocalRandom.current().nextInt(items.size()));
Collections.shuffle(items);                      // in place
Collections.shuffle(items, new SecureRandom());  // secure shuffle

Java: Secure Random Numbers with SecureRandom

java.util.Random is predictable. Use SecureRandom for passwords, tokens and draws - create it once and reuse it.

import java.security.SecureRandom;

SecureRandom secure = new SecureRandom();
int n = secure.nextInt(10) + 1;   // 1..10
byte[] token = new byte[16];
secure.nextBytes(token);

Java: Common Mistakes

Math.abs(random.nextInt()) % n can return a negative number (the absolute value of Integer.MIN_VALUE is still negative) and is biased - use nextInt(n). Creating a new Random on every call wastes time; reuse one instance or use ThreadLocalRandom.

Java Questions

How do I generate a random number between 1 and 10 in Java?

ThreadLocalRandom.current().nextInt(1, 11) - the upper bound is exclusive, so 11 makes 10 possible. With java.util.Random: random.nextInt(10) + 1.

How do I import Random in Java?

Add import java.util.Random; (or import java.util.concurrent.ThreadLocalRandom; or import java.security.SecureRandom;) at the top of the file.

What is the difference between Random and SecureRandom?

Random is fast but predictable; SecureRandom draws from a cryptographically secure source and is the one to use for tokens and passwords.

Is nextInt(bound) inclusive?

No. nextInt(bound) returns 0 to bound - 1, and nextInt(origin, bound) excludes bound.

Random Numbers in C#

How to generate a random number in C#: Random.Shared for everyday use, RandomNumberGenerator for anything security-related.

C#: Random Int Between Min and Max

Next(minValue, maxValue) excludes maxValue, so add 1 to include it. Random.Shared is thread-safe (.NET 6+).

int n = Random.Shared.Next(1, 11);   // 1..10
int m = Random.Shared.Next(10);      // 0..9

C#: Random Double

NextDouble() returns a value in [0.0, 1.0).

double d = Random.Shared.NextDouble();             // 0.0 <= d < 1.0
double e = 1.5 + Random.Shared.NextDouble() * 3.0;  // 1.5 <= e < 4.5

C#: Random Element and Shuffle

Pick by index; .NET 8 added Shuffle on both Random and RandomNumberGenerator.

string[] items = { "red", "green", "blue" };
string pick = items[Random.Shared.Next(items.Length)];
Random.Shared.Shuffle(items);              // .NET 8+
RandomNumberGenerator.Shuffle(items.AsSpan()); // secure, .NET 8+

C#: Secure Random Numbers

System.Random is predictable. For tokens, passwords and draws use System.Security.Cryptography.RandomNumberGenerator.

using System.Security.Cryptography;

int n = RandomNumberGenerator.GetInt32(1, 11);  // 1..10
byte[] token = RandomNumberGenerator.GetBytes(16);

C#: Common Mistakes

On .NET Framework, creating several new Random() in quick succession can give them the same time-based seed and identical sequences - use one shared instance (or Random.Shared on .NET 6+).

C# Questions

How do I generate a random number between 1 and 10 in C#?

Random.Shared.Next(1, 11) - the upper bound is exclusive. For a secure value: RandomNumberGenerator.GetInt32(1, 11).

Is System.Random secure?

No. Use RandomNumberGenerator for anything security-related.

Why does my C# Random return the same numbers?

On .NET Framework, Random instances created at almost the same moment get the same seed. Reuse a single instance or use Random.Shared.

Is Random.Next upper bound inclusive?

No. Next(min, max) returns min to max - 1.

Random Numbers in Go

How to generate a random number in Go: math/rand/v2 for everyday use, crypto/rand for anything security-related.

Go: Random Int in a Range

rand.IntN(n) returns 0 to n-1; add the minimum to shift the range. math/rand/v2 (Go 1.22+) is seeded automatically.

import "math/rand/v2"

n := rand.IntN(10) + 1 // 1..10

Go: Random Float

rand.Float64() returns a value in [0.0, 1.0).

f := rand.Float64()            // 0.0 <= f < 1.0
g := 1.5 + rand.Float64()*3.0  // 1.5 <= g < 4.5

Go: Random Element and Shuffle

Pick by index; rand.Shuffle swaps elements through a callback.

items := []string{"red", "green", "blue"}
pick := items[rand.IntN(len(items))]
rand.Shuffle(len(items), func(i, j int) {
	items[i], items[j] = items[j], items[i]
})

Go: Secure Random Numbers with crypto/rand

math/rand is not suitable for secrets. crypto/rand reads from the operating system CSPRNG; rand.Int returns an unbiased value below a big.Int limit.

import (
	"crypto/rand"
	"math/big"
)

v, err := rand.Int(rand.Reader, big.NewInt(10)) // 0..9
if err != nil {
	panic(err)
}
n := v.Int64() + 1 // 1..10

buf := make([]byte, 16)
_, _ = rand.Read(buf) // 16 random bytes

Go: Common Mistakes

With the original math/rand before Go 1.20, forgetting rand.Seed gave the same sequence on every run; math/rand/v2 removes that trap. Never use math/rand for tokens or keys.

Go Questions

How do I generate a random number between 1 and 10 in Go?

rand.IntN(10) + 1 with math/rand/v2. For a secure value use crypto/rand: rand.Int(rand.Reader, big.NewInt(10)), then add 1.

Do I need to seed math/rand in Go?

Not with math/rand/v2 or with math/rand since Go 1.20: both are seeded automatically.

Is math/rand secure?

No. Use crypto/rand for anything security-related.

Is rand.IntN(n) inclusive?

No. It returns 0 to n - 1.

Random Numbers in PHP

How to generate a random number in PHP: random_int() is both easy and cryptographically secure, so it is the right default.

PHP: Random Integer in a Range

random_int($min, $max) includes both ends and is cryptographically secure (PHP 7+). mt_rand is faster but predictable; rand() is an alias of it since PHP 7.1.

$n = random_int(1, 10);  // 1..10, secure
$m = mt_rand(1, 10);     // 1..10, not secure

PHP: Random Float

PHP 8.3 added Random\Randomizer::getFloat; before that, divide mt_rand() by mt_getrandmax().

$r = new \Random\Randomizer();
$f = $r->getFloat(1.5, 4.5);          // PHP 8.3+
$g = mt_rand() / mt_getrandmax();      // 0.0 <= g <= 1.0

PHP: Random Element and Shuffle

array_rand and shuffle use the non-secure generator; Random\Randomizer (PHP 8.2+) defaults to the secure engine.

$items = ["red", "green", "blue"];
$pick = $items[array_rand($items)];                     // not secure
$securePick = $items[random_int(0, count($items) - 1)];   // secure
shuffle($items);                                         // not secure
$shuffled = (new \Random\Randomizer())->shuffleArray($items); // secure, PHP 8.2+

PHP: Secure Tokens and Strings

For tokens, reset links and API keys, generate random bytes and encode them.

$token = bin2hex(random_bytes(16)); // 32 hex characters

PHP: Common Mistakes

uniqid() is based on the clock, not random - never use it for tokens. Neither rand() nor mt_rand() is safe for passwords or tokens; random_int and random_bytes are.

PHP Questions

How do I generate a random number between 1 and 10 in PHP?

random_int(1, 10) - both ends are included and the result is cryptographically secure.

What is the difference between rand, mt_rand and random_int?

rand is an alias of mt_rand since PHP 7.1; both are fast but predictable. random_int uses a cryptographically secure source.

How do I generate a random string in PHP?

bin2hex(random_bytes(16)) gives 32 secure hex characters.

Is random_int inclusive?

Yes, random_int($min, $max) can return both $min and $max.

Random Numbers in Bash

How to generate a random number in Bash: $RANDOM for quick scripts, shuf or /dev/urandom for wider ranges and anything security-related.

Bash: Random Number in a Range

$RANDOM returns 0 to 32767 in Bash (not in plain sh). The modulo trick is slightly biased and limited to 32768 values; shuf has neither problem.

echo $(( RANDOM % 10 + 1 ))   # 1..10, quick and slightly biased
shuf -i 1-10 -n 1              # 1..10
shuf -i 1-1000000 -n 5         # five different numbers

Bash: Random Line from a File

shuf also picks lines.

shuf -n 1 names.txt     # one random line
shuf names.txt          # whole file in random order

Bash: Secure Random Numbers and Strings

Read from the kernel CSPRNG for anything security-related.

od -An -N4 -tu4 /dev/urandom                  # random 32-bit unsigned integer
shuf -i 1-10 -n 1 --random-source=/dev/urandom
openssl rand -hex 16                          # 32 hex characters
head -c 16 /dev/urandom | base64

Bash: Common Mistakes

$RANDOM does not exist in /bin/sh on systems where sh is dash (Debian, Ubuntu) - run the script with bash. On macOS, shuf comes from GNU coreutils (installed as gshuf).

Bash Questions

How do I generate a random number between 1 and 10 in Bash?

shuf -i 1-10 -n 1, or echo $(( RANDOM % 10 + 1 )) for a quick, slightly biased value.

What is the range of $RANDOM?

0 to 32767.

How do I generate a secure random number in Bash?

Read from /dev/urandom, for example od -An -N4 -tu4 /dev/urandom, or use shuf with --random-source=/dev/urandom.

How do I generate a random string in Bash?

openssl rand -hex 16, or head -c 16 /dev/urandom | base64.

Frequently Asked Questions

How do I generate a random number in code? ▶
Every language has a built-in function: random.randint in Python, Math.random in JavaScript, ThreadLocalRandom in Java, Random.Shared in C#, math/rand/v2 in Go, random_int in PHP and $RANDOM in Bash. Use the secure variant for anything security-related.
Which random functions are cryptographically secure? ▶
Python secrets, JavaScript crypto.getRandomValues, Java SecureRandom, C# RandomNumberGenerator, Go crypto/rand, PHP random_int and random_bytes, and /dev/urandom on Linux and macOS.
Why is my random number never equal to the maximum? ▶
Many APIs exclude the upper bound - Java nextInt, C# Next, Go IntN, Python randrange. Add 1 to the maximum to include it.

[ HOW TO CITE THIS PAGE ]

APA Style:
Generate-Random.org. (2026). Random Number Code Generator. Retrieved from https://generate-random.org/random-number-code
Web Citation:
Random Number Code Generator - Generate-Random.org (https://generate-random.org/random-number-code)