Reputation: 13
Okay here is part of my code
user_inputs = input('Input A B C >')
user_inputs_list = user_inputs.split()
print(user_inputs_list) #
print(user_inputs_list[:1]) #
if user_inputs_list[:1] == '0':
print('error')
I am trying to make sure the first number is NOT zero but this code doesnt print the error. If the numbers are 0 1 2, the user_inputs_list[:1] should be 0 , right? wouldnt that print the error?
Upvotes: 0
Views: 85
Reputation: 4035
user_inputs = input('Input A B C >')
if user_inputs.startswith("0"):
print ("error")
You can use startswith()
which is more easy and clear.
>>>
Input A B C >26
>>>
>>>
Input A B C >026
error
>>>
Upvotes: 1
Reputation: 33691
You are using the slice syntax, which returns list of first n
elements (n=1
in your case). If you want to check if the first element is zero, you should put number of element (zero-based) into brackets:
In [1]: user_input = '0 1 2'.split()
In [2]: user_input
Out[2]: ['0', '1', '2']
In [3]: user_input[:1]
Out[3]: ['0']
In [4]: user_input[0]
Out[4]: '0'
In [5]: user_input[0] == '0'
Out[5]: True
Upvotes: 3
Reputation: 882251
You need to check
if user_inputs_list[1] == '0':
without the :
you prepended to the 1
.
The colon makes what you wrote a slicing -- a list of items up to 1 included (so, a list with a single item, the 0th one).
Without the colon you have an indexing, which gets the one item at that position -- a string, which you can sensibly compare with another string, rather than a list of strings, which it makes no sense to thus compare.
Upvotes: 0