You need to give found = False
every time you enter in the inner loop, otherwise it sets found = False
only once from the outside of all the loops, which is why if at any time in the inner loop found
become True
then it never become False
and remains True
for rest of the time, and that is why it never enter into if not found:
as found
remains True
always.
Your code should be like:
message="hello !"
s=""
# found=False
key=[['m', 'c'], ['u', 'e'], ['b', 'g'], ['a', 'k'], ['s', 'v'], ['h', 'x'],['i', 'z'], ['r', 'y'], ['p', 'w'], ['l', 'n'], ['o', 'j'], ['t', 'f'], ['q', 'd']]
for i in message:
found=False # use found here, cause you need to give `found = False` every time you enter in the inner loop, as in the inner loop you are considering found every time, so you need to set it from the outer loop
for j in key:
if i==j[0]:
found=True
s+=j[1]
break
elif i==j[1]:
found=True
s+=j[0]
break
if not found:
s+=i
print(s) # you may be want to print the `s` rather return
Output :
xunnj !
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…