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.
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'
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With