Functions
Defining and calling functions
Introduction
In this lesson, you'll learn about functions in Python. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with defining and calling functions.
Python has its own approach to defining and calling functions, which we'll explore step by step.
The Python Way
Let's see how Python handles this concept. Here's a typical example:
# Function definition
def greet(name):
return "Hello, " + name + "!"
# Lambda (like arrow functions)
add = lambda a, b: a + b
# Default parameters
def greet(name="World"):
return f"Hello, {name}!"Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
// Function declaration
function greet(name) {
return "Hello, " + name + "!";
}
// Arrow function
const add = (a, b) => a + b;
// Default parameters
function greet(name = "World") {
return `Hello, ${name}!`;
}You may be used to different syntax or behavior.
Python uses def keyword instead of function
You may be used to different syntax or behavior.
Python uses indentation instead of curly braces
You may be used to different syntax or behavior.
Lambda is Python's version of arrow functions
Step-by-Step Breakdown
1. Function Definition
Use def keyword and colon. Body is indented.
function greet(name) {
return "Hello";
}def greet(name):
return "Hello"2. Lambda Functions
Python lambdas are limited to single expressions.
const add = (a, b) => a + b;add = lambda a, b: a + bCommon Mistakes
When coming from JavaScript, developers often make these mistakes:
- Python uses def keyword instead of function
- Python uses indentation instead of curly braces
- Lambda is Python's version of arrow functions
Key Takeaways
- def keyword for functions
- Indentation defines blocks
- Lambdas for simple single-expression functions