Home > database >  how to make nested loops in python for passing a string?
how to make nested loops in python for passing a string?

Time:03-01

I was trying to do the nested loop for string in python and the output is one string is repeating. The program shown below,

recipients = ['[email protected]', '[email protected]', '[email protected]']
t = Template('$email')

message = ['employee1', 'employee2', 'employee3']
n = Template('$name')


def get_email_text():
    for i in draftnotification.recipients:
        recipient = draftnotification.t.substitute(email=i)
        print(recipient)
        for j in draftnotification.message:
            names = draftnotification.n.substitute(name=j)
            print('hi ' names)
        text = 'Fee Summary Report'
        print(text)

    return text

the output is,

[email protected]
hi employee1
hi employee2
hi employee3
Fee Summary Report
[email protected]
hi employee1
hi employee2
hi employee3
Fee Summary Report
[email protected]
hi employee1
hi employee2
hi employee3
Fee Summary Report

hi employee is repeating need to get the output like is showing below

[email protected]
hi employee1
Fee Summary Report
[email protected]
hi employee2
Fee Summary Report
[email protected]
hi employee3
Fee Summary Report

kindly looking for someones help. Thanks in advance.

CodePudding user response:

You can use enumerate function for this

recipients = ['[email protected]', '[email protected]', '[email protected]']

message = ['employee1', 'employee2', 'employee3']

for i, j in enumerate(recipients, 0):
    print(f'{j}')
    print(message[i])

CodePudding user response:

You're going over every element in message every time you process a new recipient.

Instead, use zip() to bind each recipient to its corresponding message:

def get_email_text():
    for i, j in zip(draftnotification.recipients, draftnotification.message):
        recipient = draftnotification.t.substitute(email=i)
        # Rest of the for loop is the same, omitted for brevity.
        ...
  • Related