30-Day Coding Challenge
Days 24, 25, & 26 — Match Case and Illness
3 more days have gone by. And I’m halfway into the 4th week of my challenge.
Days 24 and 25 were really fun days of coding and discovery. But yesterday (day 26), I fell sick.
While I hate having setbacks, there was nothing I could do. My PC remained closed all day.
I’m better but still feeling weird. You’ll always know when something’s wrong with your body functions.
Anyway, while I have the strength to do so, here’s my top highlight from days 24 & 25 — Match Case Statements!
Match Case
It’s been a while since I’ve doubted the need for a function or method in Python. But I honestly felt that way about the Match Case
statement.
After all, it works the same way as the if else
statement. The only difference is the syntax:
def describe_number(number):
match number:
case 1:
return "One"
case 2:
return "Two"
case 3:
return "Three"
case _:
return "Other number"
# OUTPUTS:
print(describe_number(1)) # Output: One
print(describe_number(4)) # Output: Other number
Whereas, when written with if else
, it’ll look like this:
def describe_number(number):
if number == 1:
return "One"
elif number == 2:
return "Two"
elif number == 3:
return "Three"
else:
return "Other number"
# OUTPUTS
print(describe_number(1)) # Output: One
print(describe_number(4)) # Output: Other number
The difference? Well, other than currently being a good alternative to if else
, I don’t see any difference in the way match case
operates.
Although, I understand if some programmers find it better since it’s cleaner and more straightforward.
But I’ll be sticking to if else
for now. And like I always do, I’m committing this to memory. Who knows when it’ll come in handy?
It’s day 27 and I haven’t done any coding yet. I hope to get at least a few things done before the day runs out.
Thanks for reading, and see you in my next report…