DEV Community

Discussion on: Daily Challenge #233 - Get Planet Name by ID

Collapse
 
dak425 profile image
Donald Feury

I have two answers, first one assumes this is python, second assumes its pseudo-code

Python Answer

Python has no concept of switch statements like alot of other languages do. Could implement something similar with a dict.

planets = {
    1: "Mercury",
    2: "Venus",
    3: "Earth",
    4: "Mars",
    5: "Jupiter",
    6: "Saturn",
    7: "Uranus",
    8: "Neptune"
}

def get_planet_name(id):
    return planets.get(id, "")

print("Planet Name: ", get_planet_name(3))

Should give the desired result

Pseudo-Code Answer

Most languages that have switch statements, expect an explicit break inside of each case statement. Otherwise, when the first true case is found, ALL following case statements will execute ( I know PHP does this if you don't have a break in your case statement. )

Also, instead of initializing the variable at the beginning and returning it at the end, you could just have each case return the string.

This switch also has no default case, which could be used to just return the empty string, in the case of an invalid id being given.