The function below is not returning the correct values. Can you figure out why?
def get_planet_name(id):
# This doesn't work; Fix it!
name=""
switch id:
case 1: name = "Mercury"
case 2: name = "Venus"
case 3: name = "Earth"
case 4: name = "Mars"
case 5: name = "Jupiter"
case 6: name = "Saturn"
case 7: name = "Uranus"
case 8: name = "Neptune"
return name
get_planet_name(3) # Should return "Earth"
Good luck!
This challenge comes from jhoffner on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (10)
switch
statements don't exist in Python like they do in some other languages. We can use a dictionary instead:I'm gonna do the traditional way:
this is the correct answer (: Python intentionally shunned the switch statement because it's easy to make mistakes, especially with languages which allow fall-through (:
Haskell
There is no switch statement in Python (which this appears to be).
I think the best replacement would be to use a dictionary and ideally use a try/except to do something if the index is out of range:
Because it's Python.
My solution :
Or another one :
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.
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.
Here is what I came up with:
I also tested it, the output is 100% correct
No return or break statements, but yes, Python Dicts were the solution to this.