gaz
gaz

Reputation: 31

python - Check Raw_input is not empty

I have created the following code as part of an online exercise on codeacademy

print "Welcome to the English to Pig Latin translator!"
original = raw_input("what's you name?")

if original != "" and original.isalpha():
    print original
else:
    print "empty"

but then saw later on the course it swapped original != "" to using len(original) > 0

Are they the same as far the interpretter in python cares please?

Upvotes: 0

Views: 1160

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

In your concrete example, original != "" and len(original) > 0 will always give back the same results because we know original will always be a string. The latter variant will be a little slower, but you wouldn't notice.

But the whole condition is unnecessary in this context because

>>> "".isalpha()
False

Therefore, you'd get the same logic with

if original.isalpha():
    print original
else:
    print "empty"

However, the results would not be correct because

>>> "1".isalpha()
False

Better use something like

if original.isalpha():
    print original
elif not original:
    print "empty"
else:
    print "not alpha"

Upvotes: 5

Related Questions