Random Number Generation and Person Data Model

  • Share this:

Code introduction


This code block contains two functions. The first function `generate_random_number_list` takes three parameters: the size of the list, the minimum value, and the maximum value, and returns a list of random integers within the specified range. The second function `Person` is a data model defined using Pydantic, which has three properties: `name`, `age`, and a validator to ensure that the age is between 0 and 120.


Technology Stack : Pydantic, random

Code Type : Function

Code Difficulty : Intermediate


                
                    
from pydantic import BaseModel, validator
from typing import List, Optional
import random

def generate_random_number_list(size: int, min_value: int = 1, max_value: int = 100):
    # This function generates a random list of integers of a specified size with a range of values.
    return [random.randint(min_value, max_value) for _ in range(size)]

class Person(BaseModel):
    name: str
    age: int
    # Validator to ensure age is between 0 and 120
    @validator('age')
    def check_age(cls, v):
        if not 0 <= v <= 120:
            raise ValueError('Age must be between 0 and 120')
        return v

# Example usage:
person_data = Person(name="Alice", age=30)
random_numbers = generate_random_number_list(size=5, min_value=10, max_value=50)