简体   繁体   中英

How not to execute else statement of for-loop when if statement is satisfied at least once?

I am trying to check all elements in a list to see if they meet the condition "less than 5". What I'm trying to do is if no numbers in my list are less than 5, I want to print a statement "There are no elements in this list less than 5.", otherwise print only those numbers that are, and not "There are no elements in this list less than 5." also.

list = [100, 2, 1, 3000]
for x in list:
    if int(x) < 5:
        print(x)
else:
    print("There are no elements in this list less than 5.")

This produces the output:

2
1
There are no elements in this list less than 5.

How can I get rid of the last line of that output?

The else of a for-loop will only be executed if no break was encountered. Thus, a for-else statement is not appropriate for finding multiple elements in a list since the first break will stop the loop.

Instead, use a list-comprehension and print accordingly based on the result.

lst = [100, 2, 1, 3000]

less_than_five = [x for x in lst if x <  5]

if less_than_five:
    print(*less_than_five)
else:
    print('There are no elements in this list greater than 5.')

You could do something like:

if max(mylist) < 5:
    print('there are no elements in this list greater than 5')
else:
    for x in mylist:
        if int(x) < 5:
            print(x)

This checks if your list contains anything greater than 5 before anything, and if there is, then it runs your loop.

Keep a boolean flag outside the loop. Set it to true if at least one element is found. If the flag does not change- print out your statement about no elements being found greater than 5:

list = [100, 2, 1, 3000]
found = False
for x in list:
  if int(x) < 5:
    print(x)
    found = True

if found == False:
  print("There are no elements in this list greater than 5")     

What you need is some sort of flag to keep track whether condition was met like in the code below. list = [100, 2, 1, 3000] flag = False for x in list: if int(x) < 5: print(x) flag = True if not flag: print("There are no elements in this list greater than 5.")

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