Python Forum

Full Version: if statement in for loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This runs a blank. Any suggestions?
story="HOW THE WHALE GOT HIS THROAT IN the sea, once upon a time, O my Best Beloved, there was a Whale, and he ate fishes. He ate the starfish and the garfish, and the crab and the dab, and the plaice and the dace, and the skate and his mate, and the mackereel and the pickereel, and the really truly twirly-whirly eel. All the fishes he could find in all the sea he ate with his mouth--so! Till at last there was only one small fish left in all the sea, and he was a small "
for letter in story:
	letter1=letter
	if letter1.isalpha():
    	print(letter1)
Your closing python tag is wrong, so it's hard to see what the indentation is. Please edit that.

But the code itself seems reasonable and it runs and has output on my machine. How are you running it? If you put a print("starting") as the first line, are you at least getting that output?
This code prints out the letters and skips blanks and punctuation and other non-alphas.
story="Hello world!"
for letter in story:
    if letter.isalpha():
        print(letter)
I played around with different indentation and cannot see how this code, or your code, could print a blank/space. Are you sure the code you posted is the code you ran?
isalpha() will only return True if it is an alpha character a-z or A-Z

>>> ' '.isalpha()
False
>>> '1'.isalpha()
False
>>> 'd'.isalpha()
True
>>> 'D'.isalpha()
True
This part is unnecessary
Quote:
    letter1=letter

so it makes me think about what else is in your code not shown to us in the code snippet provided
Thank you everyone. I was using the python interpreter at w3schools - are online interpreters unreliable perhaps?
Not sure. I was able to run the code above on w3schools online python and got the output expected. You might try reloading the page or repasting the code.
I would be really surprised if isalpha doesn't work. You can test easily enough using the examples in metulburr's post.

You should be trying to debug this problem yourself. The first thing I would have done was start with a much shorter and more interesting story, at least from a programming point of view.
story = 'aA 12 !@#$%^&*()+=-~'
for letter in story:
    if letter.isalpha():
        print(letter, letter.)
If this didn't give me the expected results I would test if isalpha worked as expected.
story = 'aA 12 !@#$%^&*()+=-~'
for letter in story:
    print(letter, 'isalpha =', letter.isalpha())
Depending on the results I would check the documentation to determine if I was doing the loop right or using isalpha() correctly.

After doing that research I might consider posting a question on the forum. My research would probably solve the problem and I wouldn't have to wait for an answer. If I still had questions I would ask a better question and be in a better position to understand the answer.