Skip to content

Functions and Classes

First PublishedByAtif Alam
def greet(name):
return f"Hello, {name}"
def add(a, b):
return a + b

Optional default arguments:

def say(msg, prefix=">"):
return f"{prefix} {msg}"
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hi, I'm {self.name}"
p = Person("Alice", 30)
p.greet() # "Hi, I'm Alice"
  • __init__ is the constructor; self is the instance.
  • Methods take self as the first parameter. You can nest data (attributes) and behavior (methods) in a class.