Reputation: 79
mylist = [right_branchcode, right_branchname, right_sellingcode, right_advcorp, right_childparent, \
right_eliteCategoryId, right_partyid, right_retailmga]
for item in mylist:
if len(item) > 0:
print(item)
else:
print()
I want to be able to return "True" if the for loop prints an item. The ultimate goal is to trigger an email notification that also includes the print(item) within it. I just dont know how to assign an operator to a for loop which contains an if statement.
I hope this is clear. Im still learning and find it hard to express what I need sometimes.
Thanks
Upvotes: 0
Views: 52
Reputation: 1824
The cleanest way is to just execute the code you want (e.g. send or do not send email) inside the loop. However, if you really want to separate concerns and have the email-sending logic separate from the iterating logic, you can use a generator. This corresponds to the notion of having an iterator return (yield
) a value.
mylist = [...]
def iterate_over_list(l):
for item in l:
if len(item) > 0:
yield True
item_iterator = iterate_over_list(mylist)
for item in item_iterator:
if item:
print('Send email') # replace with email-sending code
else:
print("Don't send email")
Upvotes: 0
Reputation: 33335
Initialize a variable to False before the loop. Inside the loop, if you print anything, then set that variable to True. Finally, after the loop finishes, return the variable.
mylist = [... stuff ...]
myflag = False
for item in mylist:
if len(item) > 0:
print(item)
myflag = True
else:
print()
return myflag
Upvotes: 0
Reputation: 531808
The loop itself isn't true or false; it's a flow-control statement, not an expression. What you are looking for is a flag (a Boolean-valued variable) whose value indicates whether or not a non-empty value was printed.
mylist = [...]
printed_something = False
for item in mylist:
if item:
print(item)
printed_something = True
else:
print()
After the loop completes, you can use the value of printed_something
as necessary. It will only have been changed to True
if at least one non-empty value was seen during the iteration.
Upvotes: 2
Reputation: 1691
I am not sure if i understood it correctly, but you can simply assign a variable inside the if statement.
mylist = [right_branchcode, right_branchname, right_sellingcode, right_advcorp, right_childparent, \
right_eliteCategoryId, right_partyid, right_retailmga]
for item in mylist:
if len(item) > 0:
print(item)
bool_var = True
else:
print()
print(bool_var) # It will print true if item is found
You can also use return
inside it, or break
if you want to stop the loop when it finds the item.
Upvotes: 2