Lesson 9: Programming
Homepage | Content | Slides | Video |
Warning
This lesson is under construction. Learn from it at your own risk. If you have any feedback, please fill out our General Feedback Survey.
Homepage | Content | Slides | Video |
Warning
This lesson is under construction. Learn from it at your own risk. If you have any feedback, please fill out our General Feedback Survey.
Programming is a big topic.
function f(x):
# This line is a comment, not run by the computer.
# Comments are only for human eyes.
if x is less than than 5
print "x is less than 5"
else if x is less than than 10
print "x is greater than five and less than 10"
else
print "x is greater than 10"
>>> x = "value"
>>> print(x)
value
>>> x = "different value"
>>> print(x)
different value
Data types dictate how a piece of data should be handled within a program.
Static | Types are known at compile time and defined by the programmer. |
Dynamic | Types may change based on how the program runs. |
Strongly | Types are enforced and cannot change. |
Weakly | Types are fluid and can be 'bent' based on needs. |
Int | 1, 5, 10000 |
Float | 1.5, 3.14159 |
Char | 'a', 'f', 'g' |
String | "foo", "BAR" |
Array | [1, 2, 3], ['a', 'b', 'c'] |
Flow Control allows you to execute code only if certain conditions are met.
Conditionals are used to tell the program when to execute commands.
In pseudocode, they usually look something like
if some conditional statement is true
do something
else if some other conditional
do something else
else
do a final thing
Loops are used to do multiple things, usually an indefinite number of things.
For instance:
for every element, let's call it "foo", in a list "my_list"
if foo is greater than five
print(foo)
else
print(foo + " is too small")
While loops execute indefinitely (while something continues to be true).
For loops iterate over a list (array) of elements or to a specific number.
>>> user_input = get_input("Where would you like to go today? ")
>>> -> Where would you like to go today? Nebraska
>>> print(user_input)
>>> -> nebraska
>>> print(reverse(user_input))
>>> -> aksarben
function read_file(x):
# Also check that it exists! How convenient!
if file_exists(x)
v = read_file_to_string(x)
return v
else
print("file does not exist")
return Null
struct dog {
breed: String
height: Float
color: String
age: Integer
}
spot = struct dog # Create a new variable of type `struct dog`
spot.breed = "corgie" # Assign each member a variable.
spot.height = 1.5
spot.color = "Blond"
spot.age = 1
print(spot.breed, spot.height, spot.color, spot.age)
class chair():
function init(material):
self.material = material
function rock():
print("The ", self.material, " chair rocks slowly.")
>>> my_chair = chair.init("plastic")
>>> my_chair.rock()
>>> -> The plastic chair rocks slowly.
import math_lib
print(math_lib.pi, math_lib.pow(2, 5), math_lib.tan(79.3))
# prints out "3.14 32 .951"
$ sudo <apt or yum> install python
Type | Example |
boolean | True |
integer | 7 |
long | 18,446,744,073,709,551,615 |
float | 12.4 |
string | "Hello World!" |
list | ['first', 'second'] |
dict (map) | {'key1': 'value', 'key2', 'value2'} |
tuple | ('value','paired value') |
object | anObjects.variable == <value> |
None |
# This is a comment
boolean = True # boolean
name = "Lucy" # string
age = 20 # integer
pi = 3.14159 # float
alphabet = ['a', 'b', 'c']
dictionary = {"pi":3.14159, "sqrt 1":1}
winter = ('December', 'January', 'February', 'March')
print(name + " is " + str(age+1) + " this " winter[3])
Open a REPL (Read Evaluate Print Loop):
$ python
>>> print("I'm in a REPL!")
>>> name = # <Your name>
>>> age = # <Your age>
>>> print(name + " is " + str(age))
>>> # We need to convert age from int to string so it can print!
if name == "Lucy":
for month in winter:
print name + " doesn't like " + month
else:
print "My name isn't Lucy!"
def myfunction(arg1, arg2):
return arg1 + arg2
print myfunction(1, 5)
There are a few ways to use other code in your code:
from math import pi
x = pi
from math import *
x = pi
There are hundreds of Python libraries. If you're trying to do something and think "This has probably been solved...", Google it!
Some libraries to know:
$ sudo apt-get install python-virtualenv
$ sudo yum install
# In each project you work on, you'll want to run
$ virtualenv venv
$ source venv/bin/activate
(venv)$ pip install <package>
(venv)$ deactivate
Formalize the last TODO by writing them in Python.
Prove the program works by running the code!