Exercise: Multiple Inputs and Outputs to Callbacks

Practice with some lab exercises.

We'll cover the following

Exercise 1

Create a Dash app that allows the user to enter a number x as input. Now create two outputs, each of them as separate markdown components.

  • The first markdown component should read x² = [squared_num]
  • The second markdown component should read x³ = [cubed_num]

Here [squared_num] and [cubed_num] represent the computed values from the callback function calculation.

Solution

  • Two lambda functions are defined on line 1 and 2, respectively, for calculating the square and cube of a number, respectively.

  • The app layout is set using the dbc.Container method on line 8 which includes:

    • An H1 header element on line 9, displaying Exercise 1.

    • An Input element on line 11 from Dash Core Components, allowing users to input a number.

    • Two Markdown elements on line 12 and 13, respectively, from Dash Core Components with IDs of output1 and output2 to display the calculated square and cube of the input number.

  • A callback function on line 17 is defined to update the output1 and output2 markdown elements content when the user inputs a number.

  • The callback function takes the input number and calculates its square and cube values using the defined lambda functions.

  • The calculated square and cube values are returned as formatted LaTeX strings, which are then displayed in the output1 and output2 elements using MathJax rendering.

  • A new app is created on line 32, and a radio button input is added to allow users to select a sport.

  • A paragraph element § with an ID of output_text is added to display the chosen sport later.

  • A callback function is defined to update the output_text paragraph element’s content when the user selects a different sport from the radio buttons.

  • The callback function takes the selected sport and returns a formatted string displaying the chosen sport in lowercase.

Get hands-on with 1400+ tech skills courses.