So, I'm a beginner to programming. I am trying to create a program where the user can input a sentence and the program will tell the user how many letters are in that sentence.
counter=0
wrd=raw_input("Please enter a short sentence.")
if wrd.isalpha():
counter=counter+1
print "You have" + str(counter) +"in your sentence."
When I enter this, my output is blank. What is my mistake in this program?
4 Answers 4
You need to indent code inside if blocks. In the code you have provided, you've forgotten to indent counter = counter + 1.
You are missing a loop across all characters of wrd. Try this instead,
counter = 0
wrd = raw_input("Please enter a short sentence.")
# Iterate over every character in string
for letter in wrd:
# Check if the letter is an alphabet
if letter.isalpha():
# Increment counter only in this condition
counter += 1
print "You have " + str(counter) + " in your sentence."
Comments
First of all as @kalpesh mentioned, the statement counter=counter+1 should be indented.
Second of all, you need to iterate over the entire string entered and then count the number of characters or whatever the logic you need.
counter=0
wrd=raw_input("Please enter a short sentence.")
for i in wrd:
if i.isalpha():
counter = counter+1
print "You have " + str(counter) +"in your sentence."
Once you start learning more, then you can use the below code,
counter=[]
count = 0
wrd=raw_input("Please enter a short sentence.")
counter = [len(i) for i in wrd.split() if i.isalpha()]
print "You have " + str(sum(counter)) +"in your sentence."
I am just splitting the word and then checking if it is alpha or not and using the list comprehension to iterate over the string entered.
Comments
wrd.isalpha() returns a boolean (true or false). So if the function returns true, counter=counter+1 will be called once (and only once). You need to iterate through every letter of wrd and call isalpha() on each letter.
Comments
You could always remove the spaces from your sentence using replace() then use len() to get how many characters are in the sentence.
For example:
sentence = input("Type in a sentence: ") # Ask the user to input a sentence
sentence = sentence.replace(" ", "") # Replace the spaces in the sentence with nothing
print("Your sentence is " + str(len(sentence)) + " characters long") # Use len() to print out number of letters in the sentence
counter=counter+1I think. Besides this, you aren't exactly using a looplen()? That's the easiest and fastest way to do what you describe. Of course you'd still need to filter out the all the non-letters from your sentence.