Search code examples
pythonerror-handlingcrashletters

Python not detecting a single letter, but detects two letters fine


This is the code I am using to detect if a string contains letters. If none are detected, it allows the program to convert the string to a float. The idea was that I could stop the program from crashing after attempting to convert a string with letters to a float.

for i in range(1, len(argument)):
    if argument[i].isalpha():
        return False
        print("Ran option 1")
    else:
        return True
        print("Ran option 2")

The print lines are just to help me see which part is being executed. As it turns out, neither of them are.

http://puu.sh/ivVI7/8598b82fe8.png

This is a screenshot of the output. In the first half, it detects the "aa" string and does not crash the code. However, in the second half, it fails to detect the single "a" and attempts to convert it to a float, crashing the program. If anybody could lend a hand, it would be greatly appreciated.

If it helps, the rest of the code is here: http://pastebin.com/Cx7HbM4c


Solution

  • Python strings are 0-based. The test never checks the first character in the string.

    for i in range(0, len(argument)):
    

    Filing that knowledge away, the python way (for char in argument) as shown in answers from @DeepSpace and @helmbert seems cleaner.