If you ever see a "could not find a kernel for this notebook" error message, it will offer you a pull down menu for you to pick a fitting kernel.
Remember, kernels
are the notebook's way to find the correct interpretor for the code you write into notebook cells. And these days this can be R
, Julia
, Python
and several other things (Find the available kernels list here).
$T_C = \frac{5}{9} \left(T_F - 32 \right)$
In [1]:
tempF = 212.0
tempC = (5 / 9) * (tempF - 32.0)
tempC
Out[1]:
In [2]:
x = 45
type(x) # Gives (returns) the type of variable
Out[2]:
In [3]:
x = float(x)
print(type(x))
x
Out[3]:
In [4]:
x = 26.9
int(x)
Out[4]:
In [5]:
from math import *
import math
print(sqrt(2))
math.sqrt(2)
Out[5]:
It's using the exact same library twice, you just told Python 2 different ways to get to it.
And there's even a way to prove it: With the id()
function:
In [6]:
id(sqrt)
Out[6]:
In [7]:
id(math.sqrt)
Out[7]:
As you can see it's the same memory address (but this number is not necessarily the same on your computer), meaning the Python interpreter uses the exact same object twice, you just gave it 2 different names.
Another syntax is available to import modules:
In [8]:
# Import math module and give it a new name
import math as m # Note the use of "as", a reserved word
m.sqrt(2)
Out[8]:
or specific functions within a module:
In [9]:
# Import sqrt from math and give it a new name
from math import sqrt as sq
from math import pi as PIE
sq(2)
Out[9]:
The point of loops is to compactly code repetitive tasks. For example, computing the gravitational force for multiple planetary masses.
Loops are an essential programming tool (this is why we program!).
Python supports two types of loops:
In [10]:
x = 0 # Initialize the variable x to 0
while(x != 3): # While (as long as) x is not equal to 3
print("The value of x is", x) # Print this to the screen
x += 1 # Increment x by 1 (add 1 to x)
# REPEAT!!!
In [11]:
print(x)
# What is the value of x?
In [12]:
x = 0 # Initialize the variable x to 0
print("The value of x is", x) # Print this to the screen
x += 1 # Increment x by 1 (add 1 to x)
print("The value of x is", x) # Print this to the screen
x += 1 # Increment x by 1 (add 1 to x)
print("The value of x is", x) # Print this to the screen
x += 1 # Increment x by 1 (add 1 to x)
Recall the Gravitational Force Equation
In [13]:
print('# Table of Gravitational Forces for Multiple Planet Masses\n')
# Initialize variables - use meters and kilograms for units
G = 6.67e-11 # Gravitational constant
mass_earth = 5.97e24 # Earth mass
mass_person = 70 # Person mass
radius_earth = 6.37e6 # Earth radius
# Begin calculation
mass1 = mass_earth
# Print a header
print('# mass1/mass_earth Force')
# The loop ends when conditional mass1 <= (10.0 * massEarth) is no longer true
while(mass1 <= (10.0 * mass_earth)): # Note the colon!
force = G * mass1 * mass_person / radius_earth**2 # All lines in the loop must be indented by
# the same amount (iPython does it automatically)
# print(str(mass1 / mass_earth) + " " + str(force))
print("{mass_ratio}\t{force:7.2f}".format(mass_ratio=mass1 / mass_earth,
force=force))
mass1 = mass1 + mass_earth # Increment by Earth's mass
# No indent! This line is executed after the loop is done
print('# Done')
The increment could have been done in shorthand
In [14]:
# Note that I have to reset mass1 here!!
mass1 = mass_earth
print('# mass1/mass_earth Force')
while(mass1 <= (10.0 * mass_earth)):
force = G * mass1 * mass_person / radius_earth**2
print("{:18.1f} {:7.2f}".format(mass1 / mass_earth, force))
# mass1 = mass1 + mass_earth
mass1 += mass_earth # Shorthand version of the line above.
'# Done'
Out[14]:
In [15]:
# How to prevent an infinite loop
maxCount = 10 # A number that is more than your loop should ever do
count = 0 # The current number your loop is on
# Adding "and < maxCount" to the end of your conditional prevents infinite loops
while(True and count < maxCount):
print("Loop count: " + str(count))
count += 1 # Increment your current loop count
Boolean expressions are conditional statements. There are only two possible values: True or False
I've capitalized True and False because these are reserved words in Python.
In [16]:
5 <= 10
Out[16]:
In [17]:
5 >= 10
Out[17]:
In [18]:
not 5 >= 10
Out[18]:
See how readable Python is?
Boolean expressions can be combined with "and", "or" and "not" to form compound conditional expressions.
In [ ]:
5 <= 10 and 5 >= 10
In [ ]:
5 <= 10 or 5 >= 10
In [19]:
import random
minNumber = 1
maxNumber = 10
# Get a random number between 1 and 10
randomNumber = random.randint(minNumber, maxNumber)
userGuess = -1
while(userGuess != randomNumber):
userPrompt = "Guess a number between " + str(minNumber) + " and " + str(maxNumber) + ": "
userGuess = input(userPrompt) # Prompt the user
userGuess = int(userGuess)
print("You have guessed the correct number! " + str(userGuess))
In [22]:
massRatio = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
massRatio
Out[22]:
In [23]:
massRatio[3]
Out[23]:
In [24]:
type(massRatio[3])
Out[24]:
Lesson learned: Python is zero-index based
In [ ]:
massRatio.append(11.0)
massRatio
In [ ]:
# This inserts 4.5 into index 4 of the list:
massRatio.insert(4, 4.5)
massRatio
In [ ]:
del massRatio[4]
In [ ]:
massRatio
In [ ]:
# We can find out its length with len(object)
len(massRatio)
# Python uses [] to access elements and () to perform a function on an object.
In [25]:
massRatio = massRatio + [12.0, 13.0, 14.0]
massRatio
Out[25]:
In [ ]:
massRatio.extend([15.0, 16.0, 17.0])
print("Extend", massRatio)
massRatio.append([18.0, 19.0, 20.0])
print("Append", massRatio)
print(massRatio[17][1])
In [28]:
massRatio.index(12.0)
Out[28]:
In [29]:
# And, this fails
massRatio.index(20.0)
In [ ]:
# We can check if there is an element in a list. The result of the check
# is boolean: True or False.
14.0 in massRatio
In [ ]:
99.0 in massRatio
In [ ]:
massRatio
In [ ]:
# Negative indices start counting from the right (the end) of a list:
massRatio[-4]
In [ ]:
# Initializations first
massRatio = [] # Creates an empty list
massRatioValue = 1.0 # For the conditional
massRatioMax = 5.0 # Also for the conditional
userInput = "BIG NOPE"
# And the while loop
while(userInput != "N" and massRatioValue <= massRatioMax): # Remember the colon!
# Remember to indent!
massRatio.append(massRatioValue)
massRatioValue += 1.0
userInput = input("Add another mass ratio value? ")
userInput = userInput.upper()
print("Finished creating the list massRatio!")
In [ ]:
massRatio
In [ ]: