Introduction to Programming using Python and Jupyter

Python

is a Programming Language.

Jupyter

is an Interactive NoteBook

Adding two numbers

a + b

2 + 3 = 5

-2 + 2 = 0

How do we add two numbers in Python

  • Define a function called add that takes two inputs a and b
  • Compute the expression a + b and store it in result
  • Return the result

In [1]:
def add(a, b):
    result = a + b
    return result

Testing the function


In [2]:
add(2, 5)


Out[2]:
7

In [3]:
add(-20, 30)


Out[3]:
10

Adding an User Interface

So that we can interactively provide inputs

Display the result

Import the function


In [4]:
from ipywidgets import interact

In [5]:
interact(add, a=10, b=20)


36

Manually type the value for inputs


In [6]:
from ipywidgets.widgets import IntText

In [7]:
aText = IntText(min=0, max=10, value=2)
bText = IntText(min=0, max=10, value=2)

interact(add, a=aText, b=bText)


0

Subtracting two numbers


In [8]:
def sub(a, b, verbose=False):
    result = a - b
    
    if verbose:
        return "a - b = %s" % (result)
    else:
        return result

In [9]:
from ipywidgets.widgets import IntSlider

In [10]:
aSlider = IntSlider(min=-100, max=100, value=0)
bSlider = IntSlider(min=-100, max=100, value=0)

interact(sub,
         a=aSlider,
         b=bSlider,
         verbose=True,
        )


'a - b = -47'