简体   繁体   English

不确定python函数

[英]Not sure about python function

I am only starting and getting mad over this function (it gives me the wrong outputs): 我只是开始对此功能感到生气(它给了我错误的输出):

def rental_car_cost(days):
    x = 40
    if days < 2:
        return days*x
    elif days >= 3:
        return days*x-20
    elif days>= 7:
        return days*x-50
    else:
        print "Please enter nr of days"

Also, how do I make sure that a number is entered for "days"? 另外,如何确保输入“天”的数字?

Not sure what you are expecting, however change the order of the elif conditions: 不确定您期望什么,但是更改elif条件的顺序:

def rental_car_cost(days):
    if isinstance(days, int):
        x = 40
        if days < 2:
            return days*x
        elif days >= 7:
            return days*x-50
        elif days>= 3:
            return days*x-20
    else:
        print "Please enter nr of days"

The days>= 7 and else clauses never trigger, because the earlier days >= 3 triggers on the same inputs. days>= 7else子句从不触发,因为前days >= 3在相同的输入上触发。 if / elif / else clauses are processed in order until one of them is triggered. if / elif / else子句按顺序处理,直到其中一个被触发。

What you need are clauses for days < 2 , days < 7 and else . 你需要哪些条款days < 2 days < 7else

To detect non-numbers, start with 要检测非数字,请从

if not isinstance(days, int):

which does a type check for integers. 进行类型检查整数。

rental_car_cost(2) should equal 60 rental_car_cost(2)应该等于60

But, none of your if statements will match 2. 2 isn't less than 2, nor is it greater than or equal to 3, nor is it greater than or equal to 7. Follow the advise from the other two answers by larsmans and Ankit Jaiswal also, but I'm assuming 2 should match the days*x-20 part. 但是,您的所有if语句都不会匹配2。2不小于2,也不大于或等于3,也不大于或等于7。请遵循larsmans和其他两个答案的建议Ankit Jaiswal也是,但是我假设2应该匹配days*x-20部分。 Just change elif days >= 3: to elif days >= 2: . 只需将elif days >= 3:更改为elif days >= 2:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM