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

179 views Asked by At

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

5

There are 5 answers

1
Mark Larter On BEST ANSWER

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.

0
DeepSpace On

You have the print lines after the return command, so they will never be executed. Move the print above the return.

You can also make your code more pythonic and more readable:

for char in argument:
   return char.isalpha()
0
helmbert On

In Python, arrays are zero-indexed. This means, you need to start iterating at 0, not at 1!

You can reproduce this easily by simply adding a print(argument[i]) into your loop body:

def func(argument):
    for i in range(1, len(argument)):
        print(argument[i])

func("a") # Prints nothing
func("ab") # Prints "b"

Keeping as closely as possible to your original code, simply start iterating at 0 instead of 1:

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

Easier yet, you can also iterate a string directly:

for character in argument:
    print(character) # Will print every single character
    # ...
0
outoftime On

Ok, if you try to find out can you convert string or not, why don't you use function like this:

def convertable(value): 
    try: 
        float(value)
        return True
    except ValueError:
        return False
2
Pynchia On

if all you want is to prevent your program from crashing, exceptions are your friends:

argument = "abc"
try:
    value = float(argument)
except ValueError as e:
    print e, "is unacceptable"
else:
    print value, "is acceptable as a float"
finally:
    print "alright"

outputs:

could not convert string to float: abc is unacceptable
alright

whereas, if argument = "3.14" it outputs:

3.14 is acceptable as a float
alright

Of course, you can put all that logic into a function, in case you need to do it many times across your program. Have fun!