Python - For-Loop通过all然后打印?

时间:2017-09-30 11:39:46

标签: python loops for-loop printing

所以这是我提供的代码,描述如下:)

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)   

输出

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

我想要的是它不应该说“找不到名字”,直到它通过循环圈出所有名字,然后说它没有找到任何名字。 但它现在做的是它逐个循环每个名字,直到找到名字,然后我使用break来不再搜索其他名称,因为它不需要。

所以问题是我怎么能把它变成它所说它没有找到名字,因为它已经为每个名字循环,然后说在找到所有名字之后没找到名字?

编辑:

因此,每当它找到名称时,它将转到addtonotes = {'id': nameID},然后它将被添加到 addtonotes 但它没有找到,然后会有一个追溯说:

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

所以我也想要的是,当它没有找到任何名称时,它应该只使用Sys.exit()但我现在不能在else语句中真正做到这一点,因为它将通过第一个循环进行sys.exit。 ..

我希望有人理解这个问题:)

1 个答案:

答案 0 :(得分:1)

最简单的方法是在循环之前将nameID设置为空值

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')

但是,Python for循环实际上具有针对此案例的专用语法;您可以在else:循环中添加for块。它仅在for循环完成时执行,即没有break提前结束循环时执行:

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')