0

The purpose of this script is to send an email to a receivers list, and the code works just for the first receiver but the never works for the rest of the list.

here is the code:

class email:
    def __init__(self, sender, subject, message):
        self.sender = sender
        self.subject = subject
        self.message = message



    def receivers(self):
        receivers = ('adam', 'tom', 'mel')
        for receiver in receivers:
            return receiver



    def send(self):
        print('we send email from'.capitalize(), self.sender, 'to', email.receivers().title(), 'and the subject is',
              self.subject, 'finally the massage is', self.message)


email = email('sayed', 'morning message', 'wake up man')
email.send()

here is the result:

We send email from sayed to Adam and the subject is morning message finally the massage is wake up man
Sayed Gouda
  • 605
  • 3
  • 9
  • 22

4 Answers4

4

Whenever a return statement is executed, the current function is immediately exited. Use either return receivers (without the loop) to return the entire set instead of just one item, or use yield receiver to create a generator (if you choose the latter, please read the linked answer to understand what generators are).

Stylistic advice: reusing a function name as a variable name inside that function is likely going to confuse people who read your code.

Aasmund Eldhuset
  • 37,289
  • 4
  • 68
  • 81
1

Return exits the function once it returns a value. It's like a break.

You get that result, because once you return the first value ('adam'), you exit the function via return. You should just return the whole tuple: return receivers, then in send(self):

receivers = email.receivers()
for receiver in receivers:
    print('we send email from'.capitalize(), self.sender, 'to', receiver.title(), 'and the subject is',
              self.subject, 'finally the massage is', self.message)
Fanatique
  • 431
  • 3
  • 13
0

your receivers function stops after returning the first receiver, I suggest returning the set and iterate over it

def receivers(self):
    return ('adam', 'tom', 'mel')

for receiver in email.receivers():
    print('we send email from'.capitalize(), self.sender, 'to', receiver.title(), 'and the subject is',
          self.subject, 'finally the massage is', self.message)
Bernhard
  • 1,253
  • 8
  • 18
0

If tuple of receivers is static, then move this tuple to be class attribute:

class Email: # convenient
  _receivers = ('adam', 'tom', 'mel') # _ - to be protected
RandomB
  • 3,367
  • 19
  • 30