1
class Questionare:
    def ask_age(self):
        try:
            age = int(input('Type your age after the arrow -> '))
            self.age = age
            print(['inside'], self.age)
            return self.age
        except ValueError:
            print('Only use numbers to inform your age!')
            self.ask_age()

    def __init__(self):
        self.age = self.ask_age()
        print(['__init__'], self.age)

if __name__ == '__main__':
    user_data = Questionare()
    print(['outside'], user_data.age)

Why is it habing such behavior? the result inside is "ok", but the output returns None. What goes on?

Type your age after the arrow -> a
Only use numbers to inform your age!
Type your age after the arrow -> 12
['inside'] 12
['__init__'] None
['outside'] None
Lucas Farias
  • 33
  • 1
  • 4

1 Answers1

2

You need to return the value from the recursive call when a ValueError happens:

class Questionare:
    def ask_age(self):
        try:
            age = int(input('Type your age after the arrow -> '))
            self.age = age
            print(['inside'], self.age)
            return self.age
        except ValueError:
            print('Only use numbers to inform your age!')
            return self.ask_age()   # return here

Note: using recursion like this is usually not the right approach. Use a loop instead.

Also, you're already assigning to self.age inside the ask_age method. You don't necessarily need to return anything & assign again within __init__. Assign at only one place.

rdas
  • 20,604
  • 6
  • 33
  • 46
  • Do you mean using while True with try except inside, and in except ValueError, instead of using "return self.ask_age()", I should be using "continue"? – Lucas Farias Oct 24 '22 at 22:49
  • Something like that. See this question for pointers: https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response – rdas Oct 25 '22 at 04:49