# A first glance at Python and Jupyter

### 1. Hello World

In [ ]:
print('Hello World')

### 2. Print the 'help' for a particular function (try also using the IPython shell)

In [ ]:
help(random)

Some useful to get help in Jupyter Notebook:

• Hold Shift + Tab over a function inside a code cell.
• Function name with a question mark after it.

In [ ]:
random.random?

### 3. IPython Magic Commands

The magics we are going to use the most: %%time, %%timeit, and %matplotlib. More info about magics here.

In [ ]:
%lsmagic

### 3. Importing Python modules

To use an external module in Python you can import it into your script by using the import statement.

In [46]:
import math #imports the whole module. It requires to use the prefix "math." before calling each function
from math import * #imports all functions and variable within the current namespace (it does not require to use the prefix)
from math import cos, pi #imports only the specific functions and variables listed

Try using the different import options to describe the following expression:

x = cos(2 *pi)

In [ ]:
x = math.cos(2 * math.pi)
x = cos(2 * pi)
print(x)

## Functions

### 1. Define a function that returns the sum of two random numbers

In [ ]:
import random

In [ ]:
def sumTwoRandomNumbers():
a = random.random()
b = random.random()
c = a+b
print ('a: ', a, ' b: ', b)
print(type(a))
return c

In [ ]:
sumTwoRandomNumbers()

### 2. Define a function that returns the sum of two given numbers

In [ ]:
def sumTwoGivenNumbers(a, b):
c = a+b
return c

In [ ]:
sumTwoGivenNumbers(23, 7)

### 3. Define a function that returns the sum of multiple given numbers

In [ ]:
def sumMultipleNumbers(*args):
c = sum(args)
return c

In [ ]:
sumMultipleNumbers(1,2,3)

### 4. Define a function that returns sum or the average of a variable set of numbers

In [ ]:
def opMultipleNumbers(*args, **kwargs):
if kwargs.get("operation") == "sum":
c = sum(args)
if kwargs.get("operation") == "avg":
c = sum(args)/len(args)
return c

In [ ]:
opMultipleNumbers(1,2,3,4,operation="avg")

## Exercise

### 1. Define a function that returns a list of numbers that sum up to 1

• Generate a list of random numbers
• Sum up all the numbers in the list
• Take each number in the initial list and divide it by the sum of all numbers
• Print the new list
• Sum up all the values in the new list. It should sum up to 1

In [51]:
randomNumbers = [random.random() for i in range(1,10)]
s = sum(randomNumbers)
r = [ i/s for i in randomNumbers ]
print (r)
print(sum(r))

[0.02770880546317565, 0.15676907789403854, 0.002290709060239855, 0.014333832439627468, 0.31363690061092536, 0.17574429881851422, 0.04481370109223432, 0.14866960184950107, 0.11603307277174349]
1.0

In [ ]: