Forms in Colab allow for easy parameterization of code. To add form fields:
- Navigate to:
Insert → Add form field
Changing a form's value updates the code, making your notebook interactive and user-friendly.
text = 'value' # @param {type:"string"}
dropdown = '1st option' # @param ["1st option", "2nd option", "3rd option"]
text_and_dropdown = 'value' # @param ["1st option", "2nd option", "3rd option"] {allow-input: true}
text_with_placeholder = '' # @param {type:"string", placeholder:"enter a value"}
print(text)
print(dropdown)
print(text_and_dropdown)
print(text_with_placeholder)
raw_input = None # @param {type:"raw"}
raw_dropdown = raw_input # @param [1, "raw_input", "False", "'string'"] {type:"raw"}
raw_with_placeholder = None # @param {type:"raw", placeholder:"enter a value"}
print(raw_input)
print(raw_dropdown)
print(raw_with_placeholder)
date_input = '2018-03-22' # @param {type:"date"}
print(date_input)
number_input = 10.0 # @param {type:"number"}
number_slider = 0 # @param {type:"slider", min:-1, max:1, step:0.1}
integer_input = 10 # @param {type:"integer"}
integer_slider = 1 # @param {type:"slider", min:0, max:100, step:1}
print(number_input)
print(number_slider)
print(integer_input)
print(integer_slider)
boolean_checkbox = True # @param {type:"boolean"}
boolean_dropdown = True # @param ["False", "True"] {type:"raw"}
print(boolean_checkbox)
print(boolean_dropdown)
You can include Markdown directly in forms to provide context or instructions:
# @title ## Markdown
# @markdown You can also include Markdown in forms.
file_path = "" # @param {type:"string"}
Toggle the visibility of form fields and code using:
- View → Show/hide code
- Toolbar options above code cells
You can show only the form, only the code, or both.
Cells marked with { run: "auto" }
will auto-run when their form value changes, but only if they were manually executed first.
Colab supports Jupyter Widgets for Python-browser interactivity, enhancing user experience.
import ipywidgets as widgets
from IPython.display import display
button = widgets.Button(description="Click Me!")
output = widgets.Output()
def on_button_clicked(b):
with output:
print("Button clicked.")
button.on_click(on_button_clicked)
display(button, output)
import ipywidgets as widgets
slider = widgets.IntSlider(value=5, max=10)
display(slider)
# Access the slider's value
slider.value
For more, visit the Jupyter Widgets Documentation.
- Run all cells:
Runtime → Run all
- Run selected cell: Click the cell and press Run
- Restart and run all cells:
Runtime → Restart and run all