简体   繁体   中英

Python: How to make sure a number in the list is 0

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?

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
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
>>>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM