Skip to content

Instantly share code, notes, and snippets.

@OkiStuff
Last active January 2, 2022 02:57
Show Gist options
  • Save OkiStuff/759ad12807fed62ebe4a4775e51c4098 to your computer and use it in GitHub Desktop.
Save OkiStuff/759ad12807fed62ebe4a4775e51c4098 to your computer and use it in GitHub Desktop.
DIY Switch statement tutorial in Python
# This is an example of switch statements in Python
# Switch statements are not a part of libpython (my nickname for the python standard library) or the Python Language Standard
# But they are very easy to DIY, and they improve readability, and performance!!
# Lets say we want to return the age for a passed name
def get_age(name):
# You might think to start writing if statements, and for something small, that is fine. But they can get real messy and hard to edit
# Let's use a DIY switch statement instead!!!
switch = {
"John": 22,
"Mark": 13,
"Daniel": 16,
"Bob": 19,
"Julia":33
}
# What we just made is a dictionary, it's sorta like python's built in version of JSON.
# Dictionaries allows us to set a key (the value to the left of the ':') and a pair (the value to the right of the ':')
return switch.get(name, "Invalid name")
# What we are now doing is getting the value of the key (the key is the name)
# This means we dont have to check if a name has a age paired to it
# We just try to get the age without checking if it exists
# But what if it doesnt exist?
# Well that is why we aren't just returning 'switch[name]' (which is valid python code!)
# The 'get' method automatically handles if there is no key with the name we passed.
# it just returns the second argument we passed if it can't find the key.
# For us we just set the second argument to be "Invalid name"
# That means if we pass a name that doesn't exist. It just returns "Invalid name"
# This is very easy to implement yourself, but why not let the language do it for you?
# Here we finally try the code
john_age = get_age("John")
daniel_age = get_age("Daniel")
bob_age = get_age("Bob")
julia_age = get_age("Julia")
# If we were to use if + elif + else statement instead of our DIY switch statement, the further we got down the list of names
# The longer it would take to return the age!
# But with switch statements, we ignore all the other names and just return the age of the passed name]
unknown_age = get_age("ALIENS!!!")
print(john_age)
print(daniel_age)
print(bob_age)
print(julia_age)
print(unknown_age)
"""
Output:
22
16
19
33
Invalid name
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment