Reputation: 41
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?
Upvotes: 4
Views: 3872
Reputation: 149
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')
Upvotes: 0
Reputation: 106
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()) )
Upvotes: 1
Reputation: 9693
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
Upvotes: 6
Reputation: 1284
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.")
Upvotes: 5
Reputation: 5889
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
Upvotes: 2