Python BasicsMedium

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

Medium

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.

Constraints
  • 0 <= len(s) <= 1000
  • s contains only printable ASCII characters

Examples

Example 1
Input
s = 'hello'
Output
5
Explanation

The string 'hello' has 5 characters: h, e, l, l, o.

Example 2
Input
s = 'python'
Output
6
Explanation

The string 'python' has 6 characters.

Example 3
Input
s = ''
Output
0
Explanation

An empty string has length 0.

Need a Hint?
Consider using Recursion-specific data structures like sets or heaps.
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.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.