How to Get Planet Name By ID in Python

0 min read 135 words

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]

Option 2:

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

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"

Test cases to validate our solution

import test
from solution import get_planet_name

@test.describe("Fixed Tests")
def fixed_tests():
    @test.it('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')
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags