Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 38 ยท Input Widgets

Text and Number Input

Collect typed input in Streamlit with text_input, text_area and number_input. Learn defaults, validation, password fields, int versus float values and when the app reruns.

Many apps start with a box to type in: a search term, a name, a note, an amount. Streamlit offers st.text_input for one line, st.text_area for several lines and st.number_input for numbers. They look simple, but a few rules decide whether your app feels right: what the widget returns before the user types, when the script reruns, and how you validate what comes back.

The Streamlit snippets are real and read-only, and the result on the page is described. Runnable blocks hold the validation logic, which is plain Python.

st.text_input

Python
import streamlit as st

name = st.text_input("Your name", placeholder="e.g. Ada Lovelace")
city = st.text_input("City", value="Oslo", max_chars=30)
secret = st.text_input("Password", type="password")

st.write(f"Hello {name or 'stranger'} from {city}")

The page shows three single-line boxes: the first empty with grey placeholder text, the second pre-filled with "Oslo" and limited to 30 characters, the third showing dots instead of letters. Below them, the text reads "Hello stranger from Oslo" until a name is entered.

Key facts:

  • The return value is always a string. Before the user types, it is "" (or your value=), never None. Test with if name:.
  • The script reruns when the user presses Enter or the box loses focus (clicks elsewhere), not on every keystroke. A hint "Press Enter to apply" appears while editing.
  • type="password" hides the characters on screen only. It does not encrypt anything. Never print or log the value, and do not store it in plain text. For real authentication use a proper login method.
  • label_visibility="collapsed" hides the label visually but keeps it for screen readers. Always give a label.
  • help="..." adds a tooltip. key="..." gives a stable identity. disabled=True blocks typing.
  • autocomplete gives the browser a hint (for example "email" or "off").

st.text_area

Python
notes = st.text_area("Notes", height=150, max_chars=500, placeholder="Write here...")
st.write(f"{len(notes)} characters")

The page shows a multi-line box 150 pixels tall that scrolls if needed, with a character counter in its corner because max_chars is set. The script reruns when the user presses Ctrl+Enter (Cmd+Enter on a Mac) or clicks outside the box; plain Enter inserts a new line. The result is a string with \n between lines.

st.number_input

Python
age = st.number_input("Age", min_value=0, max_value=120, value=30, step=1)
price = st.number_input("Price", min_value=0.0, value=9.99, step=0.01, format="%.2f")
st.write(type(age).__name__, type(price).__name__)

The page shows two number boxes with small minus and plus buttons. The age box starts at 30; each click on plus adds 1 and typing a value above 120 is clamped. The price box shows 9.99, moves in cents and always displays two decimals. The text line reads "int float".

The type of the returned number depends on the arguments: if value, min_value and step are all integers you get an int; if any is a float you get a float. Mixing them (for example min_value=0 with value=1.5) is an error, so write 0.0 for float boxes. Pass value=None for an empty box that returns None until the user types.

Widget Returns Reruns when
text_input str Enter or focus lost
text_area str Ctrl/Cmd+Enter or focus lost
number_input int, float or None Enter, focus lost or the +/- buttons

Never trust the input

Users type anything. Validate before you use the value, and tell the user what is wrong. A typical pattern:

Python
email = st.text_input("Email")
if email and "@" not in email:
    st.error("That does not look like an email address.")
    st.stop()

st.stop() ends the run, so the rest of the page (which depends on a valid email) is not drawn. That pattern comes from the rerun model lesson.

Validation helpers you can run

Keep validation in small, testable functions that return an error message or None. They are plain Python, so test them here with a few examples:

Python Validate typed input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the app: msg = validate_email(email), then if msg: st.error(msg); st.stop().

Process free text

A text area usually feeds an analysis. This logic counts words and finds the most frequent ones, as you might for a "text statistics" tool. It runs here in full:

Python Text statistics for a text_area

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Here apps appears four times, data three times and easy twice, so those are the top three. In an app, text = st.text_area(...) replaces the fixed string, and you would show the numbers with st.metric and the words with st.bar_chart.

Defaults, keys and state

Every widget remembers its value for the session. Two widgets with the same label and arguments need distinct keys, otherwise Streamlit raises a duplicate-widget error:

Python
a = st.text_input("Name", key="billing_name")
b = st.text_input("Name", key="shipping_name")

A key also gives the value a name in st.session_state (for example st.session_state["billing_name"]), which later chapters use to set or read widget values from other places.

Changing a widget's arguments (a new default, a different label) makes Streamlit treat it as a brand new widget and reset its value. That is occasionally confusing when options are computed dynamically; give the widget a fixed key to keep it stable.

Chat input preview

st.chat_input("Ask something...") is a special single-line input pinned to the bottom of the page. It returns the submitted text once and then None again, exactly like a button, and is the basis of chatbot apps in the Machine Learning chapter.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does st.text_input return before the user types anything?

    text_input always returns a string; before typing it is empty unless you set value=.
  2. 2. When does a text_area trigger a rerun?

    Plain Enter adds a new line in a text area; Ctrl/Cmd+Enter or leaving the box applies the text.
  3. 3. number_input has value=1, min_value=0 and step=1. What type does it return?

    When all numeric arguments are integers the widget returns an int.
  4. 4. Does type='password' make the stored value secure?

    It masks the display. You must still protect the value yourself and use real authentication for logins.

Summary

  • text_input and text_area return strings and rerun on Enter/Ctrl+Enter or when focus is lost; number_input returns int or float depending on its arguments.
  • Treat empty strings as "no input yet" and validate everything the user types.
  • Keep validation in small functions, and use st.error plus st.stop() to block invalid input.
  • Give widgets with identical labels distinct keys.

Next: Choice Widgets