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"?
-
Give us an example of actual vs expected outputs, and explain how the function is supposed to behave. Also, ask one question per question, please.Henry Keiter– Henry Keiter2013年06月19日 16:30:41 +00:00Commented Jun 19, 2013 at 16:30
-
rental_car_cost(2) should equal 60, but it gives me "please enter nr of days"aaaa– aaaa2013年06月19日 16:33:37 +00:00Commented Jun 19, 2013 at 16:33
-
3@aaa Well, 2 is not less than 2, nor is it greater than or equal to either 3 or 7, so it is only doing what you asked it to...twalberg– twalberg2013年06月19日 16:37:13 +00:00Commented Jun 19, 2013 at 16:37
3 Answers 3
Not sure what you are expecting, however change the order of the elif conditions:
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"
2 Comments
The days>= 7 and else clauses never trigger, because the earlier days >= 3 triggers on the same inputs. if/elif/else clauses are processed in order until one of them is triggered.
What you need are clauses for days < 2, days < 7 and else.
To detect non-numbers, start with
if not isinstance(days, int):
which does a type check for integers.
3 Comments
isinstance(days, (int, long)). Although in this context it shouldn't matter I suppose.
rental_car_cost(2)should equal 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. Just change elif days >= 3: to elif days >= 2:.