Python: String Length without Built-in Functions

1. Introduction

While Python provides a built-in len() function to determine the length of a string, understanding how to manually compute this can be an insightful exercise. In this post, we'll explore a simple way to calculate the length of a string in Python without using any built-in functions.

2. Program Overview

1. Create a function to iterate through the string and count the number of characters.

2. Take user input for the string.

3. Call the function with the user-provided string.

4. Display the result.

3. Code Program

# Python program to calculate the length of a string without using built-in functions

def string_length(s):
    """Function to calculate the length of a string."""
    count = 0  # Initialize count to 0
    for char in s:
        count += 1  # Increment count for every character
    return count

# Taking user input
string_input = input("Enter a string: ")

# Calculate the length of the string
length = string_length(string_input)

# Display the result
print(f"The length of the string '{string_input}' is: {length}.")

Output:

(For an input of "Python")
Enter a string: Python
The length of the string 'Python' is: 6.

4. Step By Step Explanation

1. We start by defining a function named string_length that takes a single string argument s.

2. Inside the function, we initialize a variable count to zero. This variable will store the length of the string.

3. We then iterate over each character in the string using a for loop. For every character, we increment the count by 1.

4. After processing all characters, the function returns the value of count which represents the length of the string.

5. Outside the function, we prompt the user to provide a string.

6. We then call the string_length function with the user-input string and store the result in the length variable.

7. Finally, we display the length of the string using a formatted print statement.

8. The provided output section illustrates the program's output for the input string "Python".

Comments