FunctionsLesson 1 of 3
Function Basics
Functions in Python are defined with def instead of function. No curly braces: just a colon and indentation, like conditionals. Arrow functions become lambdas, but lambdas are limited to a single expression.
The real upgrade is keyword arguments. In JS, if a function takes 5 parameters, you have to remember the order or pass an options object and destructure it. Python lets you call greet(greeting="Hi", name="Alice"), specifying arguments by name in any order. This makes function calls self-documenting, and it removes most of the reasons JS code uses options objects.
Python also has **kwargs, which collects any extra named arguments into a dictionary. It plays the role of the JS 'options object' pattern, but the caller just passes normal named arguments instead of building an object. Combined with *args (which collects extra positional arguments into a tuple, like JS rest parameters), this gives you a lot of flexibility.
Parameter ordering is strict. The order is: regular parameters (those with defaults after those without), then *args, then keyword-only parameters, then **kwargs. def fn(a, b=2, *args, option=True, **kwargs) is valid. Getting the order wrong is a SyntaxError.
Lambda functions are limited to a single expression. You cannot put statements (if blocks, for loops, assignments) inside a lambda. If your logic is more than one line, use a regular def function. A lambda returns its expression automatically; you never write return inside it.
Quick reference
| JavaScript | Python | Note |
|---|---|---|
| function greet(name) {} | def greet(name): | def keyword, colon, indent |
| (a, b) => a + b | lambda a, b: a + b | Single expression only |
| ...args (rest) | *args | Collects into a tuple |
| fn(a, { verbose: true }) | fn(a, verbose=True) | Named args replace options objects |
| function fn(a, opts = {}) | def fn(a, **kwargs): | Extra named args land in a dict |
| fn(a, b) | fn(b=2, a=1) | Can name args in any order |
| return undefined | return None | Implicit return is None |
Side by side
// JavaScript
function greet(name, greeting = "Hello") {
return `${greeting}, ${name}!`;
}
const add = (a, b) => a + b;
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
function create(name, opts = {}) {
return { name, ...opts };
}# Python
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
add = lambda a, b: a + b
def total(*numbers): # *args = rest
return sum(numbers)
def create(name, **kwargs): # **kwargs = extra named args
return {"name": name, **kwargs}
create("box", color="red", size=3)
# Named arguments in any order!
greet(greeting="Hi", name="Alice")
# Type hints (optional)
def add_typed(a: int, b: int) -> int:
return a + bExercise
Real Python, running in your browserWrite a Python function called build_profile:
Ctrl + Enter runCtrl + Shift + Enter checkTab indentEsc then Tab to leave the editorCtrl + / comment