166k views
1 vote
Question 2

Complete the for loop and string method needed in this function so that a function call like "alpha_length("This has 1 number in it")" will return the output "17". This function should:

accept a string through the parameters of the function;

iterate over the characters in the string;

determine if each character is a letter (counting only alphabetic characters; numbers, punctuation, and spaces should be ignored);

increment the counter;

return the count of letters in the string.

def alpha_length(string):
character = ""
count_alpha = 0
# Complete the for loop sequence to iterate over "string".
for ___:
# Complete the if-statement using a string method.
if ___:
count_alpha += 1
return count_alpha

print(alpha_length("This has 1 number in it")) # Should print 17
print(alpha_length("Thisisallletters")) # Should print 16
print(alpha_length("This one has punctuation!")) # Should print 21

User Badhan Sen
by
7.6k points

1 Answer

7 votes

Final answer:

The completed function iterates over each character of a string, checks if the character is an alphabetic letter using the .isalpha() method, and returns the total count of such letters.

Step-by-step explanation:

The task is to complete a Python function that counts the number of alphabetic characters in a given string. The code should include a for loop to iterate through each character in the string and an if statement to check whether a character is an alphabetic letter using the .isalpha() method. Here is the completed function:

def alpha_length(string):
count_alpha = 0
for character in string:
if character.isalpha():
count_alpha += 1
return count_alpha
When called with different strings, such as "This has 1 number in it", "Thisisallletters", or "This one has punctuation!", the function will return the count of letters in each string, ignoring numbers, spaces, and punctuation.

User Rafael Merlin
by
8.4k points