SlideShare a Scribd company logo
Welcome to
6.00.1x
16.00.1X LECTURE
OVERVIEW OF COURSE
 learn computational modes of
thinking
 master the art of computational
problem solving
 make computers do what you want
them to do
6.00.1X LECTURE 2
https://ohthehumanityblog.files.wordpress.com/2014/09/computerthink.gif
TOPICS
 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
6.00.1X LECTURE 3
WHAT DOES A COMPUTER DO
 Fundamentally:
◦ performs calculations
a billion calculations 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
6.00.1X LECTURE 4
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!
6.00.1X LECTURE 5
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
6.00.1X LECTURE 6
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
6.00.1X LECTURE 7
6.00.1X LECTURE 8
TYPES OF KNOWLEDGE
 computers know what you tell them
 declarative knowledge is statements of fact.
◦ there is candy taped to the underside of one chair
 imperative knowledge is a recipe or “how-to”
knowledge
1) face the students at the front of the room
2) count up 3 rows
3) start from the middle section’s left side
4) count to the right 1 chair
5) reach under chair and find it
6.00.1X LECTURE 9
A NUMERICAL EXAMPLE
 square root of a number x is y such that y*y = x
 recipe for deducing square root of number x (e.g. 16)
1) Start with a guess, g
2) If g*g is close enough to x, stop and say g is the
answer
3) Otherwise make a new guess by averaging g and x/g
4) Using the new guess, repeat process until close enough
6.00.1X LECTURE 10
g g*g x/g (g+x/g)/2
3 9 5.333 4.1667
4.1667 17.36 3.837 4.0035
4.0035 16.0277 3.997 4.000002
WHAT IS A RECIPE
1) sequence of simple steps
2) flow of control process
that specifies when each
step is executed
3) a means of determining
when to stop
Steps 1+2+3 = an algorithm!
6.00.1X LECTURE 11
6.00.1X LECTURE 12
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
6.00.1X LECTURE 13
http://www.upgradenrepair.com/computerparts/computerparts.htm
CC-BY SA 2.0 dIaper
BASIC MACHINE ARCHITECTURE
6.00.1X LECTURE 14
MEMORY
CONTROL
UNIT
ARITHMETIC
LOGIC UNIT
INPUT OUTPUT
program counter do primitive ops
STORED PROGRAM COMPUTER
 sequence of instructions stored inside computer
◦ built from predefined set of primitive instructions
1) arithmetic and logic
2) simple tests
3) moving data
 special program (interpreter) executes each
instruction in order
◦ use tests to change flow of control through sequence
◦ stop when done
6.00.1X LECTURE 15
BASIC PRIMITIVES
 Turing showed you can compute anything
using 6 primitives
 modern programming languages have
more convenient set of primitives
 can abstract methods to create new
primitives
 anything computable in one language is
computable in any other programming
language
6.00.1X LECTURE 16
By GabrielF (Own work) [CC BY-
SA 3.0
(http://creativecommons.org/lic
enses/by-sa/3.0)], via
Wikimedia Commons
6.00.1X LECTURE 17
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 a programming language
6.00.1X LECTURE 18
ASPECTS OF LANGUAGES
 primitive constructs
◦ English: words
◦ programming language: numbers, strings, simple
operators
6.00.1X LECTURE 19
ASPECTS OF LANGUAGE
 syntax
◦ English: "cat dog boy"  not syntactically valid
"cat hugs boy"  syntactically valid
◦ programming language: "hi"5  not syntactically valid
3.2*5  syntactically valid
6.00.1X LECTURE 20
ASPECTS OF LANGUAGES
 static semantics is which syntactically valid strings have
meaning
◦ English: "I are hungry"  syntactically valid
but static semantic error
◦ programming language: 3.2*5  syntactically valid
3+"hi"  static semantic error
6.00.1X LECTURE 21
ASPECTS OF LANGUAGES
 semantics is the meaning associated with a
syntactically correct 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
6.00.1X LECTURE 22
WHERE 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 crashes, stops running
◦ program runs forever
◦ program gives an answer but different than expected
6.00.1X LECTURE 23
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
6.00.1X LECTURE 24
6.00.1X LECTURE 25
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
6.00.1X LECTURE 26
OBJECTS
 programs manipulate data objects
 objects have a type that defines the kinds of things
programs can do to them
 objects are
◦ scalar (cannot be subdivided)
◦ non-scalar (have internal structure that can be accessed)
6.00.1X LECTURE 27
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
6.00.1X LECTURE 28
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.9 to integer 3
6.00.1X LECTURE 29
PRINTING 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
6.00.1X LECTURE 30
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>
6.00.1X LECTURE 31
OPERATORS ON ints and floats
 i+j  the sum
 i-j  the difference
 i*j  the product
 i/j  division
 i//j  int division
 i%j  the remainder when i is divided by j
 i**j  i to the power of j
6.00.1X LECTURE 32
- if both are ints, result is int
- if either or both are floats, result is float
- result is int, quotient without remainder
- result is float
SIMPLE OPERATIONS
 parentheses used to tell Python to do these
operations first
◦ 3*5+1 evaluates to 16
◦ 3*(5+1) evaluates to 18
 operator precedence without parentheses
◦ **
◦ *
◦ /
◦ + and – executed left to right, as appear in expression
6.00.1X LECTURE 33
6.00.1X LECTURE 34
BINDING VARIABLES AND
VALUES
 equal sign 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
6.00.1X LECTURE 35
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)
6.00.1X LECTURE 36
PROGRAMMING vs MATH
 in programming, you do not “solve for x”
pi = 3.14159
radius = 2.2
# area of circle
area = pi*(radius**2)
radius = radius+1
6.00.1X LECTURE 37
CHANGING BINDINGS
 can re-bind variable 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 again
6.00.1X LECTURE 38
pi
radius
area
3.14
2.2
15.1976
3.2
pi = 3.14
radius = 2.2
area = pi*(radius**2)
radius = radius+1
6.00.1X LECTURE 39
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
6.00.1X LECTURE 40
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  True if both are True
a or b  True if either or both are True
6.00.1X LECTURE 41
If right clear,
go right
If right blocked,
go forward
If right and
front blocked,
go left
If right , front,
left blocked,
go back
6.00.1X LECTURE 42
BRANCHING PROGRAMS
The simplest branching statement
is a conditional
◦ A test (expression 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
6.00.1X LECTURE 43
A SIMPLE EXAMPLE
x = int(input('Enter an integer: '))
if x%2 == 0:
print(‘’)
print('Even')
else:
print(‘’)
print('Odd')
print(’Done with conditional')
6.00.1X LECTURE 44
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 indentation 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 indentation provides a visual structure
that reflects the semantic structure of the program
6.00.1X LECTURE 45
NESTED CONDITIONALS
if x%2 == 0:
if x%3 == 0:
print('Divisible by 2 and 3’)
else:
print('Divisible by 2 and not by 3’)
elif x%3 == 0:
print('Divisible by 3 and not by 2’)
6.00.1X LECTURE 46
COMPOUND BOOLEANS
if x < y and x < z:
print('x is least’)
elif y < z:
print('y is least’)
else:
print('z is least’)
6.00.1X LECTURE 47
CONTROL FLOW - BRANCHING
if <condition>:
<expression>
<expression>
...
if <condition>:
<expression>
<expression>
...
else:
<expression>
<expression>
...
if <condition>:
<expression>
<expression>
...
elif <condition>:
<expression>
<expression>
...
else:
<expression>
<expression>
...
 <condition> has a value True or False
 evaluate expressions in that block if <condition> is True
6.00.1X LECTURE 48
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!”)
6.00.1X LECTURE 49
= 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 smaller”)
else:
print("y is smaller”)
print("thanks!”)
6.00.1X LECTURE 50
WHAT HAVE WE ADDED?
 Branching 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
6.00.1X LECTURE 51

More Related Content

PDF
เออาร์Pdf
PPT
บทที่2
PDF
MIT6_0001F16_Lec1.pdf
PPT
3 algorithm-and-flowchart
PDF
Blueprints: Introduction to Python programming
PPTX
Python programming language presentation
PDF
01a-Introduction. pds.pdf
PPTX
1_Introduction_to_R - disease modeling.pptx
เออาร์Pdf
บทที่2
MIT6_0001F16_Lec1.pdf
3 algorithm-and-flowchart
Blueprints: Introduction to Python programming
Python programming language presentation
01a-Introduction. pds.pdf
1_Introduction_to_R - disease modeling.pptx

Similar to MITx 6.00.1x Introduction to Computer Science and Programming Using Python - 1. Introduction to Python (20)

PDF
Introduction to programming : flowchart, algorithm
PPTX
GRAPHICAL STRUCTURES in our lives
PPTX
Course work Questions and answers .pptx
PPTX
Introductionof c
DOCX
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
PDF
structured programming Introduction to c fundamentals
PPTX
W1-Intro to python.pptx
PDF
ELAVARASAN.pdf
PDF
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
PDF
PPTX
lecture 2.pptx
DOCX
BTE 320-498 Summer 2017 Take Home Exam (200 poi.docx
PDF
CSC1100 - Chapter12 - Flow Charts
PPTX
refactoring code by clean code rules
PDF
Skiron - Experiments in CPU Design in D
PPTX
Bit-Manipulation for competitive programming
PDF
L1. Basic Programming Concepts.pdf
PPTX
2-Algorithms and Complexity analysis.pptx
PPTX
asic computer is an electronic device that can receive, store, process, and o...
PDF
علم البيانات - Data Sience
Introduction to programming : flowchart, algorithm
GRAPHICAL STRUCTURES in our lives
Course work Questions and answers .pptx
Introductionof c
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
structured programming Introduction to c fundamentals
W1-Intro to python.pptx
ELAVARASAN.pdf
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
lecture 2.pptx
BTE 320-498 Summer 2017 Take Home Exam (200 poi.docx
CSC1100 - Chapter12 - Flow Charts
refactoring code by clean code rules
Skiron - Experiments in CPU Design in D
Bit-Manipulation for competitive programming
L1. Basic Programming Concepts.pdf
2-Algorithms and Complexity analysis.pptx
asic computer is an electronic device that can receive, store, process, and o...
علم البيانات - Data Sience
Ad

Recently uploaded (20)

PPTX
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
PDF
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
PDF
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
PPTX
Strengthening open access through collaboration: building connections with OP...
PPTX
Congenital Hypothyroidism pptx
PPTX
Software Engineering BSC DS UNIT 1 .pptx
PPTX
An introduction to Dialogue writing.pptx
PDF
What Is Coercive Control? Understanding and Recognizing Hidden Abuse
PPTX
Introduction and Scope of Bichemistry.pptx
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
PDF
UTS Health Student Promotional Representative_Position Description.pdf
PDF
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
PPTX
Odoo 18 Sales_ Managing Quotation Validity
PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
PDF
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
PDF
5.Universal-Franchise-and-Indias-Electoral-System.pdfppt/pdf/8th class social...
PDF
High Ground Student Revision Booklet Preview
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Strengthening open access through collaboration: building connections with OP...
Congenital Hypothyroidism pptx
Software Engineering BSC DS UNIT 1 .pptx
An introduction to Dialogue writing.pptx
What Is Coercive Control? Understanding and Recognizing Hidden Abuse
Introduction and Scope of Bichemistry.pptx
Information Texts_Infographic on Forgetting Curve.pptx
UTS Health Student Promotional Representative_Position Description.pdf
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
NOI Hackathon - Summer Edition - GreenThumber.pptx
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
Odoo 18 Sales_ Managing Quotation Validity
Skill Development Program For Physiotherapy Students by SRY.pptx
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
5.Universal-Franchise-and-Indias-Electoral-System.pdfppt/pdf/8th class social...
High Ground Student Revision Booklet Preview
Ad

MITx 6.00.1x Introduction to Computer Science and Programming Using Python - 1. Introduction to Python

  • 2. OVERVIEW OF COURSE  learn computational modes of thinking  master the art of computational problem solving  make computers do what you want them to do 6.00.1X LECTURE 2 https://ohthehumanityblog.files.wordpress.com/2014/09/computerthink.gif
  • 3. TOPICS  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 6.00.1X LECTURE 3
  • 4. WHAT DOES A COMPUTER DO  Fundamentally: ◦ performs calculations a billion calculations 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 6.00.1X LECTURE 4
  • 5. 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! 6.00.1X LECTURE 5
  • 6. 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 6.00.1X LECTURE 6
  • 7. 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 6.00.1X LECTURE 7
  • 9. TYPES OF KNOWLEDGE  computers know what you tell them  declarative knowledge is statements of fact. ◦ there is candy taped to the underside of one chair  imperative knowledge is a recipe or “how-to” knowledge 1) face the students at the front of the room 2) count up 3 rows 3) start from the middle section’s left side 4) count to the right 1 chair 5) reach under chair and find it 6.00.1X LECTURE 9
  • 10. A NUMERICAL EXAMPLE  square root of a number x is y such that y*y = x  recipe for deducing square root of number x (e.g. 16) 1) Start with a guess, g 2) If g*g is close enough to x, stop and say g is the answer 3) Otherwise make a new guess by averaging g and x/g 4) Using the new guess, repeat process until close enough 6.00.1X LECTURE 10 g g*g x/g (g+x/g)/2 3 9 5.333 4.1667 4.1667 17.36 3.837 4.0035 4.0035 16.0277 3.997 4.000002
  • 11. WHAT IS A RECIPE 1) sequence of simple steps 2) flow of control process that specifies when each step is executed 3) a means of determining when to stop Steps 1+2+3 = an algorithm! 6.00.1X LECTURE 11
  • 13. 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 6.00.1X LECTURE 13 http://www.upgradenrepair.com/computerparts/computerparts.htm CC-BY SA 2.0 dIaper
  • 14. BASIC MACHINE ARCHITECTURE 6.00.1X LECTURE 14 MEMORY CONTROL UNIT ARITHMETIC LOGIC UNIT INPUT OUTPUT program counter do primitive ops
  • 15. STORED PROGRAM COMPUTER  sequence of instructions stored inside computer ◦ built from predefined set of primitive instructions 1) arithmetic and logic 2) simple tests 3) moving data  special program (interpreter) executes each instruction in order ◦ use tests to change flow of control through sequence ◦ stop when done 6.00.1X LECTURE 15
  • 16. BASIC PRIMITIVES  Turing showed you can compute anything using 6 primitives  modern programming languages have more convenient set of primitives  can abstract methods to create new primitives  anything computable in one language is computable in any other programming language 6.00.1X LECTURE 16 By GabrielF (Own work) [CC BY- SA 3.0 (http://creativecommons.org/lic enses/by-sa/3.0)], via Wikimedia Commons
  • 18. 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 a programming language 6.00.1X LECTURE 18
  • 19. ASPECTS OF LANGUAGES  primitive constructs ◦ English: words ◦ programming language: numbers, strings, simple operators 6.00.1X LECTURE 19
  • 20. ASPECTS OF LANGUAGE  syntax ◦ English: "cat dog boy"  not syntactically valid "cat hugs boy"  syntactically valid ◦ programming language: "hi"5  not syntactically valid 3.2*5  syntactically valid 6.00.1X LECTURE 20
  • 21. ASPECTS OF LANGUAGES  static semantics is which syntactically valid strings have meaning ◦ English: "I are hungry"  syntactically valid but static semantic error ◦ programming language: 3.2*5  syntactically valid 3+"hi"  static semantic error 6.00.1X LECTURE 21
  • 22. ASPECTS OF LANGUAGES  semantics is the meaning associated with a syntactically correct 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 6.00.1X LECTURE 22
  • 23. WHERE 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 crashes, stops running ◦ program runs forever ◦ program gives an answer but different than expected 6.00.1X LECTURE 23
  • 24. 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 6.00.1X LECTURE 24
  • 26. 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 6.00.1X LECTURE 26
  • 27. OBJECTS  programs manipulate data objects  objects have a type that defines the kinds of things programs can do to them  objects are ◦ scalar (cannot be subdivided) ◦ non-scalar (have internal structure that can be accessed) 6.00.1X LECTURE 27
  • 28. 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 6.00.1X LECTURE 28
  • 29. 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.9 to integer 3 6.00.1X LECTURE 29
  • 30. PRINTING 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 6.00.1X LECTURE 30
  • 31. 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> 6.00.1X LECTURE 31
  • 32. OPERATORS ON ints and floats  i+j  the sum  i-j  the difference  i*j  the product  i/j  division  i//j  int division  i%j  the remainder when i is divided by j  i**j  i to the power of j 6.00.1X LECTURE 32 - if both are ints, result is int - if either or both are floats, result is float - result is int, quotient without remainder - result is float
  • 33. SIMPLE OPERATIONS  parentheses used to tell Python to do these operations first ◦ 3*5+1 evaluates to 16 ◦ 3*(5+1) evaluates to 18  operator precedence without parentheses ◦ ** ◦ * ◦ / ◦ + and – executed left to right, as appear in expression 6.00.1X LECTURE 33
  • 35. BINDING VARIABLES AND VALUES  equal sign 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 6.00.1X LECTURE 35
  • 36. 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) 6.00.1X LECTURE 36
  • 37. PROGRAMMING vs MATH  in programming, you do not “solve for x” pi = 3.14159 radius = 2.2 # area of circle area = pi*(radius**2) radius = radius+1 6.00.1X LECTURE 37
  • 38. CHANGING BINDINGS  can re-bind variable 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 again 6.00.1X LECTURE 38 pi radius area 3.14 2.2 15.1976 3.2 pi = 3.14 radius = 2.2 area = pi*(radius**2) radius = radius+1
  • 40. 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 6.00.1X LECTURE 40
  • 41. 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  True if both are True a or b  True if either or both are True 6.00.1X LECTURE 41
  • 42. If right clear, go right If right blocked, go forward If right and front blocked, go left If right , front, left blocked, go back 6.00.1X LECTURE 42
  • 43. BRANCHING PROGRAMS The simplest branching statement is a conditional ◦ A test (expression 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 6.00.1X LECTURE 43
  • 44. A SIMPLE EXAMPLE x = int(input('Enter an integer: ')) if x%2 == 0: print(‘’) print('Even') else: print(‘’) print('Odd') print(’Done with conditional') 6.00.1X LECTURE 44
  • 45. 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 indentation 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 indentation provides a visual structure that reflects the semantic structure of the program 6.00.1X LECTURE 45
  • 46. NESTED CONDITIONALS if x%2 == 0: if x%3 == 0: print('Divisible by 2 and 3’) else: print('Divisible by 2 and not by 3’) elif x%3 == 0: print('Divisible by 3 and not by 2’) 6.00.1X LECTURE 46
  • 47. COMPOUND BOOLEANS if x < y and x < z: print('x is least’) elif y < z: print('y is least’) else: print('z is least’) 6.00.1X LECTURE 47
  • 48. CONTROL FLOW - BRANCHING if <condition>: <expression> <expression> ... if <condition>: <expression> <expression> ... else: <expression> <expression> ... if <condition>: <expression> <expression> ... elif <condition>: <expression> <expression> ... else: <expression> <expression> ...  <condition> has a value True or False  evaluate expressions in that block if <condition> is True 6.00.1X LECTURE 48
  • 49. 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!”) 6.00.1X LECTURE 49
  • 50. = 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 smaller”) else: print("y is smaller”) print("thanks!”) 6.00.1X LECTURE 50
  • 51. WHAT HAVE WE ADDED?  Branching 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 6.00.1X LECTURE 51