Install Python environment, know how to enter expressions in Python and how to save, run, and open files! To work with plots, you will need these Python library packages: matplotlib and numpy. If you’re using Anaconda Python, your system should already have numpy and matplotlib installed. Addition (+), subtraction (-), multiplication (*), division (/), modulo (%) and power (**) operators are built into the Python language.
Below are two examples of square root calculation:
In [1]: 16**0.5
Out [1]: 4.0
In [2]: import math
In [3]: math.sqrt(16)
Out[3]: 4.0
The math module allows you to do a number of useful operations:
In [1]: math.log(16, 2)
Out [1]: 4.0
In [2]: math.cos( 0 )
Out [2]: 1.0
- try out code in your Python development environment (Anaconda, Canopy, IDLE, or whatever)
- read the Python documentation or other Python tutorials
- use a paper and pencil to sketch out solutions
- if you have the textbook, read the relevant sections
- post to the forums (or any of our social media platforms)
Programming.
We also teach computational methods.
Documentation
- Official Python 3 Documentation – “official”/technical explanation of what a particular function/operator does, examples of correct syntax, what the various libraries are, etc.
- Built in functions: https://docs.python.org/3/library/functions.html#built-in-funcs
Textbooks/Tutorials
- Dive Into Python – another survey of Python syntax, datatypes, etc.
- Think Python by Allen Downey – a good general overview of the Python language. Includes exercises.
- The Official Python Tutorial – self-explanatory
- Learn Python the Hard Way – (note: for Python 2) another free online text
- Reserved Keywords in Python – don’t use these as variable names
- PEP 8 – Style Guide for Python Code – learn what is good and bad style in Python
- CheckIO – learn Python by exploring a game world
- Invent with Python – develop your Python skills by making games or hacking ciphers
- Codecademy – (note: for Python 2) learn Python by building web apps and manipulating data; interactive tutorial sequence
- Python Tutor – interactive tutorial sequence of exercises
- Blog with tutorials – created by one of our community TAs
Debugging
- Python Tutor – an excellent way to actually visualize how the interpreter actually reads and executes your code
- DiffChecker – compares two sets of text and shows you which lines are different
- Debugging in Python – steps you can take to try to debug your program
Software
- Python Tools for Visual Studio – Visual Studio plug-in enabling Python programming
Other Q&A
- Stack Overflow – a large Q&A forum for programming concepts (not just Python). Try searching here before you post on the edX forum, and you may find that someone has already answered your question.
More practice problems
- Python Challenge – a series of puzzles you can try to test your Python abilities
- Project Euler – additional programming challenges you can try once your Python knowledge becomes stronger; problems are sorted by increasing difficulty
- Coding Bat – problems you can solve within an online interpreter
- Codewars – improve your skills by training on real code challenges
Variables
Creating web apps, games, and search engines all involve storing and working with different types of data. They do so usingvariables. A variable stores a piece of data, and gives it a specific name.
Infinite loops in your programs
If you accidentally created an infinite loop and your program sits for a few seconds without printing anything out or terminating, restart the console.
- You can do this in Spyder by hitting Ctrl + c (Ctrl key and the c button on your keyboard) in the console. Or go to the button beside the red square at the top of your console and select Restart Kernel. If this doesn’t work, restart Anaconda/Spyder.
- You can do this in IDLE by clicking Ctrl + F6 or by going to the menu Shell -> Restart Shell
MITx
6.00.1x
Learn computational modes of thinking and master the art of computational problem solving. Make computers do what you want them to do. We will represent knowledge with data structures, iteration and recursion as computational metaphors, abstraction of procedures and data types, organize and modularize systems using object classes and methods, different classes of algorithms, searching and sorting, complexity of algorithms. What does a computer do:
- Fundamentally:
- peforms calculations a billion customers per second! two operations in same time light travels 1 foot
- remembers results 100s of gigabytes of storage! typical machine could hold 1.5M books of standard size
- What kinds of calculations?
- built-in to the language
- ones that you define as the programmer
Simple calculations enough?
- Searching the World Wide Web
- 45B pages; 1000 words/page; 10 operations/word to find
- Need 5.2 days to find something using simple operations
- Playing chess
- Average of 35 moves/setting; look ahead 6 moves; 1.8B boards to check; 100 operations/choice
- 30 minutes to decide each move
- Good algorithm design also needed to accomplish a task!
Enough storage?
- What if we could just pre-compute information and then look up the answer
- Playing chess as an example
- Experts suggest 10^123 different possible games
- Only 10^80 atoms in the observable universe
- Playing chess as an example
Are there limits?
- Despite its speed and size, a computer does have limitations
- Some problems still too complex
- Accurate weather prediction at a local scale
- Cracking encryption schemes
- Some problems are fundamentally impossible to compute
- Predicting whether a piece of code will always halt with an answer for any input
- Some problems still too complex
Turing halt problem
Types of knowledge
- Computers know what you tell them
- Declarative knowledge is statements of fact.
- there is a candy taped to the underside of one chair
- Imperative knowledge is a recipe or “how-to” knowledge
- face the students at the front of the room
- count up 3 rows
- start from the middle section’s left side
- count to the right 1 chair
- reach under the chair and find it
A numerical example:
- Square root of a number x is y such that y*y = x
- Recipe for deducting square root of number x
- Start with guess, g
- If g*g is close enough to x, stop and say g is the answer
- Otherwise make a new guess by averaging g and x/g
- Using the new guess, repeat process until close enough
What is a recipe
- Sequence of simple steps
- Flow of control process that specifies when each step is executed
- A means of determining when to stop
- Steps 1+2+3= algorithm
An algorithm is a conceptual idea, a program is a concrete instantiation of an algorithm. A computational mode of thinking means that everything can be viewed as a math problem involving numbers and formulas. Two things every computer can de are performed calculations and remember the results. Declarative knowledge refers to statements of fact and imperative knowledge refers to “how to” methods. A recipe for deducing the square root involves guessing a starting value for y. Without another recipe to be told how to pick a starting number, the computer cannot generate one on its own.
Computers are machines.
- How to capture a recipe in a mechanical process
- Fixed program computer
- Calculator
- Alan Turing’s Bombe
- Stored program computer
- machine stores and executes instructions
Basic Machine Architecture
Memory: data
Control unit: program counter
Arithmetic logic unit: do primitive ops
Input and Output
Stored program computer:
- Sequence of instructions stored inside computer
- Built from predefined set of primitive instructions
- Arithmetic and logic
- Simple tests
- Moving data
- Built from predefined set of primitive instructions
- Special program (interpreter) executes each instruction in order
- Use tests to change flow of control through sequence
- Stop when done
Basic Primitives
- Turning showed you can compute anything using 6 primitives: move left, move right, scan, read, write, and do nothing.
- Modern programming languages have more convenient set of primitives
- Anything computable in one language is computable in any other programming languag – Turing complete
The computer walks through the sequence executing some computation means the computer executes the instructions mostly in a linear sequence, except sometimes it jumps to a different place in the sequence. A program counter points the computer to the next instruction to execute in the program.
Creating Recipes
- A programming language provides a set of primitive operations
- Expressions are complex but legal combinations of primitives in a programming language
- Expressions and computations have values and meanings in programming language
Aspects of languages
- Primitive constructs
- English: words
- programming language: numbers, strings, simple operators
- syntax
- English: “cat dog boy” -> not syntactically valid
- “cat hugs boy” -> syntactically valid
- Programming language: “hi” 5 -> not syntactically valid
- 3.2*5 -> syntacically valid
- static semantics is which syntactically valid strings have meaning
- English: “I are hungry” -> syntactically valid but semantic error
- programmmin language: 3.2*5 -> syntactically valid
- 3 + “hi” -> stat semantic error
- Semantics is the meaning associated with a syntactically string of symbols with no static semantic errors
- English: can have many meanings –
- “Flying planes can be dangerous”
- “This reading lamp hasn’t uttered a word since I bought it?”
- programming languages: have only one meaning but may not be what programmer intended
- English: can have many meanings –
- English: “cat dog boy” -> not syntactically valid
Wher things go wrong
- Syntactic errors
- Common and easily caught
- Static semantic errors
- Some languages check for these before running program
- Can cause unpredictable behavior
- No semantic errors but different meaning than what programmer intended
- Program crahes, stops running
- Program runs forever
- Program gives an answer but different than expected
Our Goal
- Learn the syntax and semantics of a programming language
- Learn how to use those elements to translate “recipes” for solving a problem into a form that the computer can use to do the work for us
- Learn computational modes of thought to enable us to leverage a suite of methods to solve complex problems
- Syntax – Determines whether a string is legal
- Static Semantics – Determines whether a string has meaning
- Assigns a meaning to a legal sentence
Python Programs
- A program is a sequence of definitions and commands
- Definitions evaluated
- Commands executed by Python interpreter in a shell
- Commands (statements) instruct interpreter to do something
- Can be typed directly in a shell or stored in a file that is read into the shell and evaluated
Objects
- Programs manipulate data objects
- Objects have atype that defines the kinds of things programs can do to them
- Object are
- Scalar (cannot be subdivided)
- Non-scalar (Have internal structure that can be accessed
Scalar Objects
- int – represent integers, ex. 5
- float – represent real numbers, ex. 3.27
- bool – represent Boolean values True and False
- Nonetype – special and has one value, None
- can use type () to see the type of an object
In [1]: type (5)
Out [1]: int
In [2]: type (3.0)
Out [2]: float
Type Conversions (Cast)
- Can convert object of one type to another
- float (3) converts integer 3 to float 3.0
- int (3.9) truncates float 3.0 to integer 3
Printint to Console
- To show output from code to a user, use print command
In [11]: 3+2
Out [11]: 5
In [12]: print (3+2)
5
Expressions
- Combine objects and operators to form expressions
- an expression has a value, which has a type
- syntax for a simple expression <object> <operator> <object>
Operators ON ints and floats
- i + j -> the sum (if both are ints, result is int. if either or both are floats, result is float.)
- i – j -> the difference (if both are ints, result is int. if either or both are floats, result is float.)
- i * j -> the product -> (if both are ints, result is int. if either or both are floats, result is float.)
- i / j -> division (result is float.)
- i//j -> int division -> result is int, quotient without remainder
- i%j -> the remainder when i is divided by j
- i**j -> i ot the power of j
Simple Operations
- Parentheses used to tell Python to do these operations first
- 3*5+1 evalutates to 16
- 3*(5+1) evaluates to 18
- Operator precedence without parentheses
- **
- *
- /
- + and – executed left to right, as appear in expression
Answers
- 3.14 – float
- -34 int
- True bool
- None nonetype
- 3.0 float
Binding Variables and Values
- Equal isng is an assignment of a value to a variable name
- pi – 3.14159
- pi_approx = 22/7
- Value stored in computer memory
- An assignment binds name to value
- Retrieve value associated with name or variable by invoking the name, by typing pi
Abstracting Expressions
- Why give names to values of expressions?
- Reuse names instead of values
- Easier to change code later
- pi = 3.14159
- radius = 2.2
- area = pi * (radius **2)
Programming vs math
- In programming, you do not “solve for x”
- pi = 3.14159
- radius = 2.2
- # area of circle
- area = pi * (radius **2)
- redius = radius + 1
Changing Bindings
- Can re-bind names using new assignment statements
- previous value may still stored in memory but lost the handle for it
- value for area does not change until you tell the computer to do the calculation gain
- pi = 3.14
- readius = 2.2
- area = pi * (radius **2)
- radius = radius + 1
Comparison operators on int and float
- i and j are any variable names
- i > j
- i >=j
- i<j
- i<j
- i==j -> equality test, True if i equals j
- i!=j -> inequality test, True if i not equal to j
Logic operators on bools
- a and b are any variable names
- not a -> True if a is False
- False if a is True
- a and b -> Ture if bot are True
- a or b -> True if either or both are True
Branching programs
- The simplest branching statement is a condiditonal
- A test (expression that evalutes to True or False)
- A block of code to executte if the test is True
- An optional block of code to execute if the test is False
A simple example
x = int (input )’Enter an integer: ‘))
if x%2 ==0:
print (”)
print (‘Even’)
else:
print (”)
print (‘Odd’)
print (‘Done with conditional’)
Some Observations
- The expression x%2 == 0 evaluates to True when the remainder of x divided by 2 is 0
- Note that == is used for comparison, since = is reserved for assignment
- The identation is important – each indented set of expressions denotes a block of instructions
- For example, if the last statement were indented, it would be executed as part of the else block of code
- Note how this identation provides a visual structure that reflects the semantic structure of the program
Nested Conditionals
if x%2 == 0:
if x%3 ==0:
else:
print (‘Divisible by 2 and not by 3’)
elif x%3 == 0:
print (‘Divisible by 3 and not by 2’)
Compound Booleans
if x < y and x < z:
print (‘x is least’)
elif y < z:
print (‘y is least’)
else:
print (/z is least’)
Control flow – branching
if <condition>
<expression>
- <condition> has a vaue True or False
- evaluate expressions in that block if <condition> is True
Indentation
- matters in Python
- how you denote blocks of code
- x = float (input (”Enter a number for x: “))
- y = float (input (”Enter a number for y: “))
- if x == y:
- print (”x and y are equal”)
- if y ! = 0:
- print (“therefore, x / y is “, x/y)
- elif x < y:
- print (“x is smaller”)
- else:
- print (“y is smaller”)
- print (“thanks!”)
=vs==
x = float (input (“Enter a number for x: “))
y = float (input (“Enter a number for y: “))
if x == y:
print (“x and y are equal”)
if y ! = 0:
print )”therefore, x /y is”, x/y)
elif x < y:
print (“x is amller”)
else:
print (“y is smaller”)
print (“thanks!”)
What have we added?
- Branhing programs allow us to make choices and do different things
- But still the case that at most, each statement gets executed once
- So maximum time to run the program depends only on the length of the program
- These programs run in constant time
Strings, Branching, Iteration
Variables
- name
- Descriptive
- meaningful
- helps you re-read code
- cannot be keywords
- value
- information stored
- can be updated
Variable binding with =
- Compute the right hand side -> VALUE
- store it (aka bind it) in the left hand side -> VARIABLE
- left hand side will be replaced with new value
- = is called assignment
- x = 2
- x = x*x
- y = x+1
Binding Example
- swap variables
- – is this ok?
- x = 1
- y = 2
- y = x
- x = y
- swap variables
- x = 1
- y = 2
- temp = y
- y = x
- x = temp
Types
- Variables and expressions
- int
- float
- bool
- string — NEW
- …..and others we will see later
STRINGS
- letters, special charactrs, spaces, digits
- enclose in quotation marks or single quotes
- hi = “hello there”
- greetings = ‘hello’
- concatenate strings
- name = “eric”
- greet = hi + name
- greeting = hi +” ” + name
OPERATIONS ON STRINGS
- ‘AB’ + ‘CD’ -> Concatenation
- 3* ‘eric’ -> successive concatenation
- len (‘eric’) -> the length
- ‘eric’ [1] -> indexing
- ‘eric’ [1:3] -> slicing
INPUT/OUTPUT: print
- used to output stuff to console
- keyword is print
- x = 1
- print (x)
- x_str – str (x)
- print (“my fav num is”), x, “.”, “x =”, x)
- print (“my fav num is ” + x_str + “. ” + “x = ” + x_str)
INPUT/OUTPUT: input (“”)
- prints whatever is within the quotes
- user types in something and hits enter
- returns entered sequence
- can bind that value to a variable so can reference
- text = input (“Type anything…”)
- print (5*text)
- input returns a string so must cast if working with numbers
- num = int (input (“Type a number…”))
- print (5*num)
IDE’s
- painful to just type things into a shell
- better to have a text editor – integrated development environment (IDE)
- Idle or Anaconda are examples
- comes with
- Text editor – use to enter, edit and save your programs
- Shell – place in which to interact with and run your programs; standard methods to evaluate your programs from the editor or from stored files
- Integrated debugger (we’ll use later)
Branching programs
- The simplest branching statement is a conditional
- A test (expresion that evaluates to True or False)
- A block of code to execute if the test is True
- An optional block of code to execute if the test is False
Comparison operators on int and float
- i and j are any variable names
- i>j
- i>=j
- i<j
- i<=j
- i==j -> equality test, True if i equals j
- i!=j -> inequality test, True if i not equal to j
Logic operators ON bools
- a and ba are any variable names
- not a -> True if a is False
- False if a is True
- a and b -> True if both are True
- a or b -> True if either or both are True
Using Control in Loops
- Simple branching programs just make choices, but path through code is still linear
- Sometimes want to reuse parts of the code indeterminate number of times
CONTROL FLOW:
while LOOPS
- while <condition> evaluates to a Boolean
- if <condition> is True, do all the steps inside the while code block
- check <condition> is True, do all steps inside the while code block
- check <condition> again
- repeat until <condition> is False
n = input (“You are in the Lost Forest. Go left or right? ”
while n == “right”:
n = input (“You are in the Lost Forest. Go left or right? “)
print (“You got out of the Lost Forest!”)
Control Flow:
while and for LOOPS
# more complicated with while loop
n = 0
while n < 5:
print (n)
n = n + 1
# shortcut with for loop
for n in range (5) :
print (n)
Control Flow: for Loops
for <variable> in range (<some_num>) :
<expression>
- each time through the loop, <variable> takes a value
- first time, <variable> starts at the smallest value
- next time, <variable> gets the prev value + 1
- etc.
range (start, stop, step)
- default values are start = 0 and step = 1 and is optional
- loop until value is stop -1
mysum = 0
for i in range (7, 10):
mysum += i
print (mysum)
mysum = 0
for i in range (5, 11, 2) :
mysum += i
print (mysum)
break statement
- immediately exits whatever loop it is in
- skips remaining expressions in code block
- exits ony innermost loop
while <condition_1>:
while <condition_2>:
<expression_a>
break
<expression_b>
<expression_c>
break STATEMENT
mysum = 0
for i in range (5, 11, 2):
mysum += i
if mysum == 5:
break
print (mysum)
- what happens in this program?
For loops
- Know number of iterations
- Can end early via break
- uses a counter
- can rewrite a for loop using a while loop
While loops
- unbounded number of iterations
- can end early via break
- can use a counter but must initialize before loop and increment it inside loop
- may not be able to rewrite a while loop using a for loop
text = input (“type something”)
type something “foo”
print (5*text) “foo” “foo” “foo” “foo”
Assume that two variables, varA
and varB
, are assigned values, either numbers or strings.
Write a piece of Python code that evaluates varA
and varB
, and then prints out one of the following messages:
"string involved"
if eithervarA
orvarB
are strings"bigger"
ifvarA
is larger thanvarB
"equal"
ifvarA
is equal tovarB
"smaller"
ifvarA
is smaller thanvarB
if type(varA) == str or type(varB) == str:
print(‘string involved’)
elif varA > varB:
print(‘bigger’)
elif varA = varB:
print(‘equal’)
else:
# If none of the above conditions are true,
# it must be the case that varA < varB
print(‘smaller’)
Operator Example
= c = a + b assigns value of a + b into c
+= Add c += a is equivalent to c = c + a
AND
-= Subtract c-=a is equivalent to c = c – a
AND
*= Multipy c*= a is equivalent to c = c * a
AND
/= Divide c/=a is equivalent to c=c / ac
AND /= a is equivalent to c = c %
%=Modulus c % = a is equivalent to c = c % a
AND
**=Exponent c **= a is equivalent to c = c**a
AND
//=Floor c // = a is equivalent to c = c // a
Division