Python User Input and Interaction

User interaction is essential in many programs to select options and display results. An intuitive user interface is important to retrieve the right inputs and present results in an actionable format. A simple example of user input is an input dialog such as:

myName = input('Name: ')
myAge = input('Age: ')

The user inputs a name and age and Python stores those values in variables myName and myAge. It may be necessary to check the validity of the inputs with code such with a try, except structure.

myName = input('Name: ')
   myAge = int(input('Age: '))
   print 'Invalid age, please enter a number'

Widgets are another type of input device but only for IPython. The same Name and Age input is shown below with a more complete tutorial video that shows how to create an interactive plot.

import ipywidgets as wg
from IPython.display import display

myName = wg.Text(value='Name')
myAge = wg.IntSlider(description='Age:')

### new cell
print(myName.value + ' is ' + str(myAge.value) + ' years old')