4

I am a beginner in python and the following code I am trying

input_number = raw_input("Please input the number:")
print type(input_number)
if(input_number.index('0')):
    print "Not Accepted"
else:
    print "Accepted"

When I am giving the input for example '1234506' its showing "Not accepted" which is valid but when I am giving '123456' its throwing error "Substring not found". So how can I print the else part.

0

2 Answers 2

7

when you enter 123456 or 1234506, python considers it as a string.

Now, when you use string_object.index(substring), it looks for the occurrence of substring (in your case, the substring is '0') in the string_object. If '0' is present, the method returns the index at which the substring is present, otherwise, it throws an error.

you can use the following instead :

if '0' in input_number :
    print 'not accepted'
else :
    print 'accepted'
Sign up to request clarification or add additional context in comments.

Comments

5

str.index errors out when there is no match. In this situation, you can either choose to handle the error, or use str.find instead which returns an integer value between -1 and len(input_number), or do a set membership test on the original string.

Option 1

Conversion to set lookup:

if '0' not in set(input_number):
    print "Accepted"
else:
    print "Not accepted"

Option 2

Using try...except to handle the ValueError.

try:
    input_number.index('0')
    print "Not accepted"

except ValueError:
    print "Accepted"

Option 3

Using str.find:

if input_number.find('0') < 0:
    print "Accepted"
else:
    print "Not accepted"

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.