Search code examples
pythonreturn

Reasons to have a return statement without returning any value


The following code came from the book Fundamentals of Python, which made me think there must be some reasons for the author to use return without returning anything.

def save(self, fileName = None):
    """Saves pickled accounts to a file. The parameter
    allows the user to change filenames."""
    if fileName != None:
        self.fileName = fileName
    elif self.fileName == None:
        return # WHAT ARE THE REASONS FOR HAVING THIS LINE? CAN WE DELETE/REMOVE IT?
    fileObj = open(self.fileName, "wb")
    for account in self.accounts.values():
        pickle.dump(account, fileObj)
    fileObj.close()

The full code is as follows:

import pickle

class SavingsAccount(object):
    RATE = 0.02 # Single rate for all accounts
    
    def __init__(self, name, pin, balance = 0.0):
        self.name = name
        self.pin = pin
        self.balance = balance
    
    def __str__(self) :
        """Returns the string rep."""
        result = 'Name: ' + self.name + '\n'
        result += 'PIN: ' + self.pin + '\n'
        result += 'Balance: ' + str(self.balance)
        return result
    
    def getBalance(self):
        """Returns the current balance."""
        return self.balance
    
    def getName(self):
        """Returns the current name."""
        return self.name
    
    def getPin(self):
        """Returns the current pin."""
        return self.pin
    
    def deposit(self, amount):
        """Deposits the given amount and returns None."""
        self.balance += amount
        return None
    
    def withdraw(self, amount):
        """Withdraws the given amount.
        Returns None if successful, or an
        error message if unsuccessful."""
        if amount < 0:
            return "Amount must be >= 0"
        elif self.balance < amount:
            return "Insufficient funds"
        else:
            self.balance -= amount
            return None
    
    def computeInterest(self):
        """Computes, deposits, and returns the interest."""
        interest = self.balance * SavingsAccount.RATE
        self.deposit(interest)
        return interest
    

class Bank(object):
    def __init__(self, fileName):
        self.accounts = {}
        self.fileName = fileName
        
    def __str__(self) :
        """Return the string rep of the entire bank."""
        return '\n'.join(map(str, self.accounts.values()))

    def makeKey(self, name, pin):
        """Makes and returns a key from name and pin."""
        return name + "/" + pin

    def add(self, account):
        """Inserts an account with name and pin as a key."""
        key = self.makeKey(account.getName(),  account.getPin())
        self.accounts[key] = account
        
    def remove(self, name, pin):
        """Removes an account with name and pin as a key."""
        key = self.makeKey(name, pin)
        return self.accounts.pop(key, None)
    
    def get(self, name, pin):
        """Returns an account with name and pin as a key
        or None if not found."""
        key = self.makeKey(name, pin)
        return self.accounts.get(key, None)
    
    def computeInterest(self):
        """Computes interest for each account and
        returns the total."""
        total = 0.0
        for account in self.accounts.values():
            total += account.computeInterest()
        return total
    
    def save(self, fileName = None):
        """Saves pickled accounts to a file. The parameter
        allows the user to change filenames."""
        if fileName != None:
            self.fileName = fileName
        elif self.fileName == None:
            return
        fileObj = open(self.fileName, "wb")
        for account in self.accounts.values():
            pickle.dump(account, fileObj)
        fileObj.close()

How can the def save(self, fileName=None) be modified such that the program will ask user to provide a file name, that is:

bank = Bank(None)
bank.add(SavingsAccount("Wilma", "1001", 4000.00))
bank.add(SavingsAccount("Fred", "1002", 1000.00))
bank.save() # a prompt would appear: 'Please provide a name for the file to be saved'

Solution

  • Note that return followed by no value is the same as writing return None. In the code you've shown, the return statement is used to terminate the function in the case that no filename is passed, rather than trying to execute the code following the if and elif.