Lesson guide
What this Python exercise practices
Compute a square root with math is a beginner practice lesson that focuses on functions, parameters, return values. It is designed to be solved in about 10 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- Function parameters
- Return values
Difficulty and time
- Level
- Beginner
- Estimated time
- 10 minutes
Related public exercises
Summary
Use the math module to compute a square root and handle invalid inputs.
Problem statement
Implement a function sqrt(n) that returns the square root of n using math.sqrt. If n is negative, return None. Accept integers and floats. For zero, return 0.0. For invalid types, raise a TypeError (natural behavior is acceptable), but typical numeric inputs should be handled.
Task
Write a function that returns the square root of a non-negative number using math.sqrt; return None for negative inputs.
Examples
Perfect square
Input
sqrt(25)
Output
5.0
Explanation
Square root of 25 is 5.0.
Input format
Single numeric argument (int or float).
Output format
Return a float with the square root, or None for negative inputs.
Constraints
Use math.sqrt. Do not return complex numbers—return None instead for negatives.
Samples
Sample input 0
sqrt(2)
Sample output 0
1.4142135623730951
Explanation 0
Return the floating-point square root.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.