Except 子句未执行 python

Except clause not executing python

我目前正在学习如何在 Python (3.8) 中编程,但我的预算跟踪器程序中的一个函数出现了问题。当我键入其他内容时,except 子句不执行 'Day'、'Week'、'two weeks'、'three weeks'、'Month'、'three months'、'half a year'、'Year'、'two years'、'five years' 当我输入 'Day'、'Week' 时,它会继续并继续说 'When do you get net money?'。 . 它中断了,但我希望在发生错误时执行 except 子句。预先感谢您回答我的问题并使我的功能更有效率。如果你知道如何使更好的功能来问 'When do you get net money?' 写它。对不起,如果我在这里打错了,我的英语不完美。

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!')

如果用户键入的内容不在您的列表中,那也不例外。

您可以使用 assert 语句。

这将是您的代码:

try:
    assert self.income_phase not in ['Day','Week','two weeks','three weeks','Month','three months','half a year','Year','two years','five years']
except AssertionError:
    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): ')
else:
    print("Try again!")

希望这对您有所帮助!

如果 try 块中的指令遇到错误,您的代码只会抛出异常。您的代码的工作方式是,只要用户没有输入预期的字符串,它就会继续询问。

我还建议您使用常量来存储预定义值,例如您的输入列表。在提示中给用户的消息末尾添加一个 \n 将添加一个换行符并使内容更具可读性。

在我看来,您实际上也不需要抛出异常。但这取决于你。

您需要的是:

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()