Person Class

Write a Python program to create a class Person with attributes for name and age. Write a method greeting to return a greeting message with the person’s name.

Example 1:

Input: person = Person('John', 25), person.greeting()

Output: 'Hello, John!'

Example 2:

Input: person = Person('Emma', 30), person.greeting()

Output: 'Hello, Emma!'

Begin by defining the class Person and initialize name and age inside the __init__ function. Then, create a method greeting to return a greeting with the person’s name.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greeting(self):
        return 'Hello, ' + self.name + '!'

person = Person('John', 25)
print(person.greeting())  # Output: Hello, John!

person = Person('Emma', 30)
print(person.greeting())  # Output: Hello, Emma!

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!