Last Updated: June 01, 2026
- Generating the same random number each time and why this matters
- Python Random Number Between 1 and 10
- Python Generate Random Numbers From A Range
- Generate Random String Of Length n in Python
- Random Choice Without Replacement In Python
- Generate Date Between Two Dates in Python
- Generate Random Temporary Filename in Python
- Conclusion
- Subscribe
- Related Articles
- Frequently Asked Questions
Generating random numbers in Python is a fairly straightforward activity which can be done in a few lines. There maybe many variations which you need to do ranging from decimal places, random numbers between a start and end number, and many more. We’ll go through many useful examples in this article.
The most basic way to generate random numbers in python is with the random library:
import random
num = random.random()
print( f"Random number between 0.0 and 1.0 ={num}\n")
Output as follows:

You’ll see that each time it is run it has a new random number.
Python developer and educator with 15+ years building production systems across data engineering, web APIs, and AI tooling. Founder of Python How To Program — 270+ in-depth tutorials covering the modern Python stack.
Generating the same random number each time and why this matters
Sometimes, you may want to generate some random numbers, but then be able to generate the same random numbers each time. Now this may sound counter intuitive as the whole point of getting random numbers is so that, well, they are random. One scenario where you would like to regenerate the same random numbers is during testing. You may find some unusual behaviour and this is where you may want to replicate that behaviour for which you’l l need the same input. This is where you’d want to generate the same random number and you can do that in python using the seed function from the random library.
The idea behind the seed function is that you can think of it as a specific key which can be used to generate a series of random numbers which stems from a given key. Use a different seed and you’ll generate a different set of random numbers.
See the following example code which generates a random number between 1 and 0:
import random
random.seed(1)
for i in range(1,5):
num = random.random()
print( f"Random number between 0.0 and 1.0 ={num}\n")
Output as follows:

No matter how many times it is run, since the seed is the same each time, it generates the same numbers.
Python Random Number Between 1 and 10
Now that we know how to generate random numbers, how do you do it between two numbers? This is easily done in with either randint() for whole numbers or with uniform() for decimal numbers.
import random
num_int = random.randint(1,10)
print( f"Random whole number between 1 and 10 ={num_int}\n")
num_uni = random.uniform(1,10)
print( f"Random decimal number between 1 and 10 ={num_uni}\n")

Python Generate Random Numbers From A Range
Suppose you needed to generate random numbers from a range of data whether that be numbers, names or even a pack of cards. This can be done through selecting the random element in an array by choosing the index randomly. For example, if you had an array of 5 items, then you can randomly chose and index from 0 to 4 (where 0 is the index of the first item).
There is another and shorter way in python which is to use the random.choice() function. If you pass it an array, it will then randomly return one of the elements.
Here’s an example to randomly select a name from a list with both using the index (to show you how it works), and the much most efficient random.choice() library function:
import random
###### Selecing numbers from a range
names_list = [ "Judy", "Harry", "Sarah", "Tom", "Gloria"]
rand_index = random.randint( 0, len(names_list)-1 )
print( f"Randomly selected person 1 is = { names_list[ rand_index] }\n")
print( f"Randomly selected person 2 is = { random.choice( names_list) }\n")
And the output is different each time:

Generate Random String Of Length n in Python
If you want to generate a specific length string (e.g. to generate a password), both the random and the string libraries can come in handy where you can use it to create an easy password generator as follows:
import random, string
###### Create a random password
def generate_password( pass_len=10):
password = ""
for i in range(1,pass_len+1):
password = password + random.choice( string.ascii_letters + string.punctuation )
return password
print( f"Password generated = [{ generate_password(10) }] ")
This will output a new password each time between square brackets:

If there are specific characters you want to include or exclude, you can simply replace the string.punctuation with your own list/array of specific characters to be included
Random Choice Without Replacement In Python
Suppose you wanted to randomly select items from a list without repeating any items. For example, you have a list of students and you have to select them in a random order to go first in a specific activity. In many programming languages you may need to generate a random list and remember the previously selected items to prevent any repeated selections. In the random library, there is a function called random.sample() that will do all that for you:
import random
#### Select unique random elements
students = ["John", "Tom", "Paul", "Sarah", "July", "Rachel"]
random_order = random.sample( students, 6)
print(random_order)
This will generate a unique list without repeating any selections:

Sign up to the email list and get articles straight to your inbox. Plus get our free python one liner list!
” list=”237850″ redirect=”https://pythonhowtoprogram.com/thank-you-for-subscribing/” check_last_name=”off” layout=”top_bottom” first_name_fullwidth=”off” email_fullwidth=”off” _builder_version=”4.17.4″ _module_preset=”default” body_font=”|700|||||||” body_line_height=”1em” result_message_font=”|700|||||||” body_ul_line_height=”0.1em” custom_button=”on” button_bg_color=”#0C71C3″ button_border_color=”#FFFFFF” button_border_radius=”20px” button_letter_spacing=”0px” button_font=”|800|||||||” button_use_icon=”off” button_custom_margin=”0px||||false|false” button_custom_padding=”1px|1px|1px|1px|false|false” text_orientation=”center” background_layout=”light” custom_padding=”20px|30px|20px|30px|false|false” hover_enabled=”0″ border_radii=”on|3px|3px|3px|3px” box_shadow_style_button=”preset2″ box_shadow_vertical_button=”2px” global_colors_info=”{}” sticky_enabled=”0″][/mfe_send_fox]
Generate Date Between Two Dates in Python
In order to generate a date between two dates, this can be done by converting the dates into days first. This can be combined with the random.randint() in addition to the days of the date differences then adding back to the start date:
import random, datetime
#### Select a random date between two dates:
d1 = datetime.date( 2013, 2, 26 )
d2 = datetime.date( 2015, 12, 15 )
diff = d2 - d1
new_date_days = random.randint( 0, diff.days )
print( f"Random date is { d1 + datetime.timedelta( days=new_date_days ) }")
The output would be as follows:

Generate Random Temporary Filename in Python
A common need is to generate a random filename often for temporary storage. This might be for a log file, a cache file or some other scenario and can be easily done with the similar string generation as above. First a letter should be determined and then the remaining letters can be added with also numbers as well.
import random, string
def generate_random_filename( filename_len=10):
filename = ""
filename = filename + random.choice( string.ascii_lowercase )
for i in range(2, filename_len+1):
filename = filename + random.choice( string.ascii_lowercase + string.digits )
return filename
print( f"Random filename = [{ generate_random_filename( 10) }.txt]")
Output as follows:

There is in fact a specific python library though that does this which is even simpler:
import tempfile
filename = tempfile.NamedTemporaryFile( prefix="temp_" , suffix =".txt" )
print( f" Temporary filename is [{ filename.name }] ")
Output of the temporary filename generator is:

Conclusion
The random library has many uses from generating numbers to specific strings with a given length for password generation. Typically, these use cases sometimes have specialised libraries as there can be nuances (e.g for passwords, you may not want a repeating sequence which may be possible through random luck) which you can search for through pypi.org. However, many can be created with simple lines of code as demonstrated above. Send comments below or email me to ask further questions.
Subscribe
Not subscribed to our email list? Sign up now and get your next article in your inbox:
Related Articles
How To Use Python ward for Modern Python Testing
Intermediate
You have written enough test_something functions to last a lifetime. Your test files are full of names like test_user_creation_when_email_is_valid_and_age_is_over_18 — forty characters of snake_case just to describe one behaviour. When a test fails, the output tells you the function name but not what the test was actually checking. You end up reading the function body to figure it out, which defeats the point of a test name entirely.
Python’s ward library takes a different approach. Instead of naming test functions, you describe them — passing a plain English string to the @test decorator. When a test fails, ward prints exactly what it was supposed to do, in the language you wrote it, not a slug-cased identifier. The library also ships with a fixture system built on function arguments, a fluent expect() assertion API, and parameterized tests that read like a table of examples. Install it with pip install ward — no extra dependencies.
This article walks you through everything you need to use ward effectively. We will cover writing your first tests with the @test decorator, organizing shared setup with @fixture, running parameterized test cases, using the expect() assertion chain, and building a real-world test suite for a small utility library. By the end, you will have a working test suite and a clear picture of where ward fits against pytest.
Writing a ward Test: Quick Example
Before diving into the details, here is a minimal ward test file you can run right now. Create a file called test_math.py and paste in the following:
# test_math.py
from ward import test
@test("adding two positive integers returns their sum")
def _():
assert 1 + 2 == 3
@test("dividing by zero raises ZeroDivisionError")
def _():
try:
_ = 10 / 0
assert False, "should have raised"
except ZeroDivisionError:
pass
Run it with:
ward
Output:
PASS test_math adding two positive integers returns their sum
PASS test_math dividing by zero raises ZeroDivisionError
2 passed in 0.02 seconds
Two things stand out immediately. First, every test function is named _ — the name is irrelevant because ward uses the string you pass to @test instead. Second, the output reads like a sentence, not a mangled identifier. Those two changes alone make failing tests much easier to diagnose at a glance.
The sections below explain each ward feature in depth and show you how to apply them to realistic code.
What Is ward and Why Use It?
Ward is a Python testing framework designed to make test code more readable and test output more useful. It was created as an alternative to pytest and unittest, borrowing the best ideas from both while rethinking the parts that have always felt awkward — especially test naming and fixture injection.
The central idea is that a test is a fact you assert about your code, and that fact deserves to be written in human language. In pytest you write def test_cart_total_is_zero_when_no_items_added():. In ward you write @test("cart total is zero when no items are added"). The string is the documentation; the function body is the proof.
Here is how ward compares to pytest on the features most Python developers care about:
| Feature | pytest | ward |
|---|---|---|
| Test description | Function name (snake_case) | Plain English string |
| Fixtures | @pytest.fixture | @fixture with argument injection |
| Parameterization | @pytest.mark.parametrize | @using with each() |
| Assertions | assert (with rewriting) | assert or fluent expect() |
| Output format | Dots, F, E characters + tracebacks | Coloured PASS/FAIL lines with descriptions |
| Installation | pip install pytest | pip install ward |
Ward is not trying to replace pytest in every project — it is a deliberate choice that pays off most when you want test output to function as living documentation. If you share test runs with non-developers or treat CI output as a changelog, ward’s readable output earns its place immediately.
Installing ward
Ward requires Python 3.6 or later. Install it into your project’s virtual environment:
# install.sh
pip install ward
Verify the installation:
# verify_install.py
import ward
print(ward.__version__)
Output:
0.68.0b0
Ward discovers tests automatically. By default it searches for any file matching the pattern test_*.py in the current directory and its subdirectories — the same convention used by pytest. You can override the search path:
# Run all tests in a specific directory
ward --path tests/
# Run tests matching a keyword in their description
ward --search "total"
# Run tests in a single file
ward --path tests/test_cart.py
There is no configuration file required to get started. For larger projects, ward reads from a pyproject.toml [tool.ward] section if one exists.
Writing Tests with @test
The @test decorator is the foundation of every ward test suite. It takes a single string argument that describes what the test is verifying. The decorated function’s name is ignored entirely — the convention is to name every test function _ to make that clear.
# test_string_utils.py
from ward import test
def shout(text):
"""Convert text to uppercase with an exclamation mark."""
return text.upper() + "!"
@test("shout converts text to uppercase")
def _():
assert shout("hello") == "HELLO!"
@test("shout appends an exclamation mark")
def _():
result = shout("ward")
assert result.endswith("!")
@test("shout works on an already uppercase string")
def _():
assert shout("PYTHON") == "PYTHON!"
Output:
PASS test_string_utils shout converts text to uppercase
PASS test_string_utils shout appends an exclamation mark
PASS test_string_utils shout works on an already uppercase string
3 passed in 0.01 seconds
When a test fails, ward shows you the description, the file and line number, and the values that caused the failure. You get the “what failed” and “what were the values” without reading the traceback from the bottom up. That is a significant quality-of-life improvement when you have a large test suite and a CI run with dozens of failures.
Shared Setup with @fixture
Most tests need shared setup — a database connection, a sample data structure, or a configured object. Ward handles this with the @fixture decorator, which works very similarly to pytest fixtures. You declare a fixture function, then inject it into your test by using the fixture function as a default argument.
# test_user.py
from ward import test, fixture
@fixture
def sample_user():
return {
"name": "Alice",
"email": "alice@example.com",
"age": 25,
"active": True,
}
@test("user name is a string")
def _(user=sample_user):
assert isinstance(user["name"], str)
@test("user age is a positive integer")
def _(user=sample_user):
assert user["age"] > 0
@test("inactive users cannot be created with this fixture")
def _(user=sample_user):
assert user["active"] is True
Output:
PASS test_user user name is a string
PASS test_user user age is a positive integer
PASS test_user inactive users cannot be created with this fixture
3 passed in 0.01 seconds
The fixture function runs fresh for each test that uses it — there is no shared state between tests unless you explicitly use a module-level or session-level scope. To add teardown logic, use yield inside the fixture:
# test_file_fixture.py
import os
import tempfile
from ward import test, fixture
@fixture
def temp_file():
# Setup: create a temporary file
fd, path = tempfile.mkstemp(suffix=".txt")
os.close(fd)
with open(path, "w") as f:
f.write("hello ward")
yield path
# Teardown: delete the file after the test
if os.path.exists(path):
os.remove(path)
@test("temp file exists on disk")
def _(path=temp_file):
assert os.path.isfile(path)
@test("temp file contains the expected text")
def _(path=temp_file):
with open(path) as f:
content = f.read()
assert content == "hello ward"
Output:
PASS test_file_fixture temp file exists on disk
PASS test_file_fixture temp file contains the expected text
2 passed in 0.03 seconds
The code after yield runs automatically after each test that uses temp_file. Ward handles the teardown even if the test throws an exception, so you do not need try/finally blocks in your test functions.
Parameterized Tests with @using and each()
Parameterized tests let you run the same logic against multiple inputs without duplicating code. Ward’s approach is cleaner than pytest’s marker syntax — you use the @using decorator combined with the each() helper to define the value sets.
# test_math_ops.py
from ward import test, each, using
def clamp(value, lo, hi):
"""Clamp value to the range [lo, hi]."""
return max(lo, min(hi, value))
@test("clamp({value}, {lo}, {hi}) returns {expected}")
@using(
value=each(5, -3, 100, 50),
lo=each(0, 0, 0, 0),
hi=each(10, 10, 10, 10),
expected=each(5, 0, 10, 10),
)
def _(value, lo, hi, expected):
assert clamp(value, lo, hi) == expected
Output:
PASS test_math_ops clamp(5, 0, 10) returns 5
PASS test_math_ops clamp(-3, 0, 10) returns 0
PASS test_math_ops clamp(100, 0, 10) returns 10
PASS test_math_ops clamp(50, 0, 10) returns 10
4 passed in 0.01 seconds
Notice that ward interpolates the parameter values into the test description for each run. When one case fails, the output tells you exactly which input caused the problem — clamp(100, 0, 10) returns 10 is far more useful than test_clamp_params[2].
The each() values are matched positionally — the first value from every each() forms the first test case, the second values form the second, and so on. All each() calls in one @using decorator must have the same length.
Fluent Assertions with expect()
Ward provides an optional fluent assertion API called expect(). Instead of writing bare assert statements, you chain methods that read like English and produce more specific error messages when they fail. Use whichever style you prefer — both work the same way under the hood.
# test_expect.py
from ward import test, expect
@test("expect: integer is within range")
def _():
expect(42).to_be_greater_than(40)
expect(42).to_be_less_than(50)
@test("expect: string contains a substring")
def _():
expect("pythonhowtoprogram").to_contain("python")
@test("expect: list has expected length")
def _():
items = ["a", "b", "c"]
expect(items).has_length(3)
@test("expect: dictionary contains a key")
def _():
config = {"debug": True, "timeout": 30}
expect(config).to_contain_key("debug")
@test("expect: value is an instance of a type")
def _():
expect(3.14).to_be_instance_of(float)
Output:
PASS test_expect expect: integer is within range
PASS test_expect expect: string contains a substring
PASS test_expect expect: list has expected length
PASS test_expect expect: dictionary contains a key
PASS test_expect expect: value is an instance of a type
5 passed in 0.02 seconds
When an expect() assertion fails, ward reports both the expected condition and the actual value on separate lines. For example, if expect(15).to_be_greater_than(40) fails, the output reads Expected 15 to be greater than 40 — no need to open the test file and read the assert statement.
The expect() API supports chaining, so you can write several assertions about the same value in sequence. This is useful when a single test function validates multiple properties of one object, and you want each failure to be described independently.
Real-Life Example: Testing a Shopping Cart
Let us build a test suite for a simple shopping cart module using everything covered above: fixtures for shared state, parameterized tests for pricing logic, and expect() for readable assertions.
First, the module under test:
# cart.py
class Cart:
"""A simple shopping cart with item management and total calculation."""
def __init__(self):
self._items = {} # name -> {"price": float, "qty": int}
def add(self, name, price, qty=1):
if name in self._items:
self._items[name]["qty"] += qty
else:
self._items[name] = {"price": price, "qty": qty}
def remove(self, name):
self._items.pop(name, None)
def total(self, tax_rate=0.0):
subtotal = sum(v["price"] * v["qty"] for v in self._items.values())
return round(subtotal * (1 + tax_rate), 2)
def item_count(self):
return sum(v["qty"] for v in self._items.values())
def is_empty(self):
return len(self._items) == 0
Now the ward test suite:
# test_cart.py
from ward import test, fixture, expect, each, using
from cart import Cart
# ----- Fixtures -----
@fixture
def empty_cart():
return Cart()
@fixture
def stocked_cart():
c = Cart()
c.add("apple", price=0.99, qty=3)
c.add("bread", price=2.49)
c.add("milk", price=1.75, qty=2)
return c
# ----- Basic behaviour -----
@test("a new cart is empty")
def _(cart=empty_cart):
expect(cart.is_empty()).to_be_truthy()
expect(cart.item_count()).equals(0)
@test("adding an item increases item count")
def _(cart=empty_cart):
cart.add("apple", price=0.99, qty=4)
expect(cart.item_count()).equals(4)
@test("adding the same item twice increases quantity not entry count")
def _(cart=empty_cart):
cart.add("apple", 0.99, qty=1)
cart.add("apple", 0.99, qty=2)
expect(cart.item_count()).equals(3)
@test("removing an item reduces total")
def _(cart=stocked_cart):
before = cart.total()
cart.remove("bread")
expect(cart.total()).to_be_less_than(before)
# ----- Total calculation (parameterized) -----
@test("total with {rate*100:.0f}% tax is {expected}")
@using(
rate=each(0.0, 0.1, 0.2),
expected=each(9.46, 10.41, 11.35),
)
def _(cart=stocked_cart, rate=None, expected=None):
# stocked: 3*0.99 + 1*2.49 + 2*1.75 = 9.46 subtotal
expect(cart.total(tax_rate=rate)).equals(expected)
Output:
PASS test_cart a new cart is empty
PASS test_cart adding an item increases item count
PASS test_cart adding the same item twice increases quantity not entry count
PASS test_cart removing an item reduces total
PASS test_cart total with 0% tax is 9.46
PASS test_cart total with 10% tax is 10.41
PASS test_cart total with 20% tax is 11.35
7 passed in 0.03 seconds
The test suite demonstrates three things at once: the stocked_cart fixture gives each test a fresh, pre-populated cart without any shared mutation; the parameterized tax tests cover three pricing scenarios without duplicated code; and the expect() calls make each assertion readable without a comment explaining what is being checked. To extend the example, try adding tests for negative quantities, zero-price items, or a discount() method — the fixture and parameterization patterns scale without any structural changes.
Frequently Asked Questions
Can ward tests coexist with pytest tests in the same project?
Yes, but they run in separate commands. Ward discovers test_*.py files using the same convention as pytest, but the two runners are independent — running ward only executes tests decorated with @test, and running pytest only executes functions prefixed with test_. If you are migrating gradually, you can keep both frameworks active during the transition. Ward can also use pytest fixtures defined in a conftest.py file, which eases migration considerably.
How do fixture scopes work in ward?
Ward fixtures support four scopes: Scope.Test (default, reruns for every test), Scope.Module (reruns once per test file), Scope.Global (reruns once per entire test run), and Scope.Call (same as Test). Set the scope with @fixture(scope=Scope.Module). Use module or global scope for expensive operations like database connections or API clients that you do not want to recreate thousands of times.
Should I use expect() or plain assert statements?
Both work correctly and produce useful output. The expect() API gives you method names that double as documentation — expect(value).to_be_greater_than(10) is self-explanatory even in a code review. Plain assert is faster to type and feels more natural if you are coming from pytest. A common middle ground: use assert for straightforward equality checks and expect() when comparing ranges, types, or collection membership where the error message matters most.
How do I run a single test or a subset of tests?
Use the --search flag to filter by description substring: ward --search "cart total" will run every test whose description contains “cart total”. You can also use --path tests/test_cart.py to restrict the discovery scope to a single file. For more precise control, ward supports tags via @test("...", tags=["slow"]) combined with ward --tags slow on the command line.
Does ward support async tests?
Yes. Ward automatically detects async def test functions and fixture functions and runs them using asyncio.run(). You do not need any plugin or marker — just write async def _(): and ward handles the event loop. This works the same way for fixtures, so an async fixture can await a database connection and yield it to an async test without any additional setup.
How do I get code coverage with ward?
Run ward under coverage using the standard coverage.py wrapper: coverage run -m ward. After the run completes, generate the report with coverage report or coverage html for a browsable HTML breakdown. Ward does not bundle its own coverage tool — it relies on coverage.py, which is the same approach pytest recommends and integrates cleanly with CI pipelines and codecov.io.
Conclusion
Python ward replaces the test-naming ceremony of traditional frameworks with something more direct: a plain English description that appears in every test report, every CI log, and every team standup where someone asks “what broke?” The @test decorator, @fixture injection, @using parameterization, and the expect() assertion chain all work together to make tests read like specifications and failures read like bug reports.
The shopping cart example in this article covers the core patterns you will reach for in a real project. Try extending it — add a coupon fixture that returns a discount function, write parameterized tests for boundary cases like zero-quantity items, or switch the Cart storage to a database and test the async fixture pattern. Each of those extensions fits naturally into the structure already in place.
For the full API reference, see the official ward documentation at ward.readthedocs.io. The project is also actively maintained on GitHub at github.com/darrenburns/ward, where you can find the changelog and open issues.
Related Articles
Further Reading: For more details, see the Python random module documentation.
Frequently Asked Questions
How do I generate a random number in Python?
Use random.randint(a, b) for integers or random.random() for a float between 0 and 1. Example: import random; num = random.randint(1, 100).
What is the difference between random and secrets?
The random module is for simulations and games but NOT for security. The secrets module provides cryptographically secure randomness for passwords, tokens, and security-sensitive applications.
How do I generate a random list of numbers?
Use [random.randint(1, 100) for _ in range(10)] for random integers. For unique numbers, use random.sample(range(1, 101), 10). For float arrays, use numpy.random.rand(10).
How do I set a random seed?
Call random.seed(42) before generating numbers. The same seed always produces the same sequence, useful for testing and reproducible experiments.
Can I generate numbers following a specific distribution?
Yes. Use random.gauss() for normal, random.uniform() for uniform. NumPy offers numpy.random.normal(), poisson(), binomial(), and many more.
Continue Learning Python
Tutorials you might also find useful: