Reputation: 83
I was working through a Python problem sheet and answered the following question
You are driving a little too fast, and a police officer stops you. Write a function to return one of 3 possible results: "No ticket", "Small ticket", or "Big Ticket". If your speed is 60 or less, the result is "No Ticket". If speed is between 61 and 80 inclusive, the result is "Small Ticket". If speed is 81 or more, the result is "Big Ticket". Unless it is your birthday (encoded as a boolean value in the parameters of the function) -- on your birthday, your speed can be 5 higher in all cases.
def caught_speeding(speed, is_birthday):
if is_birthday:
speeding = speed - 5
else:
speeding = speed
if speeding < 60:
print("No ticket")
if 60 < speeding <= 80:
print("Small Ticket")
if speeding > 80:
print("Big Ticket")
The given answer however used elif and else clauses. Is there a reason that it is better to use elif and else clauses? Or is it just personal preference?
Thank you for the help!
Upvotes: 0
Views: 1559
Reputation: 91
Here's another solution for it.
def caught_speeding(speed, is_birthday):
if is_birthday:
ll=60+5
ul=80+5
else:
ll=60
ul=80
if speed<=ll:
return "No Ticket"
elif ll<speed<=ul:
return "Small Ticket"
else:
return "Big Ticket"
Upvotes: 1
Reputation: 17322
you can write less code and also be easier to read + improve your code speed:
def caught_speeding(speed, is_birthday):
if is_birthday:
speed -= 5
if speed <= 60:
print("No ticket")
elif <= 80:
print("Small Ticket")
else:
print("Big Ticket")
Upvotes: 1
Reputation: 60
It would boil down to performance depending on the stated questions.
If -> Else If, would end that check once a solution is found.
IF -> IF -> IF would do a check for each occurance of IF, which is larger or more complex data sets would cause performance Issues.
Upvotes: 1
Reputation: 222352
Well, note that your solution is wrong, since it omits any case for speed
being 60. An if … elif … elif … else …
structure partitions the possibilities: Every possibility falls into one and only one case (or, if the else
is omitted, at most one case). If partitioning is desired, which it often is, a structure of if … if … if …
has two foibles:
speeding <= 60
and 60 < speeding
.…
code in the if
cases, we change variables, sometimes variables that are used in the test conditions, and that can make subsequent if
tests evaluate to true even though we want them to be false. The elif
construction avoids this.Upvotes: 1
Reputation: 1471
In this type of cases, if and elif both achieve the same thing logically, because only 1 of the if conditions will be true
But the added advantage using elif is that, if the if
condition already matches, the elif statements aren't executed at all. This increases performance and is also logical because you need not check other conditions if one already matched.
Upvotes: 1