Bird
Raised Fist0
Agentic AIml~20 mins

Input validation and sanitization in Agentic AI - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Input Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why is input validation important in AI systems?

Imagine you have an AI model that predicts loan approvals. Why should you validate the input data before feeding it to the model?

ATo increase the size of the dataset by adding random values.
BTo make the model run faster by skipping some data points.
CTo ensure the data is clean and within expected ranges, preventing wrong predictions.
DTo avoid training the model on too much data.
Attempts:
2 left
💡 Hint

Think about what happens if the model gets unexpected or wrong data.

Predict Output
intermediate
2:00remaining
Output of input sanitization function

What is the output of this Python function that sanitizes input text by removing digits?

Agentic AI
def sanitize(text):
    return ''.join(c for c in text if not c.isdigit())

result = sanitize('Agent007 is ready!')
print(result)
AAgent is ready!
BAgent007 is ready!
C007 is ready!
DAgent is ready!
Attempts:
2 left
💡 Hint

Look at how digits are filtered out from the string.

Model Choice
advanced
2:00remaining
Choosing a model robust to noisy input data

You have input data that may contain some errors or noise. Which model type is best to handle this situation?

AA simple linear regression model without regularization
BA deep neural network with dropout and batch normalization
CA decision tree with no pruning
DA nearest neighbor model using raw input features
Attempts:
2 left
💡 Hint

Think about models that include techniques to reduce overfitting and handle noise.

Metrics
advanced
2:00remaining
Evaluating input sanitization impact on model accuracy

You trained two models: one on raw input data and one on sanitized input data. The sanitized model has 5% higher accuracy. What does this suggest?

ASanitizing input data improved data quality, helping the model learn better.
BAccuracy is not affected by input data quality.
CThe model with raw data is always better regardless of accuracy.
DSanitizing input data removed useful information, hurting the model.
Attempts:
2 left
💡 Hint

Think about how cleaning data affects learning.

🔧 Debug
expert
2:00remaining
Identifying input validation bug in AI pipeline

Consider this code snippet that validates numeric input features before prediction. What error will it raise?

Agentic AI
def validate_features(features):
    for key, value in features.items():
        if value < 0:
            raise ValueError(f"Negative value for {key}")

input_data = {'age': 25, 'income': -5000, 'score': 70}
validate_features(input_data)
ATypeError: unsupported operand type(s) for <: 'str' and 'int'
BNo error, function runs successfully
CKeyError: 'income'
DValueError: Negative value for income
Attempts:
2 left
💡 Hint

Check which input value is negative and what the function does.

Practice

(1/5)
1. What is the main purpose of input validation in machine learning systems?
easy
A. To train the model with new data
B. To clean the data by removing unwanted characters
C. To check if the input data is the correct type and format
D. To store data securely in a database

Solution

  1. Step 1: Understand input validation

    Input validation means checking if the data is the right type and format before using it.
  2. Step 2: Differentiate from sanitization

    Input sanitization cleans data, but validation focuses on correctness and format.
  3. Final Answer:

    To check if the input data is the correct type and format -> Option C
  4. Quick Check:

    Input validation = Check data type and format [OK]
Hint: Validation means checking data type and format [OK]
Common Mistakes:
  • Confusing validation with sanitization
  • Thinking validation trains the model
  • Assuming validation stores data
2. Which of the following is the correct way to validate that an input is a positive integer in Python?
easy
A. if isinstance(input_value, int) and input_value > 0:
B. if type(input_value) == 'int' and input_value > 0:
C. if input_value.isdigit() and input_value > 0:
D. if input_value > 0:

Solution

  1. Step 1: Check type correctly

    Use isinstance(input_value, int) to check if input is an integer.
  2. Step 2: Check positivity

    Ensure the integer is greater than zero with input_value > 0.
  3. Final Answer:

    if isinstance(input_value, int) and input_value > 0: -> Option A
  4. Quick Check:

    Use isinstance and > 0 for positive integer check [OK]
Hint: Use isinstance() to check type, then compare value [OK]
Common Mistakes:
  • Using type() == 'int' (wrong syntax)
  • Calling isdigit() on non-string input
  • Skipping type check before comparison
3. Given the code below, what will be the output?
def sanitize_input(text):
    return text.strip().lower()

user_input = '  Hello World!  '
cleaned = sanitize_input(user_input)
print(cleaned)
medium
A. Hello World!
B. !dlroW olleH
C. HELLO WORLD!
D. hello world!

Solution

  1. Step 1: Understand strip()

    The strip() method removes spaces from the start and end of the string.
  2. Step 2: Understand lower()

    The lower() method converts all letters to lowercase.
  3. Final Answer:

    hello world! -> Option D
  4. Quick Check:

    strip + lower = 'hello world!' [OK]
Hint: strip removes spaces, lower makes all letters small [OK]
Common Mistakes:
  • Ignoring strip() effect on spaces
  • Confusing lower() with upper()
  • Expecting original casing in output
4. Identify the error in this input validation code snippet:
def validate_age(age):
    if age.isdigit() and age > 0:
        return True
    else:
        return False
medium
A. Comparing string with integer using > operator
B. Using isdigit() on a non-string type
C. Missing return statement in else block
D. Function name is invalid

Solution

  1. Step 1: Check isdigit() usage

    isdigit() works on strings, so age should be a string here.
  2. Step 2: Identify type mismatch in comparison

    Comparing age > 0 compares string to int, which causes error.
  3. Final Answer:

    Comparing string with integer using > operator -> Option A
  4. Quick Check:

    String > int comparison causes error [OK]
Hint: Check types before comparing values [OK]
Common Mistakes:
  • Assuming isdigit() converts type
  • Ignoring type mismatch in comparisons
  • Thinking function name affects validation
5. You receive user data as a list of strings representing ages: ['25', ' 30', 'twenty', '40', '']. Which code snippet correctly validates and sanitizes this data to keep only valid positive integers?
hard
A. valid_ages = [age for age in ages if age.isdigit() and age > 0]
B. valid_ages = [int(age.strip()) for age in ages if age.strip().isdigit() and int(age.strip()) > 0]
C. valid_ages = [int(age) for age in ages if age.isnumeric()]
D. valid_ages = [int(age) for age in ages if age.strip() != '']

Solution

  1. Step 1: Sanitize input by stripping spaces

    Use age.strip() to remove spaces before validation.
  2. Step 2: Validate with isdigit() and positive check

    Check if stripped string is digits only and convert to int to check > 0.
  3. Step 3: Convert valid strings to integers

    Use int(age.strip()) to convert valid strings to integers.
  4. Final Answer:

    valid_ages = [int(age.strip()) for age in ages if age.strip().isdigit() and int(age.strip()) > 0] -> Option B
  5. Quick Check:

    Strip spaces, check digits, convert to int > 0 [OK]
Hint: Strip spaces before isdigit(), then convert and check > 0 [OK]
Common Mistakes:
  • Not stripping spaces before validation
  • Comparing strings directly to numbers
  • Including empty or non-digit strings