Somehow, I have made it this far in Python without having an explicit understanding of how conditionals work (especially when nested in loops). I came to this realization while I was designing an algorithm that iterates over a list, and builds a new list at a 1:1 ratio.
For example:
x = ['test1', 'test2', 'test3']
y = []
for z in x:
if z == #whatever:
y.append(f'{z}{'is good'}'
if z == #whatever:
y.append(f'{z}{'is bad'}'
One would expect that y and x would both be the same length by the end of the loop. That is not what happened, and I had multiple repeats in my y list, with different conditional results. I.E. an element may have been appended three times and triggered a number of different conditionals in the statement.
So, I began testing and just became even more confused:
import re
regexp = r'webaddy'
regexp2 = r'Web Addy'
zd = ['test', 'webaddy55', 'sss', 'Web Addy:99']
for xc in zd:
if re.match(regexp, xc):
print('This has webaddy' + ' | ' + xc)
if re.match(regexp2, xc):
print('This has Web Addy' + ' | ' + xc)
else:
print("Works" + ' | ' + xc)
My expected output for this would be:
Works | test
This has webaddy | webaddy55
Works | sss
This has Web Addy | Web Addy:99
The actual output is:
Works | test
This has webaddy | webaddy55
Works | webaddy55
Works | sss
This has Web Addy | Web Addy:99
How could it have 5 outputs with only 4 elements in the list? What is wrong with how I am structuring my conditionals? I was under the impression that once a conditional is met, the loop moves on to the next item in the list, what is actually going on here?
Aucun commentaire:
Enregistrer un commentaire