0

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?

1 Answer 1

5

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.