Python Forum

Full Version: counting chars in string w/o len
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Here's my homework assignment:

Write code to count the number of characters in original_str using for loop as a counter and assign the answer to a variable num_chars. Do NOT use the len function to solve the problem.

#Here's my attempt:

original_str = "The quick brown rhino jumped over the extremely lazy fox."
counter=0
for counter in range (original_str):
	counter = counter +  1
num_chars=counter
print(num_chars)
Here's error message:
TypeError: start must be a integer on line 3
From an interactive prompt, you can type help(range) to see how it expects to be used. The short version, is that it expects a number of how many things you want in the range, so range(10) would generate a sequence of 10 digits, 0 through 9.

That's a whole lot of words to say that range() isn't where you should be with this assignment. Here's a hint, you can iterate over the string directly.
In addition to what Nilamo said, you want your loop variable to be different from the variable you are using to count the characters.