Original code copyright (C) 2009-2022 Rudolf Cardinal (

This file is part of cardinal_pythonlib.

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Support functions regarding NHS numbers, etc.

cardinal_pythonlib.nhs.generate_nhs_number_from_first_9_digits(first9digits: str) int | None[source]

Returns a valid NHS number, as an int, given the first 9 digits. The particular purpose is to make NHS numbers that look fake (rather than truly random NHS numbers which might accidentally be real).

For example:

123456789_ : no; checksum 10
987654321_ : yes, valid if completed to 9876543210
999999999_ : yes, valid if completed to 9999999999

But see also generate_random_nhs_number() with its option to use the official NHS test range.

cardinal_pythonlib.nhs.generate_random_nhs_number(official_test_range: bool = True) int[source]

Returns a random valid NHS number, as an int.


official_test_range – Make it start with “999”, the official NHS test range. See, saved at

cardinal_pythonlib.nhs.is_test_nhs_number(n: int) bool[source]

Is this number both valid and in the official test range (starting 999)? See reference above.

cardinal_pythonlib.nhs.is_valid_nhs_number(n: int) bool[source]

Validates an integer as an NHS number.


n – NHS number



Checksum details are at;

cardinal_pythonlib.nhs.nhs_check_digit(ninedigits: str | List[int | str]) int[source]

Calculates an NHS number check digit.


ninedigits – string or list


check digit


  1. Multiply each of the first nine digits by the corresponding digit weighting (see NHS_DIGIT_WEIGHTINGS).

  2. Sum the results.

  3. Take remainder after division by 11.

  4. Subtract the remainder from 11

  5. If this is 11, use 0 instead If it’s 10, the number is invalid If it doesn’t match the actual check digit, the number is invalid

This function will return 10 for some values, but that is invalid; it’s up to the caller to check.

cardinal_pythonlib.nhs.nhs_number_from_text_or_none(s: str) int | None[source]

Returns a validated NHS number (as an integer) from a string, or None if it is not valid.

It’s a 10-digit number, so note that database 32-bit INT values are insufficient; use BIGINT. Python will handle large integers happily.

NHS number rules:

cardinal_pythonlib.nhs.test_nhs_rng(n: int = 100) None[source]

Tests the NHS random number generator.