Search code examples
pythonstringfunctionemailreturn

Python function return multiple elements


I have the function below :

    def fisap(self):
    print("*" * 42)
    print("Nrc", "Data".rjust(10), "Intrari".rjust(13), "Iesiri".rjust(12))
    print("*" * 42)
    for elem in self.ddop.keys():
        if elem in self.ddint.keys():
            print(str(elem), str(self.ddop[elem]).rjust(10), str(self.ddint[elem]).rjust(13))
        else:
            print(str(elem), str(self.ddop[elem]).rjust(10), str(0).rjust(13), str(self.ddies[elem]).rjust(12))
    print("*" * 42)
    print("Soldul final este de : " + str(self.sold))

It returns the following when called ( example ) : enter image description here

It returns what it need to return, all good here, but my question is how i can store all this return text, in this format, in a variable, string or anything else to can send it by email using smtplib. If i try to send the email using the message body of : selfitem.fisap() it sends None . Like this : enter image description here

Any help is greatly appreciated.


Solution

  • You need to store the whole message in a string before printing it, only then you can return it using return

    print is not the same as return

    def fisap(self):
        elements = []
        for elem in self.ddop.keys():
            if elem in self.ddint.keys():
                elements.append(str(elem), str(self.ddop[elem]).rjust(10), str(self.ddint[elem]).rjust(13))
            else:
                elements.append(str(elem), str(self.ddop[elem]).rjust(10), str(0).rjust(13), str(self.ddies[elem]).rjust(12))
    
        message = "{divider}\n{headers}\n{elements}\n{divider}\n{total}".format(
            divider="*" * 42,
            headers='\t'.join(["Nrc", "Data".rjust(10), "Intrari".rjust(13), "Iesiri".rjust(12)]),
            elements=elements,
            total="Soldul final este de : " + str(self.sold)
            )
    
        print(message)
        return message
    
    def main():
        returned_value = fisap() #fisap() is called and its result is stored in the variable returned_value
        print(returned_value) #we can then print it again or treat it as we would a string variable