JS
PY

JavaScript to Python

10 lessons

Progress0%
1Variables and Constants2Functions3Arrays vs Lists4Objects vs Dictionaries5Classes and OOP6Modules and Imports7Array Methods vs Comprehensions8Error Handling9Async Programming10File I/O
All Mirror Courses
JS
PY
Functions
MirrorLesson 2 of 10
Lesson 2

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.

Mirror Card
JS
From JavaScript:

In JavaScript, you're familiar with defining and calling functions.

PY
In Python:

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:

PY
Python 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:

JS
JavaScript (What you know)
// 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}!`;
}
Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

PY
In Python:

Python uses def keyword instead of function

Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

PY
In Python:

Python uses indentation instead of curly braces

Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

PY
In Python:

Lambda is Python's version of arrow functions

Step-by-Step Breakdown

1. Function Definition

Use def keyword and colon. Body is indented.

JS
JavaScript
function greet(name) {
  return "Hello";
}
PY
Python
def greet(name):
    return "Hello"

2. Lambda Functions

Python lambdas are limited to single expressions.

JS
JavaScript
const add = (a, b) => a + b;
PY
Python
add = lambda a, b: a + b
Common Pitfall
Python lambdas can only contain a single expression, not statements or multiple lines.

Common 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
Common Pitfall
Don't assume Python works exactly like JavaScript. While the concepts may be similar, the syntax and behavior can differ significantly.

Key Takeaways

  • def keyword for functions
  • Indentation defines blocks
  • Lambdas for simple single-expression functions
Rule of Thumb
The best way to learn is by doing. Try rewriting some of your JavaScript code in Python to practice these concepts.
PreviousNext