简体   繁体   中英

How do I stop a print statement in a for loop from printing repeatedly if the loop needs to continue running?

The circumstances in my code make it as such that even after looking for a while, I couldn't find an applicable answer. This is a simplified version of my code:

value = int(input())
list = [5,10,15,20]

for i in list:
    if i == value:
        print("Value is in list.")
        break
    else:
        print("Value is not in list.")
       

If I were to input 15, the code would print

"Value is not in list. Value is not in list. Value is in list."

but I only want it to print "Value is in list." one time if it is in the list and print "Value is not in list." one time if it is not. I have to keep the for loop and the if/else statements. As far as I can tell, I can't use break in the else without ending the loop entirely. What do I do?

You can use a flag, the flag is False by default, and if you find the value, you set the flag to True.

After the for iteration finish, you can check the flag variable value to realize whether the value is on the list or not

value = int(input())
list = [5,10,15,20]

found = False
for i in list:
    if i == value:
        found = True
        break

if found:
    print("Value is in list.")
else:
    print("Value is not in list.")

This is a way to just update your algorithm and make it work, otherwise you can just use if value in list to check if the element is in your list

This may not be your goal, but couldn't you just check if the value exists in the list one time, rather than iterating?

value = int(input())
_list = [5,10,15,20]

if value in _list:
    print("Value is in list.")
else:
    print("Value is not in list.")

You could create a boolean.

value = int(input())
list = [5,10,15,20]
firstTime = True
for i in list:
    if i == value and firstTime == True:
        print("Value is in list.")
        firstTime = False
    else:
        if firstTime == True
            print("Value is not in list.")
            firstTime = False

You might move that to a function, which can be terminated at any time.

def isin(val):  
    list_ = [5, 10, 15, 20]  
    for i in list_:  
        if val == i:  
            print("Value in list")  
            return  
    print("Value not in list")      


isin( int(input()) )  

You could just declare a boolean variable as follows:

value = int(input())
list = [5,10,15,20]
avail=False

for i in list:
    if i == value:
        avail=True
        break  
        
if avail:
    print('Value in List')
else:
    print('Value not in List')

A more simpler way is using the in keyword as follows:

value = int(input())
list = [5,10,15,20]

if value in list:
    print('Value In list')
else:
    print('Value Not in list')

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