Lesson 10 · Intermediate · 15 min
Calculations and data with Python: reliable numbers in Gemini
Make Gemini run sandboxed Python code for arithmetic, numerical data analysis, and reliable table transformation without mental calculation.
- Goal
- You will trigger behind-the-scenes Python execution in Gemini to guarantee exact arithmetic and audit calculated figures.
- Skills
- Steer

Your first attempt, unaided
Provide a five-row expense table to Gemini and request the exact sum and percentage share per line by inspecting the generated code.
Large language models frequently miscalculate multi-step arithmetic when attempting mental math through token prediction alone. Gemini embeds an integrated, sandboxed Python code interpreter: the model automatically writes code, executes calculations programmatically in a secure runtime, and returns verifiable mathematical certainty backed by auditable source scripts.
1Integrated code interpreter: offloading math to a real runtime
The integrated code interpreter delegates complex mathematics to an actual Python runtime instead of relying on probabilistic token predictions. This technical architecture eliminates arithmetic inaccuracies common to generative models.
Because language models generate text based on statistical likelihoods, they often produce believable yet incorrect answers for multi-step multiplications or compounded ratios. Through its sandboxed code interpreter, Gemini writes Python code, runs the script in an isolated runtime, and returns the verified output. Users can upload spreadsheets to compute variances, medians, and compound growth rates with total precision.
Calculation approach Underlying engine Mathematical accuracy Recommended workplace scenario Direct text prediction Probabilistic language completion Inconsistent on figures above 4 digits Rough ballparks and high-level prose Sandboxed Python interpreter Real Python execution environment Absolute mathematical accuracy (100 %) Budgets, ratios, and audit schedules CSV spreadsheet analysis Pandas data science libraries Fully auditable analytical pipelines Data reconciliation and statistical models 

Diagram 'Exact calculations with built-in Python'Diagram generated by AI and reviewed 2Computing compound growth rates and variance without arithmetic risk
Computing compound growth rates and variance without arithmetic risk demonstrates how the Python interpreter prevents major calculation errors across complex multi-year financial datasets.
A corporate financial analyst must compute the compound annual growth rate (CAGR) and variance across ten operating fiscal years.
Weak prompt.
Here are annual operating expenses from 2015 to 2024 [paste table]. What is the average compound annual growth rate and variance?Gemini performs mental arithmetic via token generation and outputs a CAGR of 4.2% instead of the mathematically correct 5.8%.
Strong prompt.
Here are our annual operating expenses from 2015 to 2024. Write and execute a Python script to compute: 1) the exact compound annual growth rate ; 2) the sample variance. Display the executable Python code and briefly explain each calculation step in 60 words.The difference. Gemini triggers its Python sandbox, calculates figures using standard numerical libraries, and displays the underlying code, providing an auditable deliverable.
3Clean a dataset and compute dependable statistical medians
Clean a dataset and compute dependable statistical medians to practice enforcing Python execution whenever working with quantitative business data in Gemini.
Assemble a list of ten expense figures. Instruct Gemini to compute the mean, median, and interquartile range by generating and running an executable Python script.
Run this prompt:
'Based on the numbers provided below, write and execute a Python script to calculate the mean, median, and interquartile range. Format results in a 3-row summary table and include the complete Python script.'
Self-evaluation rubric: (a) the executed Python code block is visible in the answer ; (b) medians and quartiles derive from script execution ; (c) zero calculations rely on unverified mental arithmetic.
4Allowing Gemini to do mental math instead of enforcing code execution
Allowing Gemini to do mental math instead of enforcing code execution introduces subtle arithmetic errors into corporate planning documents and executive presentations.
If you simply ask 'Sum these 15 invoice balances', Gemini may take the easiest path and guess the total through text prediction rather than running code. While the result looks plausible, minor deviations can corrupt budget forecasts.
Fix: include the explicit command 'Write and execute Python code to compute this result' whenever your query involves financial or numerical data.
Rule to remember: use language models for prose; mandate Python execution for verifiable mathematics.
5Quiz
Three questions, instant feedback. Each option comes with an explanation.
6Proof of mastery
Share a numerical calculation in Gemini using code execution: submit the arithmetic query, the generated Python script, and the verified numerical outcome.
This lesson counts towards the Intermediate badgeSee the four badges
Criteria
What you wrote at the start of the lesson
Going further
Examine glossary entries for code interpreter and auditability. The next lesson, Google Workspace extensions: Drive, Docs, and Gmail, links Gemini to enterprise data. For rigorous quality validation, see Test sets and robustness.
Frequently asked questions
Why do raw LLMs frequently fail at arithmetic?
Language models predict text tokens; they lack a native CPU math unit. Without code execution, they guess mathematical outcomes probabilistically, leading to carryover and rounding errors.
How can you tell if Gemini executed Python code?
A small expandable toggle labeled 'View code' or 'Python' appears below the response. Click it to inspect the actual generated script and standard output.
Does my data leave the secure perimeter during code execution?
Python runs within an isolated sandbox hosted within Google's enterprise infrastructure, adhering to the same data boundaries as the foundation model.