I'm currently learning how to program in Python (3.8) and I've had a problem with a function in my budget tracker program. The except clause isn't executing when i type other thing then 'Day','Week','two weeks','three weeks','Month','three months','half a year','Year','two years','five years' it just continues and keep going saying 'When do you get net money?' when i type 'Day','Week'... it breaks but I want that the except clause execute when an error occurs. Thank you in advance for answering my question and making my function more efficient. If you know how to make better function to ask 'When do you get net money?' write it. Sorry if I type something wrong here, my English isn't perfect.
class Main:
def __init__(self):
self.income_phase = ''
def income_phase_ask(self):
while self.income_phase not in ['Day','Week','two weeks','three weeks','Month','three months','half a year','Year','two years','five years']:
try:
self.income_phase = input('When do you get net money? (Day; Week; two weeks; three weeks; Month; three months; half a year; Year; two years; piec lat): ')
except Exception:
print('Error! Try again!')
Your code is only going to throw an exception if the instruction in the try
block encounters an error. The way your code works is that as long as the user does not input the expected string, it will keep on asking.
I would also advise you to use constants to store predefined values like your list of inputs. Adding a \n
at the end of your message to the user in the prompt will add a line break and make things more readable.
You don't really need to throw an Exception either, in my view. But that's up to you.
What you need is something like:
class Main:
VALID_USER_INPUTS = ['Day','Week','two weeks','three weeks','Month','three months','half a year','Year','two years','five years']
def __init__(self):
self.income_phase = ''
def income_phase_ask(self):
self.income_phase = input('When do you get net money? (Day; Week; two weeks; three weeks; Month; three months; half a year; Year; two years; piec lat): \n')
if self.income_phase not in self.VALID_USER_INPUTS:
print('Error! Try again!')
self.income_phase_ask()