← Back to BlogTutorial

Python Basics for Streamlit: What You Actually Need to Know

April 2026 Β· 8 min read

Streamlit is the fastest way to build interactive finance tools with Python. But many people stall at the step before: how much Python do I actually need to know? The answer is less than you think. These 10 concepts cover 90% of what you'll use in real Streamlit apps.

1. Variables and Data Types

Python doesn't require declaring a variable's type β€” just assign a value and Python infers it. The types you'll use most in Streamlit are: integers (int), decimals (float), text (str) and booleans (bool).

# Integers and floats
revenue     = 480_000        # int β€” underscores for readability
growth_rate = 0.12           # float β€” 12%
margin      = 42.5           # float β€” percentage

# Strings
company     = "Acme Ltd"
region      = "UK"

# Booleans
is_profitable = True
has_debt      = False

# f-strings β€” format values into text
label = f"{company}: Β£{revenue:,} revenue, {margin}% margin"
print(label)
# β†’ Acme Ltd: Β£480,000 revenue, 42.5% margin

In Streamlit, variables are recalculated on every script rerun. They're not persistent β€” use st.session_state to keep values alive between widget interactions.

2. Lists and Dictionaries

Lists store ordered collections of values. Dictionaries store key-value pairs. Both appear constantly in Streamlit: for selectbox options, for grouping configuration data, and for passing parameters to chart functions.

# Lists β€” ordered, indexed from 0
regions   = ["UK", "US", "EU", "APAC"]
years     = [2022, 2023, 2024, 2025]
revenues  = [420_000, 480_000, 530_000, 610_000]

# Access by index
first  = regions[0]     # "UK"
last   = regions[-1]    # "APAC"
subset = regions[1:3]   # ["US", "EU"]

# Dictionaries β€” key:value pairs
company = {
    "name":    "Acme Ltd",
    "revenue": 480_000,
    "margin":  42.5,
    "region":  "UK",
}
print(company["name"])           # "Acme Ltd"
print(company.get("ceo", "N/A")) # "N/A" β€” safe access with default

# In Streamlit: lists power dropdowns
import streamlit as st
region = st.selectbox("Region", regions)          # list as options
year   = st.selectbox("Year",   years, index=2)   # default = 2024

3. Conditionals (if / elif / else)

Conditional logic controls what gets displayed and calculated based on widget values. It's the primary mechanism for building dynamic Streamlit apps that react to user input.

import streamlit as st

revenue = st.number_input("Annual Revenue Β£", value=500_000)
costs   = st.number_input("Total Costs Β£",    value=380_000)
profit  = revenue - costs
margin  = profit / revenue * 100 if revenue > 0 else 0

# Conditional display
if margin >= 30:
    st.success(f"Strong margin: {margin:.1f}%")
elif margin >= 15:
    st.warning(f"Acceptable margin: {margin:.1f}%")
elif margin > 0:
    st.warning(f"Thin margin: {margin:.1f}% β€” review cost structure")
else:
    st.error(f"Loss-making: {margin:.1f}%")

# Conditional sections
show_breakdown = st.checkbox("Show cost breakdown")
if show_breakdown:
    st.write(f"Revenue: Β£{revenue:,}")
    st.write(f"Costs:   Β£{costs:,}")
    st.write(f"Profit:  Β£{profit:,}")

4. Functions

Functions encapsulate reusable logic. In Streamlit you'll use them primarily two ways: wrapping data loads in @st.cache_data decorated functions, and encapsulating financial calculations in pure functions (no side effects) that are easy to test.

import streamlit as st
import pandas as pd

# Pure function β€” takes inputs, returns output, no side effects
def gross_margin(revenue: float, cogs: float) -> float:
    if revenue == 0:
        return 0.0
    return (revenue - cogs) / revenue * 100

def loan_payment(principal: float, annual_rate: float, years: int) -> float:
    r = annual_rate / 12
    n = years * 12
    if r == 0:
        return principal / n
    return principal * r * (1 + r) ** n / ((1 + r) ** n - 1)

# Cached function β€” runs once, then returns from cache
@st.cache_data(ttl=3600)
def load_data(path: str) -> pd.DataFrame:
    return pd.read_csv(path, parse_dates=["Date"])

# Usage in the app
revenue = st.number_input("Revenue Β£", value=500_000)
cogs    = st.number_input("COGS Β£",    value=300_000)
st.metric("Gross Margin", f"{gross_margin(revenue, cogs):.1f}%")

Type annotations (revenue: float) are optional but highly recommended β€” they make code more readable and help IDEs catch errors before you run anything.

5. Loops and List Comprehensions

For loops iterate over collections. List comprehensions are their compact version β€” very common in real Python. In Streamlit you'll use them to generate columns, metric cards and selectbox options dynamically.

import streamlit as st

kpis = [
    ("Revenue",      "Β£480k", "+12%"),
    ("Gross Margin", "42%",   "+2pp"),
    ("EBITDA",       "Β£96k",  "+18%"),
    ("Cash",         "Β£210k", "+5%"),
]

# Loop to generate metric cards
cols = st.columns(len(kpis))
for col, (label, value, delta) in zip(cols, kpis):
    col.metric(label, value, delta)

# List comprehension β€” build a list in one line
years   = [2020, 2021, 2022, 2023, 2024]
revenue = [320_000, 380_000, 440_000, 490_000, 560_000]

# Calculate YoY growth for each year (skip first)
growth = [
    (revenue[i] - revenue[i-1]) / revenue[i-1] * 100
    for i in range(1, len(revenue))
]
# β†’ [18.75, 15.79, 11.36, 14.29]

6. Pandas β€” The Most Important Library

Pandas is the heart of almost every Streamlit finance app. A DataFrame is a table with rows and columns β€” think of it as an Excel spreadsheet with programmable superpowers. The most important operations to master: load, filter, group and export.

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
    "Date":     ["2024-01", "2024-02", "2024-03", "2024-04"],
    "Region":   ["UK", "UK", "US", "US"],
    "Revenue":  [120_000, 135_000, 200_000, 190_000],
    "Costs":    [ 80_000,  88_000, 130_000, 125_000],
})
df["Date"]   = pd.to_datetime(df["Date"])
df["Profit"] = df["Revenue"] - df["Costs"]
df["Margin"] = df["Profit"] / df["Revenue"] * 100

# Filter rows
uk_only = df[df["Region"] == "UK"]

# Group and aggregate
by_region = (
    df.groupby("Region")
    .agg(Total_Revenue=("Revenue","sum"), Avg_Margin=("Margin","mean"))
    .reset_index()
)

# In Streamlit
import streamlit as st
st.dataframe(df, use_container_width=True, hide_index=True)
st.dataframe(by_region.style.format({"Total_Revenue": "Β£{:,.0f}", "Avg_Margin": "{:.1f}%"}))

7. Imports and Libraries

Python has a huge ecosystem of libraries. In Streamlit finance apps, you'll use the same 6–8 libraries repeatedly. You don't need to memorise their entire API β€” just the functions that appear in 80% of projects.

# The core finance app stack
import streamlit as st          # UI and layout
import pandas as pd             # DataFrames and data manipulation
import numpy as np              # Numerical calculations
import plotly.express as px     # Interactive charts
import plotly.graph_objects as go  # Fine-grained chart control
from io import BytesIO          # In-memory file buffer for exports
import requests                 # API calls
import yfinance as yf           # Stock and financial data

# Import only what you need from a module
from datetime import date, timedelta
from pathlib import Path

# Alias long names for convenience
import matplotlib.pyplot as plt  # Matplotlib β€” static charts

Add all of these to your project's requirements.txt so Streamlit Cloud or Railway install them automatically on deploy.

8. Error Handling

Finance apps receive user input and external data β€” both sources can fail. The try/except block prevents a single error from crashing the entire app. In Streamlit, combine it with st.error() to show helpful messages instead of stack traces.

import streamlit as st
import pandas as pd
import requests

# Handle file upload errors
uploaded = st.file_uploader("Upload CSV", type=["csv"])
if uploaded:
    try:
        df = pd.read_csv(uploaded)
        required = {"Date", "Revenue", "Region"}
        missing  = required - set(df.columns)
        if missing:
            st.error(f"Missing columns: {', '.join(missing)}")
            st.stop()
        st.success(f"Loaded {len(df):,} rows")
    except Exception as e:
        st.error(f"Could not read file: {e}")
        st.stop()

# Handle API errors
@st.cache_data(ttl=300)
def get_rates(base: str) -> dict:
    try:
        r = requests.get(f"https://api.example.com/rates?base={base}", timeout=10)
        r.raise_for_status()
        return r.json()
    except requests.Timeout:
        st.warning("API timed out β€” showing cached data")
        return {}
    except requests.HTTPError as e:
        st.error(f"API error: {e}")
        return {}

9. What You Don't Need (Yet)

Many people delay learning Streamlit because they assume they need to master full object-oriented programming (classes, inheritance, magic methods), advanced decorators, async programming or machine learning algorithms. You don't need any of that to build useful, professional finance apps.

  • βœ—Classes and OOP β€” useful, but not required for Streamlit
  • βœ—Async programming (async/await) β€” Streamlit handles concurrency for you
  • βœ—ML algorithms β€” unless your app specifically needs them
  • βœ—Custom decorators β€” @st.cache_data is the only one you'll use routinely
  • βœ“Variables, lists, dicts, functions, if/else, loops β€” everything above is enough to start

10. Putting It Together β€” A Complete App

This example app uses every concept above: variables, lists, functions, pandas, conditionals and error handling. It's a gross margin calculator with CSV export β€” 40 lines, fully functional.

import streamlit as st
import pandas as pd
import plotly.express as px

st.title("Gross Margin Analyser")

# ── Input ──────────────────────────────────────────
months  = ["Jan","Feb","Mar","Apr","May","Jun",
           "Jul","Aug","Sep","Oct","Nov","Dec"]
revenue = [st.number_input(f"{m} Revenue Β£", value=40_000 + i*2_000, key=f"rev_{i}")
           for i, m in enumerate(months)]
cogs    = [r * 0.6 for r in revenue]          # assume 60% COGS

# ── Calculate ──────────────────────────────────────
df = pd.DataFrame({
    "Month":   months,
    "Revenue": revenue,
    "COGS":    cogs,
    "Profit":  [r - c for r, c in zip(revenue, cogs)],
    "Margin":  [(r - c) / r * 100 if r > 0 else 0 for r, c in zip(revenue, cogs)],
})

# ── KPIs ───────────────────────────────────────────
col1, col2, col3 = st.columns(3)
col1.metric("Total Revenue", f"Β£{df['Revenue'].sum():,.0f}")
col2.metric("Total Profit",  f"Β£{df['Profit'].sum():,.0f}")
col3.metric("Avg Margin",    f"{df['Margin'].mean():.1f}%")

# ── Chart ──────────────────────────────────────────
fig = px.bar(df, x="Month", y="Profit", color="Margin",
             color_continuous_scale="RdYlGn", title="Monthly Profit & Margin")
st.plotly_chart(fig, use_container_width=True)

# ── Export ─────────────────────────────────────────
st.download_button("⬇ Download CSV", df.to_csv(index=False), "margin.csv", "text/csv")

Where to Go Next

With these concepts you can build real finance tools. The next step is learning how to structure multi-page apps, connect to external data sources (APIs, databases) and deploy to production. All of that is covered in the interactive Streamlit lessons on FinancePlots.

Share this article