0

I'm new to programming so bear with me please! I'm creating a class and having trouble getting the return message to show when the users input is empty.
Instead of returning my message it's just throwing me an error.

I want my code to return "please try again" and end, if the user input is blank.

Code:

class BankAccount():

    def __init__(self):
        # asking for a name
        self.name = str(input("Hello! Welcome to the Bank of Alex.\nWhat is your name?"))
        if self.name == "":
            return "please try again"
        else:
            print(f"\nWelcome, {self.name.title()}.")

TypeError Traceback (most recent call last) in ----> 1 account = BankAccount()

TypeError: init() should return None, not 'str

Dasax121
  • 23
  • 8
  • 1
    `__init__` is not what you are thinking of. You probably meant to write a `__main__` function. See [this question](https://stackoverflow.com/questions/419163/what-does-if-name-main-do) – Selcuk Aug 08 '19 at 00:35

2 Answers2

5

Your program structure is incorrect for using a class. You should not create an object until you know the input is valid. Have the calling program check it:

name = ""
while name == "":
    name = input("Enter your name")
    if name:
        acct = BankAccount(name)
        break
    else:
        print("Please try again")

Your __init__ method then merely crates the account -- no name check. This method implicitly returns the created object; you're not allowed to return anything else.

Prune
  • 76,765
  • 14
  • 60
  • 81
  • Such a nice and polite way to say "don't do it" – Evgeny Aug 08 '19 at 00:41
  • @Evgeny: nah -- it's just showing how we've learned to partition our functionality over the past half-century or so. In this case, it's merely waiting: don't go to the trouble of creating a new object until we have all the required parameters nailed down. – Prune Aug 08 '19 at 00:44
  • Thanks! that worked but now it's throwing me a new error message TypeError: BankAccount() takes no arguments I tried using BankAccount(self) and BankAccount(name) and that doesn't seem to work either. – Dasax121 Aug 08 '19 at 01:09
  • 3
    You'll need to adjust your class so that `__init__` takes the provided name as a parameter: `def __init__(self, name): ...` – Andrew Aug 08 '19 at 02:06
0

I was able to solve this with help from @Prune. I used the while loop he mentioned and put it under __ init __

So if user input is blank it will just keep prompting for an input. Not a perfect solution but it works.

class BankAccount():

    def __init__(self):
        self.name = input("Hello! Welcome to the Bank.\nWhat is your name?")
        while self.name == "":
            self.name = input("Please enter your name")
        if self.name:
            print(f"\nWelcome, {self.name.title()}.")
Dasax121
  • 23
  • 8