Streamlit, Python, Pandas, SQL, Oh My! Flashcards

(87 cards)

1
Q

What does ‘import x as y’ do in Python?

A

It imports the module “x” and binds it to the local name “y”.
Example: import streamlit as st lets you call st.selectbox() instead of streamlit.selectbox().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is ‘from __future__ import annotations’ and why use it?

A

It postpones evaluation of type annotations to runtime (stores them as strings).
This avoids issues with forward references and can speed imports. In Python 3.11, it’s useful for types that refer to names defined later.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you handle exceptions with try/except?

A

Wrap risky code in try and handle failures in except.
Example:

try:
    current_user = fetch_user_access_direct()
except Exception as e:
    st.error(f"Error: {e}")
    st.stop()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What does ‘st.stop()’ imply from a Python control-flow perspective?

A

It’s a Streamlit-specific exception that halts further execution of the script for that run (like an early return/abort).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are truthy/falsey values and how are they used in validation?

A

Values like '', None, 0, 0.0, [], {} are falsey.
The code checks if val in (None, "") and special-cases 0.0 for amounts. Know that 0.0 is falsey but may be valid.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does dict.get(key, default) do?

A

It returns the value for key if present, else default.
Example: corporate_switch = current_user.get("corprt_sw", "N").

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you safely access and remove keys from dictionaries?

A

Use dict.get to read with a default; dict.pop(key, None) to remove if present without raising KeyError;
del dict[key] raises if missing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you build strings with f-strings and format specifiers?

A

Use f"...{expr:format}...".
Example currency: f"${{x:,.2f}}" yields comma separators and 2 decimals.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you join a list of strings?

A

Use ", ".join(items).
Example: ", ".join(missing_labels).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What does ‘startswith’ do for strings?

A

Returns True if the string starts with a prefix.
Used to branch on outcomes like outcome.startswith("Denied").

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How do you insert into a list at a specific (possibly negative) position?

A

list.insert(index, item). Negative index counts from the end.
Example: cols.insert(-4, "DNL_AMT") inserts 4 from the end.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you iterate with a for-loop and ‘continue’?

A

continue skips to the next iteration.
Example:

for k in base_required:
    if k not in st.session_state:
        missing.append(k)
        continue
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do you convert between types (int/float/str)?

A

Use int(x), float(x), str(x). Wrap in try/except for user input.
Example: float(st.session_state.denial_amt).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the difference between ‘==’ and ‘is’?

A

== checks value equality; is checks object identity. Use is None to check against None.
The code uses val in (None, "") which compares values, not identity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do raw strings help with regular expressions?

A

Prefix with r'' to avoid Python interpreting backslashes.
Example: re.search(r"ID:(\d+)\)", text).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you extract regex groups with ‘re.search’?

A

Use match = re.search(pattern, s) then match.group(1) for the first capturing group.
Cast to int if needed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is a context manager (‘with’ statement) conceptually?

A

with ensures setup/teardown around a block by calling \_\_enter\_\_/\_\_exit\_\_.
Streamlit uses it to place widgets in column containers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How do you write a simple helper function inside another function?

A

Define it with def name(...): ....
Example:

def quote(val):
    if val is None:
        return "NULL"
    return "'" + str(val).replace("'", "''") + "'"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How do you perform early returns in functions?

A

Use return to exit early after validation or guard checks. This keeps code paths clear.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How do you get today’s date with datetime?

A

Call datetime.date.today() to get today’s date.
Streamlit date_input accepts/returns datetime.date objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is a docstring and where is it used?

A

A triple-quoted string at the start of a function/module/class documenting purpose and behavior.
Example: def render_edit_billing_page(): """Render the Edit Billing page.""".

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What does ‘elif’ provide over nested ‘if’?

A

It creates mutually exclusive branches improving readability.
Used for outcome-dependent UI sections.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How do you use ‘sorted(iterable)’ with a list?

A

Returns a new sorted list.
Example: payors_list = sorted(load_meta_vals('PYR')['VAL_NAME'].tolist()).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How to safely build lists with comprehensions?

A

[expr for x in iterable if cond].
Example: [c for c in bills.columns if c.endswith("_META_VAL_ID")].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What is None in Python?
A singleton representing "no value". Compare with `is None`. Often used as default or missing sentinel.
26
What is the effect of placing function calls at module end?
Calling a function at the bottom (e.g., `add_billing_page()`) runs it at import/script execution time in Streamlit's run cycle.
27
Gotcha: Why can float() raise an exception?
Because empty strings aren't numeric. Always guard with try/except or check for `""` before casting.
28
Best practice: Narrow exception handling
Catching `Exception` is broad and may hide bugs. Prefer specific exceptions (e.g., `KeyError`, `ValueError`) when practical.
29
How do you render Markdown with Streamlit?
Use `st.markdown(markdown_str, unsafe_allow_html=True)` to allow raw HTML/CSS. Example: `st.markdown('### Add New Billing Record')`.
30
How do Streamlit columns work?
`cols = st.columns([1,5])` returns layout containers. Use `with cols[0]:` to render widgets inside a specific column.
31
How do you create a form and submit button in Streamlit?
Use `with st.form(key): ...` and `save = st.form_submit_button("Save")`. Widgets inside the form only trigger on submission.
32
What is st.session_state and how is it used?
A dict-like store for widget values and custom state across reruns. Access via `st.session_state['key']` or `.get`/`.pop`.
33
How do you conditionally render widgets based on state?
Check values in `st.session_state` and branch. Example: if `st.session_state.selected_outcome.startswith("Denied")`: render denial fields.
34
How do you disable a widget?
Pass `disabled=True` to input widgets. Example: `st.selectbox('Select Community', options, disabled=not is_corporate_user)`.
35
What do st.error, st.info, st.toast, st.write do?
They render status messages. `st.toast` shows a transient toast; `st.error`/`st.info` show colored alerts; `st.write` prints objects.
36
How do you stop execution or rerun the app?
Use `st.stop()` to abort current run; `st.rerun()` to immediately trigger a rerun (often after changing session state or caches).
37
How do you clear Streamlit's data cache?
Call `st.cache_data.clear()` to invalidate cached `@st.cache_data` functions and force fresh loads.
38
How do keys on widgets work and why are they important?
Each widget needs a stable `key` to bind to `st.session_state`. Using consistent keys avoids losing values on rerun and enables programmatic updates.
39
How do you set default values for widgets?
Pass a default parameter (e.g., `value` or initial date) or pre-seed `st.session_state[key]` before rendering.
40
How do you display a DataFrame in Streamlit?
Use `st.dataframe(df, width='content', hide_index=True)` for interactive display. Prefer pre-formatting values for presentation.
41
Best practice: Rerun after state changes that affect layout
When you change keys used to build the UI (like outcome), calling `st.rerun()` ensures UI matches new state without stale widgets.
42
Gotcha: Form-scoped widgets only update on submit
Widgets inside `with st.form` won't update `st.session_state` immediately; they update when you press the form's submit button.
43
How do you sort a DataFrame by a column?
Use `df.sort_values('col')` or `df.sort_values(by=['A','B'], ascending=[True, False])`.
44
How do you filter rows with boolean indexing?
`df[df['ENT_ID'] == user_entity_id]` filters rows where column equals a value.
45
How do you check if a DataFrame is empty?
Use `df.empty` (boolean). If `True`, there are zero rows.
46
How do you convert a Series to a Python list?
Use `series.tolist()`. Example: `community_df['DSPLY_NAME'].tolist()`.
47
How do you merge two DataFrames?
Use `df.merge(other, on='key', how='left')` to join like SQL LEFT JOIN.
48
How do you drop columns by name or pattern?
Use `df.drop(columns=[...])`. Example builds list with `[c for c in df.columns if c.endswith('_META_VAL_ID')]`.
49
How do you rename columns using a mapping?
Use `df.rename(columns={'OLD':'NEW'})`.
50
How do you cast a column to string?
Use `df['col'] = df['col'].astype(str)`. Useful before displaying mixed-type IDs.
51
How do you treat empty/whitespace as missing and drop blank rows?
`df.replace(r'^\s*$', pd.NA, regex=True).dropna(how='all').reset_index(drop=True)`.
52
How do you format numeric columns for display?
`df['Amount'] = df['Amount'].apply(lambda x: f"${{x:,.2f}}" if pd.notna(x) else '')` to produce currency strings.
53
How do you iterate rows?
Use `for idx, row in df.iterrows(): ...` (note: slower than vectorized ops; fine for small UI lists).
54
How do you build a mapping dict from two columns?
`df.set_index('ID')['NAME'].to_dict()` creates `{ID: NAME}` mapping.
55
How do you select with .loc and .iloc?
Use `.loc[mask, 'col']` to filter by condition then `.iloc[0]` to get first matching scalar.
56
How do you search strings ignoring case and NaN?
`df['col'].str.contains(term, case=False, na=False)` returns a boolean mask.
57
Gotcha: Formatting numbers converts them to strings
After currency formatting, the column is no longer numeric. Perform numeric ops before formatting for display.
58
Best practice: Avoid iterrows for large data
Prefer vectorized operations or `itertuples()` for performance when building large UI lists.
59
Best practice: Use explicit dtypes and handle pd.NA
Pandas 2.3.1 supports nullable dtypes. Use them to distinguish `None`/`NA` from empty strings.
60
How do you build an INSERT statement with dynamic columns and values?
Create Python lists `cols` and `vals`, optionally insert conditionals, then use `",".join(list)` inside an f-string: `f"INSERT ... ({','.join(cols)}) SELECT {','.join(vals)};"`.
61
How do negative indices affect list.insert when building SQL?
Negative indices count from the end. `cols.insert(-4, 'DNL_AMT')` places the field 4 positions from the end to keep audit columns at the tail.
62
How do you escape single quotes for SQL in Python strings?
Double them inside the literal: `value.replace("'", "''")`. The helper `quote(val)` returns `NULL` for `None` else an escaped, quoted string.
63
What are the risks of f-string SQL and how to mitigate?
Direct f-strings risk SQL injection if inputs include quotes or malicious text. Prefer parameterized queries or safe quoting/whitelisting.
64
How to map human-readable values to foreign-key IDs in SQL?
Use subselects in VALUES/SELECT: `(SELECT META_VAL_ID FROM META_VAL WHERE VAL_NAME = '...')`.
65
How to fetch the last inserted row ID safely?
Ordering by timestamp may race. Prefer database-returning clauses (e.g., `RETURNING` in some DBs) or a unique surrogate to fetch the specific row.
66
Best practice: Keep audit columns updated
Set `UPDT_USER_ID` and `UPDT_TS` in UPDATE statements and `CREAT_*` in INSERT to maintain traceability.
67
Gotcha: NULL vs 'NULL' in SQL strings
SQL `NULL` is unquoted. The string `'NULL'` is a literal word. Ensure the helper returns the unquoted `NULL` token when needed.
68
How do you build a list of required keys and check them?
Keep a list `base_required`, loop through, read `st.session_state.get(k)` and collect missing when value in `(None, "")`. Handle numeric fields separately (e.g., `> 0`).
69
How do you map internal keys to user-friendly labels?
Use a dict `field_labels` and transform missing keys to readable labels for error messages.
70
How do you implement conditional required fields?
Branch on outcome. If outcome == `"Redetermination Pending"`, require appeal info; if outcome startswith `"Denied"`, require denial reason and amount `> 0`.
71
How do you enforce permission checks in code?
Compare the selected entity to the user's entity and block with `st.error` if they don't match for community users.
72
Why return early after showing an error?
Prevents the later code (like SQL execution) from running when validation fails.
73
Gotcha: Comparing dates and strings
Ensure that date values from widgets (`datetime.date`) match the types expected by your DB layer. Convert/format consistently before SQL.
74
Best practice: Centralize validation logic
Keep base and conditional validations together so the UI and SQL sections stay simple and safe.
75
How do you extract a numeric ID from a labeled string with regex?
Use `re.search` with a capturing group: ``` match = re.search(r"ID:(\d+)\)", s) rec_id = int(match.group(1)) ```
76
Gotcha: Escaping parentheses in regex patterns
To match a literal `)`, escape it as `\)`. Raw strings help: `r"\)"`.
77
How do you structure a Streamlit page as a function?
Define `def add_billing_page():` and call it at the end of the module so Streamlit runs it when the script is executed.
78
Why use a 'record_added' flag in session state?
Set it after INSERT, read it on the Edit page to clear caches and rerun so lists show the new record immediately.
79
How to implement a manual 'Refresh' button?
`st.button("Refresh")`: pop transient state keys and `st.rerun()` to reload data and UI.
80
Best practice: Keep display names and IDs separate
Store the human-readable names in widget state, map to IDs only at SQL time. This simplifies UI logic and comparisons.
81
Gotcha: Mutating lists while building SQL
When inserting at indices based on tail positions, ensure you understand how negative indices compute after prior inserts.
82
Best practice: Consistent key naming for widgets
Use descriptive, stable keys (e.g., `selected_payor`, `claim_amt`) across pages to reduce errors and ease validation.
83
What type does st.date_input return and how to use it?
It returns a `datetime.date`. You can store it directly in `st.session_state` and format it for SQL with ISO strings if needed.
84
How do you set min/max dates in date_input?
Use `min_value` and `max_value` parameters, e.g., `min_value=date(1900,1,1)`, `max_value=date.today()`.
85
How to label required fields and provide helpful errors?
Mark labels with `*` and aggregate missing fields into one message: `st.error('Missing: ' + ', '.join(labels))`.
86
How to format money amounts for readability?
Use numeric display formatting (e.g., `$1,234.00`) in the table while keeping raw numbers in state for calculations.
87
Gotcha: Mixed responsibilities in UI code
Separate data fetch, validation, and SQL building sections for maintainability. Keep each block compact and testable.