Program to calculate length of string using recursion
Detailed guide and Python implementation for the 'Program to calculate length of string using recursion' problem.
Problem Statement
Write a function string_length(s) that calculates and returns the length of the string s using recursion. You must NOT use the built-in len() function. The base case is an empty string which has length 0. For each recursive call, count one character and recurse on the remaining string.
- •0 <= len(s) <= 1000
- •s contains only printable ASCII characters
Examples
s = 'hello'
5
The string 'hello' has 5 characters: h, e, l, l, o.
s = 'python'
6
The string 'python' has 6 characters.
s = ''
0
An empty string has length 0.
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Strings
Master string manipulation in Python. Learn string methods, slicing, concatenation, and formatting techniques with clear, executable code examples.
How to Reverse a String in Python
Learn how to reverse a string in Python using slicing, the reversed() function, and loop concatenation with visual code examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python Decorators vs Decorator Design Pattern: The Key Differences
Compare Python decorators and the classic decorator design pattern. Understand the differences between definition-time function wrapping and runtime dynamic object composition with runnable code.