WeInThis WeInThis - 3 years ago 226
Python Question

Python - For-Loop through all and then print?

So this is the code im providing and the description is below :)

r = s.get(Url)
names = soup(r.text, 'html.parser')
findName = names.find('div', {'class':'nameslist'})

if (r.status_code == 200):


for name in names.find_all('option'):

global nameID

if myName == foundName:
nameID = size.get('value')
print('Profile-1 Found name')
break

else:
print('Did not find name')


if (findName != None):
notepresent = True
print('There is a value')
else:
global addtonotes
notepresent = False
addtonotes = {'id': nameID}
add2notes(addtonotes)


Output

Did not find name
Did not find name
Did not find name
Did not find name
Did not find name
Did not find name
Did not find name
Profile-1 Found name


What I want is that it should not say "Did not find name" until it has looped all the names through the loop and THEN say it did not find any names.
But what it does now is that it loops for each names one by one until it finds the name and then I used break to dont search for other names anymore since its not needed.

So the question is how can I turn it so it will say Did not find names when it has looped for every name and then say Did not find names after it has been looped through all names?

EDIT:

So whenever it found the Name it will go to
addtonotes = {'id': nameID}
and then it will be added to addtonotes but it dont find then there will be a traceback saying:

Did not find name
Did not find name
Did not find name
Did not find name
Did not find name
Did not find name
Did not find name
Did not find name
Did not find name
Did not find name
Traceback (most recent call last):
self._target(*self._args, **self._kwargs)
File "C:\Users\Test.py", line 153
addtonotes = {'id': nameID}
NameError: name 'nameID' is not defined


So what I also want is that when its not finding any names then it should just use Sys.exit() but I can't really do it in the else statement now because it will sys.exit by the first loop...

I hope someone understand the issue :)

Answer Source

The simplest approach would be to set nameID to an empty value before the loop:

nameID = None
for name in names.find_all('option'):
    if myName == foundName:
        nameID = size.get('value')
        print('Profile-1 Found name')
        break

if nameID is None:
    print('Did not find name')

However, the Python for loop actually has dedicated syntax for this case; you can add an else: block to a for loop. It is only executed when the for loop completes, i.e. when there was no break to end the loop early:

for name in names.find_all('option'):
    if myName == foundName:
        nameID = size.get('value')
        print('Profile-1 Found name')
        break
else:
    print('Did not find name')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download