Skip to content

How to Get Planet Name By ID in Python

The challenge

Create a function that takes in an id and returns the planet name.

The solution in Python code

Option 1:

def get_planet_name(id): return { 1: "Mercury", 2: "Venus", 3: "Earth", 4: "Mars", 5: "Jupiter", 6: "Saturn", 7: "Uranus" , 8: "Neptune" }[id]
Code language: Python (python)

Option 2:

def get_planet_name(id): return ["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"][id-1]
Code language: Python (python)

Option 3:

def get_planet_name(id): if id == 1: return "Mercury" elif id == 2: return "Venus" elif id == 3: return "Earth" elif id == 4: return "Mars" elif id == 5: return "Jupiter" elif id == 6: return "Saturn" elif id == 7: return "Uranus" elif id == 8: return "Neptune"
Code language: Python (python)

Test cases to validate our solution

import test from solution import get_planet_name @test.describe("Fixed Tests") def fixed_tests():'Basic Test Cases') def basic_test_cases(): test.assert_equals(get_planet_name(2), 'Venus') test.assert_equals(get_planet_name(5), 'Jupiter') test.assert_equals(get_planet_name(3), 'Earth') test.assert_equals(get_planet_name(4), 'Mars') test.assert_equals(get_planet_name(8), 'Neptune') test.assert_equals(get_planet_name(1), 'Mercury')
Code language: Python (python)

See also  How to Reorder Data in Log Files using Python
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x