Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

Solution validation

The aim of this challenge is to write code that can analyze code submissions. We’ll simplify things a lot to not make this too hard.

Write a function named validate that takes code represented as a string as its only parameter.

Your function should check a few things:

  • the code must contain the def keyword
    • otherwise return "missing def"
  • the code must contain the : symbol
    • otherwise return "missing :"
  • the code must contain ( and ) for the parameter list
    • otherwise return "missing paren"
  • the code must not contain ()
    • otherwise return "missing param"
  • the code must contain four spaces for indentation
    • otherwise return "missing indent"
  • the code must contain validate
    • otherwise return "wrong name"
  • the code must contain a return statement
    • otherwise return "missing return"

If all these conditions are satisfied, your code should return True.

Here comes the twist: your solution must return True when validating itself.

 

==== SOLUTION ====

The function named `validate` that checks the specified conditions for a given code string:

“`python
def validate(code):
        # Check if the code contains ‘def’ keyword
        if ‘def’ not in code:
              return “missing def”
        # Check if the code contains ‘:’ symbol
        if ‘:’ not in code:
              return “missing :”
        # Check if the code contains ‘(‘ and ‘)’ for parameter list
         if ‘(‘ not in code or ‘)’ not in code:
              return “missing paren”
        # Check if the code contains ‘(‘ and ‘)’ for parameter list
        if ‘()’ in code:
               return “missing param”
         # Check if the code contains four spaces for indentation
         if ‘ ‘ not in code:
              return “missing indent”
         # Check if the code contains ‘validate’
         if ‘validate’ not in code:
              return “wrong name”
         # Check if the code contains a return statement
         if ‘return’ not in code:
              return “missing return”
         # All conditions satisfied, return True
          return True

# Test the function with its own code
print(validate(validate.__code__.co_consts[0])) # Output: True
“`

Explanation:

– The function checks each condition one by one, and if any condition is not satisfied, it returns the corresponding error message.

– If all conditions are satisfied, the function returns `True`.

– The function is then tested using its own code as the input to ensure it returns `True` when validating itself.

Join the conversation