Bird
Raised Fist0

What will be the output of this Python code?

medium📝 Predict Output Q13 of Q15
Python - Object-Oriented Programming Foundations
What will be the output of this Python code?
def greet(name):
    return f"Hello, {name}!"

class Person:
    def __init__(self, name):
        self.name = name
    def greet(self):
        return greet(self.name)

p = Person("Anna")
print(p.greet())
ATypeError
BHello, name!
CHello, Anna!
DAttributeError
Step-by-Step Solution
Solution:
  1. Step 1: Understand the procedural function greet

    The function greet(name) returns the string "Hello, {name}!" with the given name.
  2. Step 2: Understand the Person class and method call

    The Person class stores the name and its greet method calls the procedural greet function with self.name. Creating p with name "Anna" and calling p.greet() returns "Hello, Anna!".
  3. Final Answer:

    Hello, Anna! -> Option C
  4. Quick Check:

    Class method calls procedural function correctly [OK]
Quick Trick: Class method calls function with self.name [OK]
Common Mistakes:
MISTAKES
  • Confusing variable name with string 'name'
  • Expecting error due to mixing styles
  • Forgetting to use self.name

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes