python中的int()和float()方法如何增强程序以不允许“0”或负数字?

2024-04-25 19:27:45 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,关于我之前的问题(下面的链接)。现在我的两个函数使用原始输入和validate作为有效的int/float。我不希望零(0)和负数被允许,但我似乎无法完成它。 代码段:

def salary_check(self):

    input_counter = 0  # local variable

    self.salary = None

    while not self.salary:

        sal = raw_input('Enter your salary: ')

        try:
            self.salary = float(sal)

        except:
            print ("Invalid salary amount!")
            if input_counter >= 6:
                print ("No more tries! No loan!")
                sys.exit(0)

        input_counter += 1

    return self.salary

Cannot pass returned values from function to another function in python


Tags: 函数noselfinput链接代码段counterfunction
2条回答

这可能是使用assert语句的好时机。assert计算布尔值,如果为false,则抛出AssertionError。我建议这样做是因为您的代码在所讨论的区域中已经有了一个try/except块,这样就避免了额外的if...else...语句。你知道吗

代码的相关部分:

while not self.salary:

    sal = raw_input('Enter your salary: ')

    try:
        self.salary = float(sal)
        assert self.salary > 0

    except:
        print ("Invalid salary amount!")
        self.salary = ""  #This is important so that your while condition holds true; 
                          #the empty string will evaluate till false, 
                          #clearing the 0 or negative number inputted
        if input_counter >= 6:
            print ("No more tries! No loan!")
            sys.exit(0)

    input_counter += 1

这样,当有人输入0或一个小于0的数字时,它抛出一个AssertionError,被你的except捕获

更改此项:

try:
    self.salary = float(sal)

对此:

try:
    self.salary = float(sal)
    if self.salary <= 0:
            raise Exception

它会进入你的大脑,除非它是零或负。你的另一个代码已经捕捉到了。你知道吗

编辑:对不起,刚才在我手机上做这个。现在应该可以了。你知道吗

相关问题 更多 >

    热门问题