Start learning free

LESSON 598 OF 635 · OBJECT-ORIENTED PROGRAMMING

Custom Greeting in Python

Practice

You build three classes that greet people.

Greeter is the plain one. PirateGreeter and FormalGreeter inherit from it.

Each class has a method greet(name). Each child overrides it with its own version.

  • In Greeter, greet(name) returns "Hello, <name>".
  • In PirateGreeter, it returns "Ahoy, <name>!".
  • In FormalGreeter, it returns "Good day, <name>.".

Each input line is a kind of greeter, then a person's name. The kinds are greeter, pirate and formal.

For each line, the test code makes that greeter and prints what greet(name) returns.

Where variables have types, the test code keeps each greeter in a Greeter variable. The override still decides the greeting.

C++ and C# mark the parent's method virtual. Kotlin marks it open. C# spells the method Greet.

 

Example 1:

Input:
    greeter Ann
    pirate Bob
    formal Cy
Output:
    Hello, Ann
    Ahoy, Bob!
    Good day, Cy.
Explanation: Each greeter answers with its own version of greet.

Example 2:

Input:
    pirate Mia
    formal Mia
    greeter Mia
Output:
    Ahoy, Mia!
    Good day, Mia.
    Hello, Mia
Explanation: The same name gets three different greetings.

Example 3:

Input:
    formal Lee
    pirate Jack
    formal Max
Output:
    Good day, Lee.
    Ahoy, Jack!
    Good day, Max.
Explanation: No plain greeter here.
Each line still gets its own greeting.

 

Constraints:

  • A name is one word of 1 to 20 English letters.
  • 1 to 100 lines per test case.
STEP 1 OF 6
    Ctrl + Enter to check

    Custom Greeting in Python

    Keep going with Python500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free