简体   繁体   中英

if/else statement problem: else statement does not work

I am a beginner in programming and I am trying to implement if...else statement but being failed. I have an array list and I have to check it does not contain a specific value. But the else statement does not work.

#For an example:
a=[10,12.0,13.0]
b=[12.0]

if a <= b:
 print("something")
else:
 print("others")  #else statement doesn't work

I think what you're looking for is an iteration. Currently you're asking if your list a is less than or equal to your list b , but semantically this doesn't have a lot of meaning. In fact, Python seems to somewhat unintuitively select the first element of each list in order to perform the comparison. Thus, in the example code you give it will always evaluate as True since 10 < 12.0 .

However, if you add an iterator like so:

a=[10,12.0,13.0]
b=[12.0]

for ai in a:
    for bi in b:
        if ai <= bi:
            print(f"a={ai} b={bi} and a is strictly smaller.")
        else:
            print(f"a={ai} b={bi} and a is equal or greater.")

In this manner you can compare every item in a with every item in b .

However, if you simply want to ensure that 12.0 is not in a , Python provides a much simpler way:

a=[10,12.0,13.0]
b=[12.0]

if b[0] in a:
    print("The list contains the selected value.")

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