HomeCourseModule 08 › =PY() — the first ten formulas

=PY() — the first ten formulas

Module 08 · Python inside Excel — =PY()9 min readBeginner

What you'll learn

  • Enter a =PY() formula
  • Commit with Ctrl+Enter (not just Enter)
  • Output as Python object vs Excel values

The syntax

  1. Click an empty cell.
  2. Type =PY( — Excel switches the cell into Python mode. A green "PY" badge appears.
  3. Write your Python.
  4. Press Ctrl+Enter (Windows) / Cmd+Enter (Mac) to commit.

Don't just hit Enter — that adds a newline inside the cell. Ctrl+Enter is the "submit" key.

Ten warm-up formulas

# 1 — basic math
=PY(1 + 1)                # 2

# 2 — a variable
=PY(
x = 100
x * 1.08
)                         # 108

# 3 — string
=PY("hello".upper())      # HELLO

# 4 — list aggregation
=PY(sum([10, 20, 30]))    # 60

# 5 — current date
=PY(
from datetime import date
date.today()
)

# 6 — a Series
=PY(
import pandas as pd
pd.Series([1, 2, 3, 4, 5]).mean()
)                         # 3.0

# 7 — a small DataFrame
=PY(
import pandas as pd
pd.DataFrame({"x": [1,2,3], "y": [4,5,6]})
)

# 8 — random
=PY(
import random
random.choice(["heads", "tails"])
)

# 9 — string manipulation
=PY("alice@example.com".split("@")[1])   # example.com

# 10 — sorted list
=PY(sorted([3, 1, 4, 1, 5, 9, 2, 6]))

Output mode: Python object vs Excel values

By default, a =PY() cell shows a Python object — a single cell that holds (say) a whole DataFrame. To spill the contents into proper Excel cells:

  1. Right-click the cell.
  2. Output as → Excel values.
  3. The DataFrame spills into a range. Headers become column headers, rows become rows.

Toggle back to Python-object mode if you want to use the cell's value in another =PY() formula.

Walkthrough: build a summary cell

Put some numbers in A1:A10

Type any 10 numbers in cells A1 through A10.

In B1, write =PY()

=PY(
xl("A1:A10").mean()
)

The xl(...) helper grabs an Excel range as a pandas Series or DataFrame. .mean() averages it.

Try a more useful summary

=PY(
s = xl("A1:A10")
{"count": s.count(),
 "sum":   s.sum(),
 "mean":  s.mean(),
 "min":   s.min(),
 "max":   s.max()}
)

Right-click → Output as → Excel values. The dict spills into a two-column table.

Key takeaways

  • =PY( + your Python + Ctrl+Enter.
  • xl("A1:A10") brings an Excel range into Python as a Series/DataFrame.
  • Right-click → Output as → Excel values to spill the result into cells.

Calculator cell

In a fresh workbook, put numbers in A1:A20. In B1, write a =PY() formula that computes the median. In B2, one that computes the standard deviation.

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.