From d584afba650c1dad208c164d8f6c0c0bed5d7a55 Mon Sep 17 00:00:00 2001
From: robotuw
Date: Sun, 29 Jan 2023 13:20:28 -0700
Subject: [PATCH 01/90] Update intro-TheWayoftheProgram.ptx
Test change to see what happens. The first section of the first chapter should be slightly updated.
---
pretext/GeneralIntro/intro-TheWayoftheProgram.ptx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pretext/GeneralIntro/intro-TheWayoftheProgram.ptx b/pretext/GeneralIntro/intro-TheWayoftheProgram.ptx
index 84fafc779..8d320b2c4 100644
--- a/pretext/GeneralIntro/intro-TheWayoftheProgram.ptx
+++ b/pretext/GeneralIntro/intro-TheWayoftheProgram.ptx
@@ -1,7 +1,7 @@
The Way of the Program
-
The goal of this book is to teach you to think like a computer scientist. This
+
The goal of this book is to be really awesome, and if there's time after that I guess we can also teach you to think like a computer scientist. This
way of thinking combines some of the best features of mathematics, engineering,
and natural science. Like mathematicians, computer scientists use formal
languages to denote ideas (specifically computations). Like engineers, they
From 0b41e314e875c1b2374864830cd5e1be8cb158ce Mon Sep 17 00:00:00 2001
From: Ethan Richards <42894274+ezrichards@users.noreply.github.com>
Date: Sun, 29 Jan 2023 14:33:22 -0700
Subject: [PATCH 02/90] Update intro-TheWayoftheProgram.ptx
---
pretext/GeneralIntro/intro-TheWayoftheProgram.ptx | 1 +
1 file changed, 1 insertion(+)
diff --git a/pretext/GeneralIntro/intro-TheWayoftheProgram.ptx b/pretext/GeneralIntro/intro-TheWayoftheProgram.ptx
index 8d320b2c4..86e611d5b 100644
--- a/pretext/GeneralIntro/intro-TheWayoftheProgram.ptx
+++ b/pretext/GeneralIntro/intro-TheWayoftheProgram.ptx
@@ -1,6 +1,7 @@
The Way of the Program
+
Testing
The goal of this book is to be really awesome, and if there's time after that I guess we can also teach you to think like a computer scientist. This
way of thinking combines some of the best features of mathematics, engineering,
and natural science. Like mathematicians, computer scientists use formal
From e645ff0e743789a2d19b9c2a296a924afeea07a9 Mon Sep 17 00:00:00 2001
From: Ethan Richards <42894274+ezrichards@users.noreply.github.com>
Date: Sun, 29 Jan 2023 14:47:14 -0700
Subject: [PATCH 03/90] Update intro-TheWayoftheProgram.ptx
---
pretext/GeneralIntro/intro-TheWayoftheProgram.ptx | 1 -
1 file changed, 1 deletion(-)
diff --git a/pretext/GeneralIntro/intro-TheWayoftheProgram.ptx b/pretext/GeneralIntro/intro-TheWayoftheProgram.ptx
index 86e611d5b..8d320b2c4 100644
--- a/pretext/GeneralIntro/intro-TheWayoftheProgram.ptx
+++ b/pretext/GeneralIntro/intro-TheWayoftheProgram.ptx
@@ -1,7 +1,6 @@
The Way of the Program
-
Testing
The goal of this book is to be really awesome, and if there's time after that I guess we can also teach you to think like a computer scientist. This
way of thinking combines some of the best features of mathematics, engineering,
and natural science. Like mathematicians, computer scientists use formal
From 8651f0dcf643e79fbafecff22384b03e6ef646b7 Mon Sep 17 00:00:00 2001
From: Ethan Richards <42894274+ezrichards@users.noreply.github.com>
Date: Sun, 29 Jan 2023 16:36:44 -0700
Subject: [PATCH 04/90] Update intro-TheWayoftheProgram.rst
---
_sources/GeneralIntro/intro-TheWayoftheProgram.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/_sources/GeneralIntro/intro-TheWayoftheProgram.rst b/_sources/GeneralIntro/intro-TheWayoftheProgram.rst
index 305ec46cb..45e1e6806 100644
--- a/_sources/GeneralIntro/intro-TheWayoftheProgram.rst
+++ b/_sources/GeneralIntro/intro-TheWayoftheProgram.rst
@@ -10,7 +10,7 @@
The Way of the Program
======================
-The goal of this book is to teach you to think like a computer scientist. This
+The goal of this book is to be really awesome, and if there's time after that I guess we can also teach you to think like a computer scientist. This
way of thinking combines some of the best features of mathematics, engineering,
and natural science. Like mathematicians, computer scientists use formal
languages to denote ideas (specifically computations). Like engineers, they
From bb11f51b7b850628090e0ef17a3f41fc93bfef3d Mon Sep 17 00:00:00 2001
From: Ethan Richards <42894274+ezrichards@users.noreply.github.com>
Date: Sun, 29 Jan 2023 17:01:42 -0700
Subject: [PATCH 05/90] Update intro-TheWayoftheProgram.rst
---
_sources/GeneralIntro/intro-TheWayoftheProgram.rst | 2 ++
1 file changed, 2 insertions(+)
diff --git a/_sources/GeneralIntro/intro-TheWayoftheProgram.rst b/_sources/GeneralIntro/intro-TheWayoftheProgram.rst
index 45e1e6806..00f2c8923 100644
--- a/_sources/GeneralIntro/intro-TheWayoftheProgram.rst
+++ b/_sources/GeneralIntro/intro-TheWayoftheProgram.rst
@@ -10,6 +10,8 @@
The Way of the Program
======================
+Test Section
+
The goal of this book is to be really awesome, and if there's time after that I guess we can also teach you to think like a computer scientist. This
way of thinking combines some of the best features of mathematics, engineering,
and natural science. Like mathematicians, computer scientists use formal
From 2c5ff70b284baf8ea756b7ea97b117c2d9548b56 Mon Sep 17 00:00:00 2001
From: Ethan Richards <42894274+ezrichards@users.noreply.github.com>
Date: Tue, 31 Jan 2023 08:40:34 -0700
Subject: [PATCH 06/90] Webhook test
---
_sources/GeneralIntro/intro-TheWayoftheProgram.rst | 2 --
1 file changed, 2 deletions(-)
diff --git a/_sources/GeneralIntro/intro-TheWayoftheProgram.rst b/_sources/GeneralIntro/intro-TheWayoftheProgram.rst
index 00f2c8923..45e1e6806 100644
--- a/_sources/GeneralIntro/intro-TheWayoftheProgram.rst
+++ b/_sources/GeneralIntro/intro-TheWayoftheProgram.rst
@@ -10,8 +10,6 @@
The Way of the Program
======================
-Test Section
-
The goal of this book is to be really awesome, and if there's time after that I guess we can also teach you to think like a computer scientist. This
way of thinking combines some of the best features of mathematics, engineering,
and natural science. Like mathematicians, computer scientists use formal
From b5cad79da5f264529d9b1ee13689bdf844e57e54 Mon Sep 17 00:00:00 2001
From: Ethan Richards <42894274+ezrichards@users.noreply.github.com>
Date: Wed, 1 Feb 2023 21:07:25 -0700
Subject: [PATCH 07/90] Update intro-TheWayoftheProgram.rst
---
_sources/GeneralIntro/intro-TheWayoftheProgram.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/_sources/GeneralIntro/intro-TheWayoftheProgram.rst b/_sources/GeneralIntro/intro-TheWayoftheProgram.rst
index 45e1e6806..305ec46cb 100644
--- a/_sources/GeneralIntro/intro-TheWayoftheProgram.rst
+++ b/_sources/GeneralIntro/intro-TheWayoftheProgram.rst
@@ -10,7 +10,7 @@
The Way of the Program
======================
-The goal of this book is to be really awesome, and if there's time after that I guess we can also teach you to think like a computer scientist. This
+The goal of this book is to teach you to think like a computer scientist. This
way of thinking combines some of the best features of mathematics, engineering,
and natural science. Like mathematicians, computer scientists use formal
languages to denote ideas (specifically computations). Like engineers, they
From ef8f9f6218aadd3f8669caa2b2c9f70cd8c157be Mon Sep 17 00:00:00 2001
From: robotuw
Date: Thu, 2 Feb 2023 17:11:48 -0700
Subject: [PATCH 08/90] Webhook check
Can I see the changes deployed on the server without another human having to be involved?
---
_sources/GeneralIntro/intro-TheWayoftheProgram.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/_sources/GeneralIntro/intro-TheWayoftheProgram.rst b/_sources/GeneralIntro/intro-TheWayoftheProgram.rst
index 305ec46cb..2f92901e3 100644
--- a/_sources/GeneralIntro/intro-TheWayoftheProgram.rst
+++ b/_sources/GeneralIntro/intro-TheWayoftheProgram.rst
@@ -10,7 +10,7 @@
The Way of the Program
======================
-The goal of this book is to teach you to think like a computer scientist. This
+Blah, blah blah. The goal of this book is to teach you to think like a computer scientist. This
way of thinking combines some of the best features of mathematics, engineering,
and natural science. Like mathematicians, computer scientists use formal
languages to denote ideas (specifically computations). Like engineers, they
From 8d5dda6744110218753174b4473b25ea9dbf90d3 Mon Sep 17 00:00:00 2001
From: robotuw
Date: Thu, 9 Feb 2023 16:47:24 -0700
Subject: [PATCH 09/90] Chapter Reordering Attempt 1
Figure out how to shuffle chapters. Attempt #1 is via index.rst
---
_sources/index.rst | 14 +++++++-------
1 file changed, 7 insertions(+), 7 deletions(-)
diff --git a/_sources/index.rst b/_sources/index.rst
index 05921b03d..81e34244e 100644
--- a/_sources/index.rst
+++ b/_sources/index.rst
@@ -55,23 +55,23 @@ Table of Contents
GeneralIntro/toctree.rst
SimplePythonData/toctree.rst
Debugging/toctree.rst
+ Strings/toctree.rst
+ Lists/toctree.rst
+ Selection/toctree.rst
+ MoreAboutIteration/toctree.rst
PythonTurtle/toctree.rst
PythonModules/toctree.rst
Functions/toctree.rst
- Selection/toctree.rst
- MoreAboutIteration/toctree.rst
- Strings/toctree.rst
- Lists/toctree.rst
Files/toctree.rst
- Dictionaries/toctree.rst
Exceptions/toctree.rst
- WebApps/toctree.rst
- GUIandEventDrivenProgramming/toctree.rst
IntroRecursion/toctree.rst
ClassesBasics/toctree.rst
ClassesDiggingDeeper/toctree.rst
Inheritance/toctree.rst
UnitTesting/toctree.rst
+ Dictionaries/toctree.rst
+ WebApps/toctree.rst
+ GUIandEventDrivenProgramming/toctree.rst
Labs
::::
From 12778a6f8fae8f8b19f075981c075efab38426c4 Mon Sep 17 00:00:00 2001
From: robotuw
Date: Sat, 11 Feb 2023 14:07:50 -0700
Subject: [PATCH 10/90] Week1-4 Update
Lots of shuffling around, some content updates. Content setting for weeks 1 through 4.
---
.../GeneralIntro/intro-TheWayoftheProgram.rst | 2 +-
_sources/Lists/Aliasing.rst | 2 +-
_sources/Lists/AppendversusConcatenate.rst | 2 +-
_sources/Lists/CloningLists.rst | 2 +-
_sources/Lists/ConcatenationandRepetition.rst | 2 +-
_sources/Lists/ListDeletion.rst | 2 +-
_sources/Lists/ListMembership.rst | 2 +-
_sources/Lists/ListMethods.rst | 2 +-
_sources/Lists/ListSlices.rst | 2 +-
_sources/Lists/Listsandforloops.rst | 2 +-
_sources/Lists/ListsareMutable.rst | 2 +-
_sources/Lists/ObjectsandReferences.rst | 2 +-
_sources/Lists/RepetitionandReferences.rst | 2 +-
_sources/Lists/StringsandLists.rst | 2 +-
.../Lists/TheAccumulatorPatternwithLists.rst | 2 +-
_sources/Lists/TheReturnofLSystems.rst | 2 +-
_sources/Lists/UsingListsasParameters.rst | 2 +-
_sources/Lists/toctree.rst | 8 +-
_sources/Selection/Chainedconditionals.rst | 22 ------
_sources/Selection/toctree.rst | 4 +-
_sources/Strings/ACollectionDataType.rst | 11 ++-
_sources/Strings/StringComparison.rst | 2 +-
_sources/Strings/StringMethods.rst | 73 ++++++-------------
_sources/Strings/StringsareImmutable.rst | 2 +-
_sources/Strings/TheSliceOperator.rst | 3 -
_sources/Strings/toctree.rst | 2 +-
_sources/index.rst | 2 +-
27 files changed, 55 insertions(+), 108 deletions(-)
diff --git a/_sources/GeneralIntro/intro-TheWayoftheProgram.rst b/_sources/GeneralIntro/intro-TheWayoftheProgram.rst
index 2f92901e3..305ec46cb 100644
--- a/_sources/GeneralIntro/intro-TheWayoftheProgram.rst
+++ b/_sources/GeneralIntro/intro-TheWayoftheProgram.rst
@@ -10,7 +10,7 @@
The Way of the Program
======================
-Blah, blah blah. The goal of this book is to teach you to think like a computer scientist. This
+The goal of this book is to teach you to think like a computer scientist. This
way of thinking combines some of the best features of mathematics, engineering,
and natural science. Like mathematicians, computer scientists use formal
languages to denote ideas (specifically computations). Like engineers, they
diff --git a/_sources/Lists/Aliasing.rst b/_sources/Lists/Aliasing.rst
index 8525b989d..560b4d9c5 100644
--- a/_sources/Lists/Aliasing.rst
+++ b/_sources/Lists/Aliasing.rst
@@ -8,7 +8,7 @@
License".
.. qnum::
- :prefix: list-11-
+ :prefix: list-14-
:start: 1
.. index:: alias
diff --git a/_sources/Lists/AppendversusConcatenate.rst b/_sources/Lists/AppendversusConcatenate.rst
index 83d67bb3f..a169ff6c8 100644
--- a/_sources/Lists/AppendversusConcatenate.rst
+++ b/_sources/Lists/AppendversusConcatenate.rst
@@ -8,7 +8,7 @@
License".
.. qnum::
- :prefix: list-16-
+ :prefix: list-11-
:start: 1
Append versus Concatenate
diff --git a/_sources/Lists/CloningLists.rst b/_sources/Lists/CloningLists.rst
index 3376aa8b1..9c7677363 100644
--- a/_sources/Lists/CloningLists.rst
+++ b/_sources/Lists/CloningLists.rst
@@ -8,7 +8,7 @@
License".
.. qnum::
- :prefix: list-12-
+ :prefix: list-15-
:start: 1
.. index:: clone
diff --git a/_sources/Lists/ConcatenationandRepetition.rst b/_sources/Lists/ConcatenationandRepetition.rst
index 6114d799d..74aa97796 100644
--- a/_sources/Lists/ConcatenationandRepetition.rst
+++ b/_sources/Lists/ConcatenationandRepetition.rst
@@ -8,7 +8,7 @@
License".
.. qnum::
- :prefix: list-6-
+ :prefix: list-5-
:start: 1
.. index::
diff --git a/_sources/Lists/ListDeletion.rst b/_sources/Lists/ListDeletion.rst
index e5dd5a6e5..0d6d3638a 100644
--- a/_sources/Lists/ListDeletion.rst
+++ b/_sources/Lists/ListDeletion.rst
@@ -8,7 +8,7 @@
License".
.. qnum::
- :prefix: list-9-
+ :prefix: list-8-
:start: 1
.. index:: del; a list portion
diff --git a/_sources/Lists/ListMembership.rst b/_sources/Lists/ListMembership.rst
index b77dfe2b7..a47245a1c 100644
--- a/_sources/Lists/ListMembership.rst
+++ b/_sources/Lists/ListMembership.rst
@@ -8,7 +8,7 @@
License".
.. qnum::
- :prefix: list-5-
+ :prefix: list-12-
:start: 1
.. index:: in; membership operator
diff --git a/_sources/Lists/ListMethods.rst b/_sources/Lists/ListMethods.rst
index 21e44e220..509025559 100644
--- a/_sources/Lists/ListMethods.rst
+++ b/_sources/Lists/ListMethods.rst
@@ -8,7 +8,7 @@
License".
.. qnum::
- :prefix: list-14-
+ :prefix: list-9-
:start: 1
List Methods
diff --git a/_sources/Lists/ListSlices.rst b/_sources/Lists/ListSlices.rst
index edfe3147b..ec90110e5 100644
--- a/_sources/Lists/ListSlices.rst
+++ b/_sources/Lists/ListSlices.rst
@@ -8,7 +8,7 @@
License".
.. qnum::
- :prefix: list-7-
+ :prefix: list-6-
:start: 1
.. index::
diff --git a/_sources/Lists/Listsandforloops.rst b/_sources/Lists/Listsandforloops.rst
index 9d7a87e58..36bd171fb 100644
--- a/_sources/Lists/Listsandforloops.rst
+++ b/_sources/Lists/Listsandforloops.rst
@@ -8,7 +8,7 @@
License".
.. qnum::
- :prefix: list-17-
+ :prefix: list-18-
:start: 1
Lists and ``for`` loops
diff --git a/_sources/Lists/ListsareMutable.rst b/_sources/Lists/ListsareMutable.rst
index ef901545e..cfc3c6c30 100644
--- a/_sources/Lists/ListsareMutable.rst
+++ b/_sources/Lists/ListsareMutable.rst
@@ -8,7 +8,7 @@
License".
.. qnum::
- :prefix: list-8-
+ :prefix: list-7-
:start: 1
Lists are Mutable
diff --git a/_sources/Lists/ObjectsandReferences.rst b/_sources/Lists/ObjectsandReferences.rst
index c39a2db5a..2efdfbf84 100644
--- a/_sources/Lists/ObjectsandReferences.rst
+++ b/_sources/Lists/ObjectsandReferences.rst
@@ -8,7 +8,7 @@
License".
.. qnum::
- :prefix: list-10-
+ :prefix: list-13-
:start: 1
diff --git a/_sources/Lists/RepetitionandReferences.rst b/_sources/Lists/RepetitionandReferences.rst
index b353e0e18..ee8b4f302 100644
--- a/_sources/Lists/RepetitionandReferences.rst
+++ b/_sources/Lists/RepetitionandReferences.rst
@@ -8,7 +8,7 @@
License".
.. qnum::
- :prefix: list-13-
+ :prefix: list-16-
:start: 1
Repetition and References
diff --git a/_sources/Lists/StringsandLists.rst b/_sources/Lists/StringsandLists.rst
index f2de1e085..b1c4fd3f2 100644
--- a/_sources/Lists/StringsandLists.rst
+++ b/_sources/Lists/StringsandLists.rst
@@ -8,7 +8,7 @@
License".
.. qnum::
- :prefix: list-24-
+ :prefix: list-10-
:start: 1
Strings and Lists
diff --git a/_sources/Lists/TheAccumulatorPatternwithLists.rst b/_sources/Lists/TheAccumulatorPatternwithLists.rst
index 5e77a5b1a..a1f3cddf5 100644
--- a/_sources/Lists/TheAccumulatorPatternwithLists.rst
+++ b/_sources/Lists/TheAccumulatorPatternwithLists.rst
@@ -7,7 +7,7 @@
License".
.. qnum::
- :prefix: list-29-
+ :prefix: list-19-
:start: 1
.. _accumulator_lists:
diff --git a/_sources/Lists/TheReturnofLSystems.rst b/_sources/Lists/TheReturnofLSystems.rst
index 3bfb82339..c91622fc1 100644
--- a/_sources/Lists/TheReturnofLSystems.rst
+++ b/_sources/Lists/TheReturnofLSystems.rst
@@ -8,7 +8,7 @@
License".
.. qnum::
- :prefix: list-15-
+ :prefix: list-17-
:start: 1
The Return of L-Systems
diff --git a/_sources/Lists/UsingListsasParameters.rst b/_sources/Lists/UsingListsasParameters.rst
index 8f6cbc43a..09398e42e 100644
--- a/_sources/Lists/UsingListsasParameters.rst
+++ b/_sources/Lists/UsingListsasParameters.rst
@@ -8,7 +8,7 @@
License".
.. qnum::
- :prefix: list-18-
+ :prefix: list-20-
:start: 1
Using Lists as Parameters
diff --git a/_sources/Lists/toctree.rst b/_sources/Lists/toctree.rst
index 3b79795c2..ffd1c81fa 100644
--- a/_sources/Lists/toctree.rst
+++ b/_sources/Lists/toctree.rst
@@ -9,18 +9,19 @@ Lists
ListValues.rst
ListLength.rst
AccessingElements.rst
- ListMembership.rst
ConcatenationandRepetition.rst
ListSlices.rst
ListsareMutable.rst
ListDeletion.rst
+ ListMethods.rst
+ StringsandLists.rst
+ AppendversusConcatenate.rst
+ ListMembership.rst
ObjectsandReferences.rst
Aliasing.rst
CloningLists.rst
RepetitionandReferences.rst
- ListMethods.rst
TheReturnofLSystems.rst
- AppendversusConcatenate.rst
Listsandforloops.rst
TheAccumulatorPatternwithLists.rst
UsingListsasParameters.rst
@@ -29,7 +30,6 @@ Lists
FunctionsthatProduceLists.rst
ListComprehensions.rst
NestedLists.rst
- StringsandLists.rst
listTypeConversionFunction.rst
TuplesandMutability.rst
TupleAssignment.rst
diff --git a/_sources/Selection/Chainedconditionals.rst b/_sources/Selection/Chainedconditionals.rst
index ec543f191..96b3a669b 100644
--- a/_sources/Selection/Chainedconditionals.rst
+++ b/_sources/Selection/Chainedconditionals.rst
@@ -135,26 +135,4 @@ Here is the same program using ``elif``.
print(x, " is 0")
-.. mchoice:: test_question6_7_2
- :practice: T
- :answer_a: a
- :answer_b: b
- :answer_c: c
- :correct: c
- :feedback_a: While the value in x is less than the value in y (3 is less than 5) it is not less than the value in z (3 is not less than 2).
- :feedback_b: The value in y is not less than the value in x (5 is not less than 3).
- :feedback_c: Since the first two Boolean expressions are false the else will be executed.
-
- What will the following code print if x = 3, y = 5, and z = 2?
-
- .. code-block:: python
-
- if x < y and x < z:
- print("a")
- elif y < x and y < z:
- print("b")
- else:
- print("c")
-
-
diff --git a/_sources/Selection/toctree.rst b/_sources/Selection/toctree.rst
index cd2eb1482..03604c8e8 100644
--- a/_sources/Selection/toctree.rst
+++ b/_sources/Selection/toctree.rst
@@ -6,12 +6,12 @@ Selection
:maxdepth: 2
BooleanValuesandBooleanExpressions.rst
- Logicaloperators.rst
- PrecedenceofOperators.rst
ConditionalExecutionBinarySelection.rst
OmittingtheelseClauseUnarySelection.rst
Nestedconditionals.rst
Chainedconditionals.rst
+ Logicaloperators.rst
+ PrecedenceofOperators.rst
BooleanFunctions.rst
Glossary.rst
Exercises.rst
diff --git a/_sources/Strings/ACollectionDataType.rst b/_sources/Strings/ACollectionDataType.rst
index 03c5e92c7..e8eda97bf 100644
--- a/_sources/Strings/ACollectionDataType.rst
+++ b/_sources/Strings/ACollectionDataType.rst
@@ -14,12 +14,10 @@
A Collection Data Type
----------------------
-So far we have seen built-in types like: ``int``, ``float``,
-``bool``, ``str`` and we've seen lists.
-``int``, ``float``, and
-``bool`` are considered to be simple or primitive data types because their values are not composed
+So far we have seen built-in types like: ``int``, ``float``, and ``str``.
+``int`` and ``float`` are considered to be simple or primitive data types because their values are not composed
of any smaller parts. They cannot be broken down.
-On the other hand, strings and lists are different from the others because they
+On the other hand, strings (and lists that we will talk about next chapter) are different from the others because they
are made up of smaller pieces. In the case of strings, they are made up of smaller
strings each containing one **character**.
@@ -30,7 +28,8 @@ single entity (the whole), or we may want to access its parts. This ambiguity is
Strings can be defined as sequential collections of characters. This means that the individual characters
that make up the string are assumed to be in a particular order from left to right.
-A string that contains no characters, often referred to as the **empty string**, is still considered to be a string. It is simply a sequence of zero characters and is represented by '' or "" (two single or two double quotes with nothing in between).
+A string that contains no characters, often referred to as the **empty string**, is still considered to be a string.
+It is simply a sequence of zero characters and is represented by '' or "" (two single or two double quotes with nothing in between).
.. index:: string operations, concatenation
diff --git a/_sources/Strings/StringComparison.rst b/_sources/Strings/StringComparison.rst
index e239e4b69..e566331e4 100644
--- a/_sources/Strings/StringComparison.rst
+++ b/_sources/Strings/StringComparison.rst
@@ -8,7 +8,7 @@
License".
.. qnum::
- :prefix: strings-8-
+ :prefix: strings-9-
:start: 1
diff --git a/_sources/Strings/StringMethods.rst b/_sources/Strings/StringMethods.rst
index 307cfda0a..c08c30fe6 100644
--- a/_sources/Strings/StringMethods.rst
+++ b/_sources/Strings/StringMethods.rst
@@ -16,13 +16,11 @@
String Methods
--------------
-We previously saw that each turtle instance has its own attributes and
-a number of methods that can be applied to the instance. For example,
-we wrote ``tess.right(90)`` when we wanted the turtle object ``tess`` to perform the ``right`` method to turn
-to the right 90 degrees. The "dot notation" is the way we connect the name of an object to the name of a method
-it can perform.
+We previously used a few functions like ``print()`` and ``input()``. A **method** is a function that is attached to a specific Python object.
+To access this function, we write the object, then a dot ``.``, and then the name of the method. The "dot notation" is the way we connect the name of an object to the name of a method
+it can perform. For example, we can write ``ss.upper()`` when we wanted the string ``ss`` to perform the ``upper()`` method to create an upper-case version of itself.
-Strings are also objects. Each string instance has its own attributes and methods. The most important attribute of the string is the collection of characters. There are a wide variety of methods. Try the following program.
+Remember that Strings are objects. Each string instance has its own attributes and methods. The most important attribute of the string is the collection of characters. There are a wide variety of methods. Try the following program.
.. activecode:: chp08_upper
@@ -157,7 +155,7 @@ change the original. You can also consult the `Python documentation for strings
.. _Format-Strings:
-String Format Method
+F-Strings
~~~~~~~~~~~~~~~~~~~~~
In grade school quizzes a common convention is to use fill-in-the blanks. For instance,
@@ -168,26 +166,25 @@ In grade school quizzes a common convention is to use fill-in-the blanks. For in
and you can fill in the name of the person greeted, and combine
given text with a chosen insertion. *We use this as an analogy:*
Python has a similar
-construction, better called fill-in-the-braces. The string method ``format``, makes
+construction, called a formatted string or an **f-string**. An f-string makes
substitutions into places in a string
enclosed in braces. Run this code:
.. activecode:: ch08_methods3
person = input('Your name: ')
- greeting = 'Hello {}!'.format(person)
+ greeting = f'Hello {person}!'
print(greeting)
There are several new ideas here!
-The string for the ``format`` method has a special form, with braces embedded.
-Such a string is called a *format string*. Places where
-braces are embedded are replaced by the value of an expression
-taken from the parameter list for the ``format`` method. There are many
+The string has been formatted in a new way. We have included an ``f`` before the starting quotation mark.
+Such a string is called an *f-string*. Places where
+braces are embedded are replaced by the value of the expression inside the braces. There are many
variations on the syntax between the braces. In this case we use
the syntax where the first (and only) location in the string with
-braces has a substitution made from the first (and only) parameter.
+braces has the variable ``person``. When this code is evaluated, the value of the person variable is placed in the string in this location.
In the code above, this new string is assigned to the identifier
``greeting``, and then the string is printed.
@@ -201,7 +198,7 @@ version:
.. activecode:: ch08_methods4
person = input('Enter your name: ')
- print('Hello {}!'.format(person))
+ print(f'Hello {person}!')
There can be multiple substitutions, with data of any type.
Next we use floats. Try original price $2.50 with a 7% discount:
@@ -211,35 +208,29 @@ Next we use floats. Try original price $2.50 with a 7% discount:
origPrice = float(input('Enter the original price: $'))
discount = float(input('Enter discount percentage: '))
newPrice = (1 - discount/100)*origPrice
- calculation = '${} discounted by {}% is ${}.'.format(origPrice, discount, newPrice)
+ calculation = f'${origPrice} discounted by {discount}% is ${newPrice}.'
print(calculation)
-The parameters are inserted into the braces in order.
-
If you used the data suggested, this result is not satisfying.
Prices should appear with exactly two places beyond the decimal point,
but that is not the default way to display floats.
-Format strings can give further information inside the braces
+F-strings can give further information inside the braces
showing how to specially format data.
In particular floats can be shown with a specific number of decimal places.
-For two decimal places, put ``:.2f`` inside the braces for the monetary values:
+For two decimal places, put ``:.2f`` inside the braces but after the variable name for the monetary values:
.. activecode:: ch08_methods6
origPrice = float(input('Enter the original price: $'))
discount = float(input('Enter discount percentage: '))
newPrice = (1 - discount/100)*origPrice
- calculation = '${:.2f} discounted by {}% is ${:.2f}.'.format(origPrice, discount, newPrice)
+ calculation = f'${origPrice:.2f} discounted by {discount}% is ${newPrice:.2f}.'
print(calculation)
The 2 in the format modifier can be replaced by another integer to round to that
specified number of digits.
-This kind of format string depends directly on the order of the
-parameters to the format method. There are other approaches that we will
-skip here, explicitly numbering substitutions and taking substitutions from a dictionary.
-
A technical point: Since braces have special meaning in a format
string, there must be a special rule if you want braces to actually
be included in the final *formatted* string. The rule is to double
@@ -251,40 +242,22 @@ formatted string::
a = 5
b = 9
- setStr = 'The set is {{ {},{} }}.'.format(a, b)
+ setStr = f'The set is {{ {a},{b} }}.'
print(setStr)
Unfortunately, at the time of this writing, the ActiveCode format implementation has a bug,
printing doubled braces, but standard Python prints ``{5, 9}``.
-You can have multiple placeholders indexing the same argument, or perhaps even have extra
-arguments that are not referenced at all:
-
-.. activecode:: ch08_formatspecification
-
- letter = """
- Dear {0} {2}.
- {0}, I have an interesting money-making proposition for you!
- If you deposit $10 million into my bank account, I can
- double your money ...
- """
-
- print(letter.format("Paris", "Whitney", "Hilton"))
- print(letter.format("Bill", "Henry", "Gates"))
-
-
-
-
.. mchoice:: test_question8_3_3
:practice: T
:answer_a: Nothing - it causes an error
- :answer_b: sum of {} and {} is {}; product: {}. 2 6 8 12
+ :answer_b: sum of {} and {} is {}; product: {}.
:answer_c: sum of 2 and 6 is 8; product: 12.
:answer_d: sum of {2} and {6} is {8}; product: {12}.
:correct: c
- :feedback_a: It is legal format syntax: put the data in place of the braces.
- :feedback_b: Put the data into the format string; not after it.
- :feedback_c: Yes, correct substitutions!
+ :feedback_a: It is legal format syntax.
+ :feedback_b: Put the value of each expression in place of the braces.
+ :feedback_c: Yes, correct!
:feedback_d: Close: REPLACE the braces.
@@ -294,7 +267,7 @@ arguments that are not referenced at all:
x = 2
y = 6
- print('sum of {} and {} is {}; product: {}.'.format( x, y, x+y, x*y))
+ print(f'sum of {x} and {y} is {x+y}; product: {x*y}.')
.. mchoice:: test_question8_3_4
@@ -313,6 +286,6 @@ arguments that are not referenced at all:
.. code-block:: python
v = 2.34567
- print('{:.1f} {:.2f} {:.7f}'.format(v, v, v))
+ print(f'{v:.1f} {v:.2f} {v:.7f}')
diff --git a/_sources/Strings/StringsareImmutable.rst b/_sources/Strings/StringsareImmutable.rst
index 3e4bca44e..ad934011e 100644
--- a/_sources/Strings/StringsareImmutable.rst
+++ b/_sources/Strings/StringsareImmutable.rst
@@ -8,7 +8,7 @@
License".
.. qnum::
- :prefix: strings-9-
+ :prefix: strings-8-
:start: 1
.. index:: mutable, immutable
diff --git a/_sources/Strings/TheSliceOperator.rst b/_sources/Strings/TheSliceOperator.rst
index f8fb8082d..283f00dc3 100644
--- a/_sources/Strings/TheSliceOperator.rst
+++ b/_sources/Strings/TheSliceOperator.rst
@@ -32,9 +32,6 @@ selecting a character:
The `slice` operator ``[n:m]`` returns the part of the string from the n'th character
to the m'th character, including the first but excluding the last. In other words, start with the character at index n and
go up to but do not include the character at index m.
-This
-behavior may seem counter-intuitive but if you recall the ``range`` function, it did not include its end
-point either.
If you omit the first index (before the colon), the slice starts at the
beginning of the string. If you omit the second index, the slice goes to the
diff --git a/_sources/Strings/toctree.rst b/_sources/Strings/toctree.rst
index 86ae0ba68..8614a42a8 100644
--- a/_sources/Strings/toctree.rst
+++ b/_sources/Strings/toctree.rst
@@ -12,8 +12,8 @@ Strings
StringMethods.rst
Length.rst
TheSliceOperator.rst
- StringComparison.rst
StringsareImmutable.rst
+ StringComparison.rst
TraversalandtheforLoopByItem.rst
TraversalandtheforLoopByIndex.rst
TraversalandthewhileLoop.rst
diff --git a/_sources/index.rst b/_sources/index.rst
index 81e34244e..0ea5c8280 100644
--- a/_sources/index.rst
+++ b/_sources/index.rst
@@ -54,10 +54,10 @@ Table of Contents
GeneralIntro/toctree.rst
SimplePythonData/toctree.rst
- Debugging/toctree.rst
Strings/toctree.rst
Lists/toctree.rst
Selection/toctree.rst
+ Debugging/toctree.rst
MoreAboutIteration/toctree.rst
PythonTurtle/toctree.rst
PythonModules/toctree.rst
From 103da7beb4f04cf5803e5e6045852e126f96abe4 Mon Sep 17 00:00:00 2001
From: robotuw
Date: Sun, 12 Feb 2023 10:41:53 -0700
Subject: [PATCH 11/90] Loops chapter revised
This was a complex one. Pushing now to see how changes went.
---
.../FlowofExecutionofthewhileLoop.rst | 52 +++++
.../SentinelValuesAndValidation.rst | 56 +++--
.../MoreAboutIteration/The3n1Sequence.rst | 29 +--
_sources/MoreAboutIteration/TheforLoop.rst | 87 ++++++++
.../MoreAboutIteration/TherangeFunction.rst | 193 ++++++++++++++++++
.../MoreAboutIteration/ThewhileStatement.rst | 166 +++++++--------
.../intro-IterationRevisited.rst | 8 +-
_sources/MoreAboutIteration/toctree.rst | 15 +-
.../ConditionalExecutionBinarySelection.rst | 18 +-
9 files changed, 463 insertions(+), 161 deletions(-)
create mode 100644 _sources/MoreAboutIteration/FlowofExecutionofthewhileLoop.rst
create mode 100644 _sources/MoreAboutIteration/TheforLoop.rst
create mode 100644 _sources/MoreAboutIteration/TherangeFunction.rst
diff --git a/_sources/MoreAboutIteration/FlowofExecutionofthewhileLoop.rst b/_sources/MoreAboutIteration/FlowofExecutionofthewhileLoop.rst
new file mode 100644
index 000000000..1f8e38d99
--- /dev/null
+++ b/_sources/MoreAboutIteration/FlowofExecutionofthewhileLoop.rst
@@ -0,0 +1,52 @@
+.. Copyright (C) Brad Miller, David Ranum, Jeffrey Elkner, Peter Wentworth, Allen B. Downey, Chris
+ Meyers, and Dario Mitchell. Permission is granted to copy, distribute
+ and/or modify this document under the terms of the GNU Free Documentation
+ License, Version 1.3 or any later version published by the Free Software
+ Foundation; with Invariant Sections being Forward, Prefaces, and
+ Contributor List, no Front-Cover Texts, and no Back-Cover Texts. A copy of
+ the license is included in the section entitled "GNU Free Documentation
+ License".
+
+.. qnum::
+ :prefix: turtle-5-
+ :start: 1
+
+.. index:: control flow, flow of execution
+
+
+
+Flow of Execution of the while Loop
+---------------------------------
+
+As a program executes, the interpreter always keeps track of which statement is
+about to be executed. We call this the **control flow**, or the **flow of
+execution** of the program. When humans execute programs, they often use their
+finger to point to each statement in turn. So you could think of control flow
+as "Python's moving finger".
+
+Control flow until now has been strictly top to bottom, one statement at a
+time. We call this type of control **sequential**. In Python flow is sequential as long as
+successive statements are indented the *same* amount. The ``while`` statement
+introduces indented sub-statements after the while-loop heading.
+
+Flow of control is often easy to visualize and understand if we draw a flowchart.
+This flowchart shows the exact steps and logic of how the ``while`` statement executes.
+
+.. image:: Figures/while_flow.png
+ :width: 300px
+ :align: center
+
+
+A codelens demonstration is a good way to help you visualize exactly how the flow of control
+works with the while loop. Try stepping forward and backward through the program by pressing
+the buttons. You can see the value of ``count`` change as the loop iterates through the values from 10 to 0.
+
+.. codelens:: vtest
+
+ count = 10
+ while count > 0:
+ print(count)
+ count = count - 1
+ print("Blastoff!")
+
+
diff --git a/_sources/MoreAboutIteration/SentinelValuesAndValidation.rst b/_sources/MoreAboutIteration/SentinelValuesAndValidation.rst
index a5f14f344..67badd49b 100644
--- a/_sources/MoreAboutIteration/SentinelValuesAndValidation.rst
+++ b/_sources/MoreAboutIteration/SentinelValuesAndValidation.rst
@@ -21,7 +21,7 @@ Other uses of ``while``
Sentinel Values
~~~~~~~~~~~~~~~~~~~
-Indefinite loops are much more common in the real world than definite loops.
+The indefinite loops provided by the ``while`` statement are common in the real world.
* If you are selling tickets to an event, you don't know in advance how
many tickets you will sell. You keep selling tickets as long as people come
@@ -61,24 +61,21 @@ zero is a **sentinel value**, a value used to signal the end of the loop. Here's
.. activecode:: ch07_sentinel
:timelimit: 60000
- def checkout():
- total = 0
- count = 0
- moreItems = True
- while moreItems:
- price = float(input('Enter price of item (0 when done): '))
- if price != 0:
- count = count + 1
- total = total + price
- print('Subtotal: $', total)
- else:
- moreItems = False
- average = total / count
- print('Total items:', count)
- print('Total $', total)
- print('Average price per item: $', average)
-
- checkout()
+ total = 0
+ count = 0
+ moreItems = True
+ while moreItems:
+ price = float(input('Enter price of item (0 when done): '))
+ if price != 0:
+ count = count + 1
+ total = total + price
+ print('Subtotal: $', total)
+ else:
+ moreItems = False
+ average = total / count
+ print('Total items:', count)
+ print('Total $', total)
+ print('Average price per item: $', average)
There are still a few problems with this program.
@@ -123,18 +120,15 @@ When you run the following code, try typing something other than Y or N to see h
.. activecode:: ch07_validation
:timelimit: 60000
- def get_yes_or_no(message):
- valid_input = False
- answer = input(message)
- while not valid_input:
- answer = answer.upper() # convert to upper case
- if answer == 'Y' or answer == 'N':
- valid_input = True
- else:
- answer = input('Please enter Y for yes or N for no. \n' + message)
- return answer
-
- response = get_yes_or_no('Do you like lima beans? Y)es or N)o: ')
+ valid_input = False
+ response = input('Do you like lima beans? Y)es or N)o: ')
+ while not valid_input:
+ response = response.upper() # convert to upper case
+ if response == 'Y' or response == 'N':
+ valid_input = True
+ else:
+ response = input('Please enter Y for yes or N for no. \n' + message)
+
if response == 'Y':
print('Great! They are very healthy.')
else:
diff --git a/_sources/MoreAboutIteration/The3n1Sequence.rst b/_sources/MoreAboutIteration/The3n1Sequence.rst
index 25d0b377d..983638731 100644
--- a/_sources/MoreAboutIteration/The3n1Sequence.rst
+++ b/_sources/MoreAboutIteration/The3n1Sequence.rst
@@ -21,21 +21,20 @@ the next term of the sequence from ``n``, either by halving ``n``,
whenever ``n`` is even, or else by multiplying it by three and adding 1 when it is odd. The sequence
terminates when ``n`` reaches 1.
-This Python function captures that algorithm. Try running this program several times supplying different values for n.
+This Python code captures that algorithm. Try running this program several times supplying different values for n.
.. activecode:: ch07_indef1
- def seq3np1(n):
- """ Print the 3n+1 sequence from n, terminating when it reaches 1."""
- while n != 1:
- print(n)
- if n % 2 == 0: # n is even
- n = n // 2
- else: # n is odd
- n = n * 3 + 1
- print(n) # the last print is 1
-
- seq3np1(3)
+ n = 3
+
+ """ Print the 3n+1 sequence from n, terminating when it reaches 1."""
+ while n != 1:
+ print(n)
+ if n % 2 == 0: # n is even
+ n = n // 2
+ else: # n is odd
+ n = n * 3 + 1
+ print(n) # the last print is 1
@@ -57,12 +56,6 @@ time through the loop until it reaches 1.
You might like to have some fun and see if you can find a small starting
number that needs more than a hundred steps before it terminates.
-
-.. admonition:: Lab
-
- * `Experimenting with the 3n+1 Sequence <../Labs/sequencelab.html>`_ In this guided lab exercise we will try to learn more about this sequence.
-
-
Particular values aside, the interesting question is whether we can prove that
this sequence terminates for *all* positive values of ``n``. So far, no one has been able
to prove it *or* disprove it!
diff --git a/_sources/MoreAboutIteration/TheforLoop.rst b/_sources/MoreAboutIteration/TheforLoop.rst
new file mode 100644
index 000000000..46e28602b
--- /dev/null
+++ b/_sources/MoreAboutIteration/TheforLoop.rst
@@ -0,0 +1,87 @@
+.. Copyright (C) Brad Miller, David Ranum, Jeffrey Elkner, Peter Wentworth, Allen B. Downey, Chris
+ Meyers, and Dario Mitchell. Permission is granted to copy, distribute
+ and/or modify this document under the terms of the GNU Free Documentation
+ License, Version 1.3 or any later version published by the Free Software
+ Foundation; with Invariant Sections being Forward, Prefaces, and
+ Contributor List, no Front-Cover Texts, and no Back-Cover Texts. A copy of
+ the license is included in the section entitled "GNU Free Documentation
+ License".
+
+.. qnum::
+ :prefix: turtle-3-
+ :start: 1
+
+.. index:: for loop, iteration, body
+ loop; for
+
+The ``for`` Loop
+----------------
+
+.. youtube:: xGSfiZt5cdw
+ :divid: forloopvid
+ :height: 315
+ :width: 560
+ :align: left
+
+The ``while`` statement is a general-purpose tool for iteration, and is necessary for any instance of iteration where we don't know how many repetitions will be needed.
+However, if we do know how many are needed, there is a more efficient method: the ``for`` statement.
+
+As a simple example, let's say we have some friends, and
+we'd like to send them each an email inviting them to our party. We
+don't quite know how to send email yet, so for the moment we'll just print a
+message for each friend.
+
+.. activecode:: ch03_4
+ :nocanvas:
+ :tour_1: "Overall Tour"; 1-2: Example04_Tour01_Line01; 2: Example04_Tour01_Line02; 1: Example04_Tour01_Line03;
+
+ for name in ["Joe", "Amy", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]:
+ print(f"Hi {name}! Please come to my party on Saturday!")
+
+
+Take a look at the output produced when you press the ``run`` button. There is one line printed for each friend. Here's how it works:
+
+
+* **name** in this ``for`` statement is the **loop variable**.
+* The list of names in the square brackets is a regular list. Later we'll see that other types besides lists can be put in this spot.
+* Line 2 is the **loop body**. Like with while, the loop body is always
+ indented. The loop body is performed one time for each name in the list.
+* On each *iteration* or *pass* of the loop, a check is done to see if
+ there are still more items to be processed. If there are none left (this is
+ called the **terminating condition** of the loop), the loop has finished.
+ Program execution continues at the next statement after the loop body.
+* If there are items still to be processed, the loop variable is updated to
+ refer to the next item in the list. This means, in this case, that the loop
+ body is executed here 7 times, and each time ``name`` will refer to a different
+ friend.
+* At the end of each execution of the body of the loop, Python returns
+ to the ``for`` statement, to see if there are more items to be handled.
+
+.. note::
+
+ Introduction of the for statement causes us to think about the types of iteration we have seen. The ``for`` statement will always iterate through a sequence of
+ values like the list of names for the party.
+ Since we know that it will iterate once for each value in the collection, it is often said that a ``for`` loop creates a
+ **definite iteration** because we definitely know how many times we are going to iterate. On the other
+ hand, the ``while`` statement is dependent on a condition that needs to evaluate to ``False`` in order
+ for the loop to terminate. Since we do not necessarily know when this will happen, it creates what we
+ call **indefinite iteration**. Indefinite iteration simply means that we don't know how many times we will repeat but eventually the condition
+ controlling the iteration will fail and the iteration will stop. (Unless we have an infinite loop which is of course a problem.)
+
+What you will notice here is that the ``while`` loop is more work for
+you --- the programmer --- than the equivalent ``for`` loop. When using a ``while``
+loop you have to control the loop variable yourself. You give it an initial value, test
+for completion, and then make sure you change something in the body so that the loop
+terminates.
+
+**Check your understanding**
+
+.. mchoice:: test_question7_6_1
+ :practice: T
+ :answer_a: True
+ :answer_b: False
+ :correct: a
+ :feedback_a: Although the while loop uses a different syntax, it is just as powerful as a for-loop and often more flexible.
+ :feedback_b: Often a for-loop is more natural and convenient for a task, but that same task can always be expressed using a while loop.
+
+ True or False: You can rewrite any for-loop as a while-loop.
diff --git a/_sources/MoreAboutIteration/TherangeFunction.rst b/_sources/MoreAboutIteration/TherangeFunction.rst
new file mode 100644
index 000000000..fcafc68c3
--- /dev/null
+++ b/_sources/MoreAboutIteration/TherangeFunction.rst
@@ -0,0 +1,193 @@
+.. Copyright (C) Brad Miller, David Ranum, Jeffrey Elkner, Peter Wentworth, Allen B. Downey, Chris
+ Meyers, and Dario Mitchell. Permission is granted to copy, distribute
+ and/or modify this document under the terms of the GNU Free Documentation
+ License, Version 1.3 or any later version published by the Free Software
+ Foundation; with Invariant Sections being Forward, Prefaces, and
+ Contributor List, no Front-Cover Texts, and no Back-Cover Texts. A copy of
+ the license is included in the section entitled "GNU Free Documentation
+ License".
+
+.. qnum::
+ :prefix: turtle-8-
+ :start: 1
+
+The range Function
+------------------
+
+.. youtube:: YK8QlIT3__M
+ :divid: advrange
+ :height: 315
+ :width: 560
+ :align: left
+
+In our first example of a while loop, we counted down from 10 to 0. If we were to consider doing this with a for loop, we would need to construct our own series of numbers
+to loop through them.
+
+It turns out that generating lists with a specific number of integers is a very common thing to do, especially when you
+want to write simple ``for loop`` controlled iteration. The conventional thing to do is to use a list of integers starting with 0.
+In fact, these lists are so popular that Python gives us special built-in ``range`` objects that can deliver a sequence of values to
+the ``for`` loop. When called with one parameter, the sequence provided by ``range`` always starts with 0. If you ask for ``range(4)``, then you will get 4 values starting with 0. In other words, 0, 1, 2, and finally 3. Notice that 4 is not included since we started with 0. Likewise, ``range(10)`` provides 10 values, 0 through 9.
+
+.. sourcecode:: python
+
+ for i in range(4):
+ # Executes the body with i = 0, then 1, then 2, then 3
+ for x in range(10):
+ # sets x to each of ... [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+
+.. note::
+
+ Computer scientists like to count from 0!
+
+
+So to count something ten times, a good Python programmer would do this:
+
+.. sourcecode:: python
+
+ for i in range(10):
+ #do something
+
+
+The `range `_ function is actually a very powerful function
+when it comes to
+creating sequences of integers. It can take one, two, or three parameters. We have seen
+the simplest case of one parameter such as ``range(4)`` which creates ``[0, 1, 2, 3]``.
+But what if we really want to have the sequence ``[1, 2, 3, 4]``?
+We can do this by using a two parameter version of ``range`` where the first parameter is the starting point and the second parameter is the ending point. The evaluation of ``range(1,5)`` produces the desired sequence. What happened to the 5?
+In this case we interpret the parameters of the range function to mean
+range(start,beyondLast), where beyondLast means an index past the last index we want. In the 2-parameter version
+of range, that is the last index included + 1.
+
+
+.. note::
+
+ Why in the world would range not just work like range(start,
+ stop)? Think about it like this. Because computer scientists like to
+ start counting at 0 instead of 1, ``range(N)`` produces a sequence of
+ things that is N long, but the consequence of this is that the final
+ number of the sequence is N-1. In the case of start,
+ stop it helps to simply think that the sequence begins with start and
+ continues as long as the number is less than stop.
+
+.. note::
+ The range function is *lazy*: It produces the next element only when needed.
+ With a regular Python 3 interpreter, printing a range does *not* calculate all the elements.
+ To immediately calculate all the elements in a range,
+ wrap the range in a list, like ``list(range(4))``.
+ Activecode is not designed to work on very long sequences, and it may allow you to be
+ sloppy, avoiding the list function, and *see* the elements in the range with ``print(range(4))``.
+
+Here are two examples for you to run. Try them and then add another line below to create a sequence starting
+at 10 and going up to 20 (including 20).
+
+.. activecode:: ch03_5
+ :nocanvas:
+
+ print(list(range(4)))
+ print(list(range(1, 5)))
+
+
+Codelens will help us to further understand the way range works. In this case, the variable ``i`` will take on values
+produced by the ``range`` function.
+
+.. codelens:: rangeme
+
+ for i in range(10):
+ print(i)
+
+
+
+Finally, suppose we want to actually count down from 10 to 1.
+How would we do that? Easy, we add another parameter, a step,
+that tells range what to count by. For our purposes, we want to start at 10
+and count down by 1 each time. So if we wanted 10 numbers counting down we would use
+``range(10,0,-1)``. The most general form of the range is
+``range(start, beyondLast, step)``. You can also create a sequence of numbers that
+skips some using a step size larger than 1 or smaller than -1.
+
+.. activecode:: ch03_6
+ :nocanvas:
+
+ print(list(range(0, 19, 2)))
+ print(list(range(0, 20, 2)))
+ print(list(range(10, 0, -1)))
+
+Try it in codelens. Do you see why the first two statements produce the same result?
+
+
+.. codelens:: rangeme2
+
+ for i in range(0, 20, 2):
+ print(i)
+
+**Check your understanding**
+
+.. mchoice:: test_question3_5_1
+ :practice: T
+ :answer_a: Range should generate a sequence that stops before 10 (including 9).
+ :answer_b: Range should generate a sequence that starts at 10 (including 10).
+ :answer_c: Range should generate a sequence starting at 3 that stops at 10 (including 10).
+ :answer_d: Range should generate a sequence using every 10th number between the start and the stopping number.
+ :correct: a
+ :feedback_a: Range will generate the sequence 3, 5, 7, 9.
+ :feedback_b: The first argument (3) tells range what number to start at.
+ :feedback_c: Range will always stop at the number in the sequence before (not including) the specified limit for the sequence.
+ :feedback_d: The third argument (2) tells range how many numbers to skip between each element in the sequence.
+
+ In the command range(3, 10, 2), what does the second argument (10) specify?
+
+.. mchoice:: test_question3_5_2
+ :practice: T
+ :answer_a: range(2, 5, 8)
+ :answer_b: range(2, 8, 3)
+ :answer_c: range(2, 10, 3)
+ :answer_d: range(8, 1, -3)
+ :correct: c
+ :feedback_a: This command generates the sequence with just the number 2 because the first parameter (2) tells range where to start, the second number tells range where to end (before 5) and the third number tells range how many numbers to skip between elements (8). Since 10 >= 5, there is only one number in this sequence.
+ :feedback_b: This command generates the sequence 2, 5 because 8 is not less than 8 (the specified number past the end).
+ :feedback_c: The first number is the starting point, the second is past the last allowed, and the third is the amount to increment by.
+ :feedback_d: This command generates the sequence 8, 5, 2 because it starts at 8, ends before 1, and skips to every third number going down.
+
+ What command correctly generates the sequence 2, 5, 8?
+
+.. mchoice:: test_question3_5_3
+ :practice: T
+ :answer_a: It will generate a sequence starting at 0, with every number included up to but not including the argument it was passed.
+ :answer_b: It will generate a sequence starting at 1, with every number up to but not including the argument it was passed.
+ :answer_c: It will generate a sequence starting at 1, with every number including the argument it was passed.
+ :answer_d: It will cause an error: range always takes exactly 3 arguments.
+ :correct: a
+ :feedback_a: Yes, if you only give one number to range it starts with 0 and ends before the number specified incrementing by 1.
+ :feedback_b: Range with one parameter starts at 0.
+ :feedback_c: Range with one parameter starts at 0, and never includes the argument it was passed.
+ :feedback_d: If range is passed only one argument, it interprets that argument as one past the end of the list.
+
+ What happens if you give range only one argument? For example: range(4)
+
+.. mchoice:: test_question3_5_4
+ :practice: T
+ :answer_a: range(5, 25, 5)
+ :answer_b: range(20, 3, -5)
+ :answer_c: range(20, 5, 4)
+ :answer_d: range(20, 5, -5)
+ :correct: b
+ :feedback_a: The step 5 is positive, while the given sequence is decreasing. This answer creates the reversed, increasing sequence.
+ :feedback_b: Yes: If we take steps of -5, not worrying about the ending, we get 20, 15, 10, 5, 0, .... The limit 3 is past the 5, so the range sequence stops with the 5.
+ :feedback_c: The step 5 is positive so the sequence would need to increase from 20 toward 4. That does not make sense and the sequence would be empty.
+ :feedback_d: the sequence can never include the second parameter (5). The second parameter must always be past the end of the range sequence.
+
+ Which range function call will produce the sequence 20, 15, 10, 5?
+
+
+.. mchoice:: test_question3_5_5
+ :practice: T
+ :answer_a: No other value would give the same sequence.
+ :answer_b: The only other choice is 14.
+ :answer_c: 11, 13, or 14
+ :correct: c
+ :feedback_a: The sequence produced has steps of 4: 2, 6, 10. The next would be 14, but it is not before the limit 12. There are other limit choices past 10, but not past 14.
+ :feedback_b: 14 would work: It is also past 10, and not past 14, but there are other integers with the same properties.
+ :feedback_c: Yes, any integer past 10, and not past the next step at 14 would work.
+
+ What could the second parameter (12) in range(2, 12, 4) be replaced with and generate exactly the same sequence?
diff --git a/_sources/MoreAboutIteration/ThewhileStatement.rst b/_sources/MoreAboutIteration/ThewhileStatement.rst
index 201fdfc99..e0f91cc24 100644
--- a/_sources/MoreAboutIteration/ThewhileStatement.rst
+++ b/_sources/MoreAboutIteration/ThewhileStatement.rst
@@ -20,75 +20,37 @@ The ``while`` Statement
:width: 560
:align: left
-There is another Python statement that can also be used to build an iteration. It is called the ``while`` statement.
-The ``while`` statement provides a much more general mechanism for iterating. Similar to the ``if`` statement, it uses
-a boolean expression to control the flow of execution. The body of while will be repeated as long as the controlling boolean expression evaluates to ``True``.
+A basic building block of all programs is to be able to repeat some code
+over and over again. In computer science, we refer to this repetitive idea as **iteration**. In this section, we will explore some mechanisms for basic iteration.
-The following figure shows the flow of control.
-
-.. image:: Figures/while_flow.png
-
-We can use the ``while`` loop to create any type of iteration we wish, including anything that we have previously done with a ``for`` loop. For example, the program in the previous section could be rewritten using ``while``.
-Instead of relying on the ``range`` function to produce the numbers for our summation, we will need to produce them ourselves. To to this, we will create a variable called ``aNumber`` and initialize it to 1, the first number in the summation. Every iteration will add ``aNumber`` to the running total until all the values have been used.
-In order to control the iteration, we must create a boolean expression that evaluates to ``True`` as long as we want to keep adding values to our running total. In this case, as long as ``aNumber`` is less than or equal to the bound, we should keep going.
-
-
-
-Here is a new version of the summation program that uses a while statement.
+Let's look at our first Python statement that can be used to build an iteration. It is called the ``while`` statement. When used with other code it can be used to
+repeat code in a **while loop**. Similar to the ``if`` statement, it uses
+a boolean expression to control the flow of execution. The body of while (code indented one space in) will be repeated as long as the controlling boolean
+expression evaluates to ``True``.
+Here is a simple example that counts down from 10 to 0.
.. activecode:: ch07_while1
- def sumTo(aBound):
- """ Return the sum of 1+2+3 ... n """
-
- theSum = 0
- aNumber = 1
- while aNumber <= aBound:
- theSum = theSum + aNumber
- aNumber = aNumber + 1
- return theSum
-
- print(sumTo(4))
-
- print(sumTo(1000))
-
-
-
-You can almost read the ``while`` statement as if it were in natural language. It means,
-while ``aNumber`` is less than or equal to ``aBound``, continue executing the body of the loop. Within
-the body, each time, update ``theSum`` using the accumulator pattern and increment ``aNumber``. After the body of the loop, we go back up to the condition of the ``while`` and reevaluate it. When ``aNumber`` becomes greater than ``aBound``, the condition fails and flow of control continues to the ``return`` statement.
-
-The same program in codelens will allow you to observe the flow of execution.
-
-.. codelens:: ch07_while2
-
- def sumTo(aBound):
- """ Return the sum of 1+2+3 ... n """
-
- theSum = 0
- aNumber = 1
- while aNumber <= aBound:
- theSum = theSum + aNumber
- aNumber = aNumber + 1
- return theSum
-
- print(sumTo(4))
-
-
-
-More formally, here is the flow of execution for a ``while`` statement:
-
-#. Evaluate the condition, yielding ``False`` or ``True``.
-#. If the condition is ``False``, exit the ``while`` statement and continue
- execution at the next statement.
-#. If the condition is ``True``, execute each of the statements in the body and
- then go back to step 1.
-
-The body consists of all of the statements below the header with the same
-indentation.
-
-This type of flow is called a **loop** because the third step loops back around
-to the top. Notice that if the condition is ``False`` the first time through the
+ count = 10
+ while count > 0:
+ print(count)
+ count = count - 1
+ print("Blastoff!")
+
+* **count** is a normal variable here, but since it is governing the ``while`` loop it is also called the **loop variable**.
+* Line 2 here is the *loop condition**. It must always be a boolean expression that will evaluate to ``False`` or ``True``.
+* Lines 3 and 4 are the **loop body**. The loop body is always
+ indented. The indentation determines exactly what statements are "in the
+ loop". The loop body is run each time the loop is repeated.
+* On each *iteration* or *pass* of the loop, a check is done to see if
+ the loop condition is True (if ``count`` is greater than zero). If it is not (this is
+ called the **terminating condition** of the loop), the loop has finished.
+ Program execution continues at the next statement after the loop body.
+* If ``count`` is greater than zero, the loop body is executed again.
+* At the end of each execution of the body of the loop, Python returns
+ to the ``while`` statement, to see if the loop should repeat.
+
+Notice that if the condition is ``False`` the first time through the
loop, the statements inside the loop are never executed.
.. warning::
@@ -102,51 +64,63 @@ loop, the statements inside the loop are never executed.
The body of the loop should change the value of one or more variables so that
eventually the condition becomes ``False`` and the loop terminates. Otherwise the
loop will repeat forever. This is called an **infinite loop**.
-An endless
-source of amusement for computer scientists is the observation that the
+An endless source of amusement for computer scientists is the observation that the
directions written on the back of the shampoo bottle (lather, rinse, repeat) create an infinite loop.
-In the case shown above, we can prove that the loop terminates because we
-know that the value of ``aBound`` is finite, and we can see that the value of ``aNumber``
-increments each time through the loop, so eventually it will have to exceed ``aBound``. In
-other cases, it is not so easy to tell.
+We can use the ``while`` loop to create any type of iteration we wish, making more general-purpose than the ``for`` loop we'll learn next week.
+For example, let us consider a program that adds all numbers from ``1`` to ``n``. To do this, we will create a variable called ``aNumber`` and initialize it to
+1, the first number in the summation. Every iteration will add ``aNumber`` to the running total until all the values have been used.
+In order to control the iteration, we must create a boolean expression that evaluates to ``True`` as long as we want to keep adding values to our
+running total. In this case, as long as ``aNumber`` is less than or equal to the bound, we should keep going.
-.. note::
+Here is the summation program that uses a while statement.
- Introduction of the while statement causes us to think about the types of iteration we have seen. The ``for`` statement will always iterate through a sequence of values like the list of names for the party or the list of numbers created by ``range``. Since we know that it will iterate once for each value in the collection, it is often said that a ``for`` loop creates a
- **definite iteration** because we definitely know how many times we are going to iterate. On the other
- hand, the ``while`` statement is dependent on a condition that needs to evaluate to ``False`` in order
- for the loop to terminate. Since we do not necessarily know when this will happen, it creates what we
- call **indefinite iteration**. Indefinite iteration simply means that we don't know how many times we will repeat but eventually the condition controlling the iteration will fail and the iteration will stop. (Unless we have an infinite loop which is of course a problem.)
+.. activecode:: ch07_while2
-What you will notice here is that the ``while`` loop is more work for
-you --- the programmer --- than the equivalent ``for`` loop. When using a ``while``
-loop you have to control the loop variable yourself. You give it an initial value, test
-for completion, and then make sure you change something in the body so that the loop
-terminates.
+ """ Return the sum of 1+2+3 ... n """
+
+ aBound = int(input("Please give a number n: "))
+ theSum = 0
+ aNumber = 1
+ while aNumber <= aBound:
+ theSum = theSum + aNumber
+ aNumber = aNumber + 1
+ print(theSum)
-So why have two kinds of loop if ``for`` looks easier? The next section, :ref:`randomly-walking-turtles`, shows an indefinite iteration where
-we need the extra power that we get from the ``while`` loop.
-.. note::
+You can almost read the ``while`` statement as if it were in natural language. It means,
+while ``aNumber`` is less than or equal to ``aBound``, continue executing the body of the loop. Within
+the body, each time, update ``theSum`` and increment ``aNumber``. After the body of the loop, we go
+back up to the condition of the ``while`` and reevaluate it. When ``aNumber`` becomes greater
+than ``aBound``, the condition fails and flow of control continues to the ``print`` statement.
- This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
+The same program in codelens will allow you to observe the flow of execution.
- .. activecode:: scratch_07_01
+.. codelens:: ch07_while3
+ """ Return the sum of 1+2+3 ... n """
+
+ aBound = int(input("Please give a number n: "))
+ theSum = 0
+ aNumber = 1
+ while aNumber <= aBound:
+ theSum = theSum + aNumber
+ aNumber = aNumber + 1
+ print(theSum)
-**Check your understanding**
-.. mchoice:: test_question7_2_1
- :practice: T
- :answer_a: True
- :answer_b: False
- :correct: a
- :feedback_a: Although the while loop uses a different syntax, it is just as powerful as a for-loop and often more flexible.
- :feedback_b: Often a for-loop is more natural and convenient for a task, but that same task can always be expressed using a while loop.
- True or False: You can rewrite any for-loop as a while-loop.
+In the case shown above, we can prove that the loop terminates because we
+know that the value of ``aBound`` is finite, and we can see that the value of ``aNumber``
+increments each time through the loop, so eventually it will have to exceed ``aBound``. In
+other cases, it is not so easy to tell.
+
+.. note::
+
+ This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
+
+ .. activecode:: scratch_07_01
.. mchoice:: test_question7_2_2
:practice: T
diff --git a/_sources/MoreAboutIteration/intro-IterationRevisited.rst b/_sources/MoreAboutIteration/intro-IterationRevisited.rst
index fac46c62c..e1e91716a 100644
--- a/_sources/MoreAboutIteration/intro-IterationRevisited.rst
+++ b/_sources/MoreAboutIteration/intro-IterationRevisited.rst
@@ -11,7 +11,7 @@
:prefix: iter-1-
:start: 1
-Iteration Revisited
+Iteration
===================
.. index:: iteration, assignment, assignment statement, reassignment
@@ -26,10 +26,8 @@ people do poorly.
Repeated execution of a sequence of statements is called **iteration**. Because
iteration is so common, Python provides several language features to make it
-easier. We've already seen the ``for`` statement in a previous chapter. This is a very common
-form of iteration in Python. In this chapter
-we are going to look at the ``while`` statement --- another way to have your
-program do iteration.
+easier. In this chapter we are going to look at two common forms of iteration: the ``while`` statement
+and the ``for`` statement.
.. index:: for loop
diff --git a/_sources/MoreAboutIteration/toctree.rst b/_sources/MoreAboutIteration/toctree.rst
index 6b944d8ff..6e1842939 100644
--- a/_sources/MoreAboutIteration/toctree.rst
+++ b/_sources/MoreAboutIteration/toctree.rst
@@ -1,18 +1,21 @@
-More About Iteration
+Iteration
::::::::::::::::::::
.. toctree::
- :caption: More About Iteration
+ :caption: Iteration
:maxdepth: 2
- intro-IterationRevisited.rst
- Theforlooprevisited.rst
+ intro-Iteration.rst
ThewhileStatement.rst
- RandomlyWalkingTurtles.rst
+ FlowofExecutionofthewhileLoop.rst
The3n1Sequence.rst
+ SentinelValuesAndValidation.rst
+
+ TheforLoop.rst
+ TherangeFunction.rst
NewtonsMethod.rst
accumulatorRevisited.rst
- SentinelValuesAndValidation.rst
+
AlgorithmsRevisited.rst
SimpleTables.rst
2DimensionalIterationImageProcessing.rst
diff --git a/_sources/Selection/ConditionalExecutionBinarySelection.rst b/_sources/Selection/ConditionalExecutionBinarySelection.rst
index 76ab28dcc..20ac98a18 100644
--- a/_sources/Selection/ConditionalExecutionBinarySelection.rst
+++ b/_sources/Selection/ConditionalExecutionBinarySelection.rst
@@ -56,14 +56,22 @@ indented under the ``else`` clause get executed.
.. image:: Figures/flowchart_if_else.png
-
-
-As with the function definition from the last chapter and other compound
-statements like ``for``, the ``if`` statement consists of a header line and a body. The header
+As a program executes, the interpreter always keeps track of which statement is
+about to be executed. We call this the **control flow**, or the **flow of
+execution** of the program. When humans execute programs, they often use their
+finger to point to each statement in turn. So you could think of control flow
+as "Python's moving finger".
+
+Control flow until now has been strictly top to bottom, one statement at a
+time. We call this type of control **sequential**. In Python flow is sequential as long as
+successive statements are indented the *same* amount. The ``if`` statement
+introduces indented sub-statements after the if heading.
+
+Each ``if`` statement consists of a header line and a body. The header
line begins with the keyword ``if`` followed by a *boolean expression* and ends with
a colon (:).
-The more indented statements that follow are called a **block**.
+The more indented statements that follow are called a **block** or sometimes a **body**.
Each of the statements inside the first block of statements is executed in order if the boolean
expression evaluates to ``True``. The entire first block of statements
From 139401f3e81d44564f187d8147e1b8383c31010e Mon Sep 17 00:00:00 2001
From: robotuw
Date: Mon, 20 Feb 2023 16:01:11 -0700
Subject: [PATCH 12/90] Weeks 7 and 8 Update
Another set of reordering and content changes for class weeks seven and eight specifically. Concerns mostly functions and modules chapters.
---
.error_schema.log | 2 +
.gitignore-20230129-131712 | 91 +++++++++
.../Functionscancallotherfunctions.rst | 95 ----------
.../Functions/Functionsthatreturnvalues.rst | 23 +--
_sources/Functions/functions.rst | 179 ++++++------------
_sources/Functions/mainfunction.rst | 68 +++----
_sources/Functions/toctree.rst | 3 +-
_sources/Lists/toctree.rst | 3 +-
.../FlowofExecutionofthewhileLoop.rst | 27 +--
_sources/MoreAboutIteration/NewtonsMethod.rst | 40 ++--
.../SentinelValuesAndValidation.rst | 14 +-
.../MoreAboutIteration/The3n1Sequence.rst | 20 +-
_sources/MoreAboutIteration/TheforLoop.rst | 19 +-
.../MoreAboutIteration/ThewhileStatement.rst | 21 +-
_sources/PythonModules/CreatingModules.rst | 6 +-
.../PythonModules/MoreAboutUsingModules.rst | 16 +-
_sources/PythonModules/modules.rst | 28 ++-
_sources/PythonModules/toctree.rst | 1 -
_sources/Strings/toctree.rst | 5 +-
_sources/index.rst | 4 +-
cli.log | 7 +
project-20230129-131712.ptx | 51 +++++
publication/publication.ptx | 7 +
requirements-20230129-131712.txt | 1 +
24 files changed, 337 insertions(+), 394 deletions(-)
create mode 100644 .error_schema.log
create mode 100644 .gitignore-20230129-131712
create mode 100644 cli.log
create mode 100644 project-20230129-131712.ptx
create mode 100644 publication/publication.ptx
create mode 100644 requirements-20230129-131712.txt
diff --git a/.error_schema.log b/.error_schema.log
new file mode 100644
index 000000000..2a12b54b8
--- /dev/null
+++ b/.error_schema.log
@@ -0,0 +1,2 @@
+file:/C:/Users/Rob/Documents/GitHub/thinkcspy/pretext/thinkcspy.ptx:3:0:ERROR:RELAXNGV:RELAXNG_ERR_ELEMWRONG: Did not expect element include there
+file:/C:/Users/Rob/Documents/GitHub/thinkcspy/pretext/thinkcspy.ptx:3:0:ERROR:RELAXNGV:RELAXNG_ERR_EXTRACONTENT: Element pretext has extra content: include
\ No newline at end of file
diff --git a/.gitignore-20230129-131712 b/.gitignore-20230129-131712
new file mode 100644
index 000000000..ed41bfbfe
--- /dev/null
+++ b/.gitignore-20230129-131712
@@ -0,0 +1,91 @@
+# Boilerplate list of files in a PreTeXt project for git to ignore
+# ensure this file is tracked
+!.gitignore
+
+# don't track unpublished builds
+output
+
+# don't track assets generated from source
+generated-assets
+
+# don't track node packages
+node_modules
+
+# don't track error logs
+.error_schema.log
+cli.log
+
+# don't track OS related files (windows/macos/linux)
+.DS_Store
+.DS_Store?
+._*
+.AppleDouble
+.LSOverride
+.Spotlight-V100
+.Trashes
+Icon
+.AppleDB
+.AppleDesktop
+Network Trash Folder
+Temporary Items
+.apdisk
+Thumbs.db
+Thumbs.db:encryptable
+ehthumbs.db
+ehthumbs_vista.db
+*.stackdump
+*.lnk
+*.cab
+*.msi
+*.msix
+*.msm
+*.msp
+[Dd]esktop.ini
+.directory
+.fuse_hidden*
+.Trash-*
+.nfs*
+
+# Don't include VSCode generated files
+.vscode
+*.code-workspace
+
+# Don't inlucde SublimeText files
+# Cache files for Sublime Text
+*.tmlanguage.cache
+*.tmPreferences.cache
+*.stTheme.cache
+
+# Workspace files are user-specific
+*.sublime-workspace
+
+# Project files should be checked into the repository, unless a significant
+# proportion of contributors will probably not be using Sublime Text
+*.sublime-project
+
+# SFTP configuration file
+sftp-config.json
+sftp-config-alt*.json
+
+# Package control specific files
+Package Control.last-run
+Package Control.ca-list
+Package Control.ca-bundle
+Package Control.system-ca-bundle
+Package Control.cache/
+Package Control.ca-certs/
+Package Control.merged-ca-bundle
+Package Control.user-ca-bundle
+oscrypto-ca-bundle.crt
+bh_unicode_properties.cache
+
+# Sublime-github package stores a github token in this file
+# https://packagecontrol.io/packages/sublime-github
+GitHub.sublime-settings
+
+
+# Don't include Dropbox settings and caches
+.dropbox
+.dropbox.attr
+.dropbox.cache
+
diff --git a/_sources/Functions/Functionscancallotherfunctions.rst b/_sources/Functions/Functionscancallotherfunctions.rst
index 726f70981..28062ce48 100644
--- a/_sources/Functions/Functionscancallotherfunctions.rst
+++ b/_sources/Functions/Functionscancallotherfunctions.rst
@@ -62,94 +62,6 @@ for ``sum_of_squares``. As you step through you will notice that ``x``, and ``y
different values. This illustrates that even though they are named the same,
they are in fact, very different.
-Now we will look at another example that uses two functions. This example illustrates an
-important computer science problem solving technique called
-**generalization**. Assume we want to write a
-function to draw a square. The generalization step is to realize that a
-square is just a special kind of rectangle.
-
-To draw a rectangle we need to be able to call a function with different
-arguments for width and height. Unlike the case of the square,
-we cannot repeat the same thing 4 times, because the four sides are not equal.
-However, it is the case that drawing the bottom and right sides are the
-same sequence as drawing the top and left sides. So we eventually come up with
-this rather nice code that can draw a rectangle.
-
-.. code-block:: python
-
- def drawRectangle(t, w, h):
- """Get turtle t to draw a rectangle of width w and height h."""
- for i in range(2):
- t.forward(w)
- t.left(90)
- t.forward(h)
- t.left(90)
-
-The parameter names are chosen as single letters for conciseness.
-In real programs, we will insist on better variable names than this.
-The point is that the program doesn't "understand" that you're drawing a rectangle or that the
-parameters represent the width and the height. Concepts like rectangle, width, and height are meaningful
-for humans. They are not concepts that the program or the computer understands.
-
-*Thinking like a computer scientist* involves looking for patterns and
-relationships. In the code above, we've done that to some extent. We did
-not just draw four sides. Instead, we spotted that we could draw the
-rectangle as two halves and used a loop to repeat that pattern twice.
-
-But now we might spot that a square is a special kind of rectangle. A square
-simply uses the same value for both the height and the width.
-We already have a function that draws a rectangle, so we can use that to draw
-our square.
-
-.. code-block:: python
-
- def drawSquare(tx, sz): # a new version of drawSquare
- drawRectangle(tx, sz, sz)
-
-Here is the entire example with the necessary set up code.
-
-.. activecode:: ch04_3
- :nocodelens:
-
- import turtle
-
- def drawRectangle(t, w, h):
- """Get turtle t to draw a rectangle of width w and height h."""
- for i in range(2):
- t.forward(w)
- t.left(90)
- t.forward(h)
- t.left(90)
-
- def drawSquare(tx, sz): # a new version of drawSquare
- drawRectangle(tx, sz, sz)
-
- wn = turtle.Screen() # Set up the window
- wn.bgcolor("lightgreen")
-
- tess = turtle.Turtle() # create tess
-
- drawSquare(tess, 50)
-
- wn.exitonclick()
-
-
-
-There are some points worth noting here:
-
-* Functions can call other functions.
-* Rewriting ``drawSquare`` like this captures the relationship
- that we've spotted.
-* A caller of this function might say ``drawSquare(tess, 50)``. The parameters
- of this function, ``tx`` and ``sz``, are assigned the values of the tess object, and
- the integer 50 respectively.
-* In the body of the function, ``tz`` and ``sz`` are just like any other variable.
-* When the call is made to ``drawRectangle``, the values in variables ``tx`` and ``sz``
- are fetched first, then the call happens. So as we enter the top of
- function ``drawRectangle``, its variable ``t`` is assigned the tess object, and ``w`` and
- ``h`` in that function are both given the value 50.
-
-
So far, it may not be clear why it is worth the trouble to create all of these
new functions. Actually, there are a lot of reasons, but this example
demonstrates two:
@@ -163,10 +75,3 @@ demonstrates two:
#. Sometimes you can write functions that allow you to solve a specific
problem using a more general solution.
-
-.. admonition:: Lab
-
- * `Drawing a Circle <../Labs/lab04_01.html>`_ In this guided lab exercise we will work
- through a simple problem solving exercise related to drawing a circle with the turtle.
-
-
diff --git a/_sources/Functions/Functionsthatreturnvalues.rst b/_sources/Functions/Functionsthatreturnvalues.rst
index 51a0fa55c..cae049591 100644
--- a/_sources/Functions/Functionsthatreturnvalues.rst
+++ b/_sources/Functions/Functionsthatreturnvalues.rst
@@ -32,9 +32,7 @@ the absolute value:
In this example, the arguments to the ``abs`` function are 5 and -5.
-Some functions take more than one argument. For example the math module contains a function
-called
-``pow`` which takes two arguments, the base and the exponent.
+Some functions take more than one argument. For example the range function that we saw with ``for`` loops.
.. Inside the function,
.. the values that are passed get assigned to variables called **parameters**.
@@ -42,14 +40,9 @@ called
.. activecode:: ch04_5
:nocanvas:
- import math
- print(math.pow(2, 3))
+ print(list(range(4, 8)))
- print(math.pow(7, 4))
-
-.. note::
-
- Of course, we have already seen that raising a base to an exponent can be done with the ** operator.
+ print(list(range(1, 10)))
Another built-in function that takes more than one argument is ``max``.
@@ -65,17 +58,17 @@ return the maximum value sent. The arguments can be either simple values or
expressions. In the last example, 503 is returned, since it is larger than 33,
125, and 1. Note that ``max`` also works on lists of values.
-Furthermore, functions like ``range``, ``int``, ``abs`` all return values that
+Furthermore, functions like ``int``, ``abs`` all return values that
can be used to build more complex expressions.
.. index:: fruitful function
variable; global
global variable
-So an important difference between these functions and one like ``drawSquare`` is that
-``drawSquare`` was not executed because we wanted it to compute a value --- on the contrary,
-we wrote ``drawSquare`` because we wanted it to execute a sequence of steps that caused
-the turtle to draw a specific shape.
+So an important difference between these functions and one like ``printRange`` is that
+``printRange`` was not executed because we wanted it to compute a value --- on the contrary,
+we wrote ``printRange`` because we wanted it to execute a sequence of steps that caused
+the list's range to print.
Functions that return values are sometimes called **fruitful functions**.
In many other languages, a chunk that doesn't return a value is called a **procedure**,
diff --git a/_sources/Functions/functions.rst b/_sources/Functions/functions.rst
index 1d1380e0b..879251e0c 100644
--- a/_sources/Functions/functions.rst
+++ b/_sources/Functions/functions.rst
@@ -55,7 +55,7 @@ pattern:
indented the same amount -- *4 spaces is the Python standard* -- from
the header line.
-We've already seen the ``for`` loop which follows this pattern.
+We've already seen the ``while`` and ``for`` loops which follow this pattern.
In a function definition, the keyword in the header is ``def``, which is
followed by the name of the function and some *parameters* enclosed in
@@ -72,37 +72,27 @@ The figure below shows this relationship. A function needs certain information
This type of diagram is often called a **black-box diagram** because it only states the requirements from the perspective of the user. The user must know the name of the function and what arguments need to be passed. The details of how the function works are hidden inside the "black-box".
-Suppose we're working with turtles and a common operation we need is to draw
-squares. It would make sense if we did not have to duplicate all the steps each time we want to make a square. "Draw a square" can be thought of as an *abstraction* of a number of smaller steps. We will need to provide two pieces of information for the function to do its work: a turtle to do the drawing and a size for the side of the square. We could represent this using the following black-box diagram.
-
-.. image:: Figures/turtleproc.png
+Suppose we're working with lists of numeric data and a common operation we need is to find the size of the range of numbers in a list.
+It would make sense if we did not have to duplicate all the steps each time we want to find the size of the range. "printRange" can be thought of as an
+*abstraction* of a number of smaller steps. We will need to provide one piece of information for the function to do its work: the list we need the range of.
Here is a program containing a function to capture this idea. Give it a try.
.. activecode:: ch04_1
:nocodelens:
- import turtle
-
- def drawSquare(t, sz):
- """Make turtle t draw a square of with side sz."""
-
- for i in range(4):
- t.forward(sz)
- t.left(90)
-
-
- wn = turtle.Screen() # Set up the window and its attributes
- wn.bgcolor("lightgreen")
+ def printRange(lst):
+ """Prints the size of the range of lst."""
+ smallest = min(lst)
+ largest = max(lst)
+ print(largest - smallest)
- alex = turtle.Turtle() # create alex
- drawSquare(alex, 50) # Call the function to draw the square passing the actual turtle and the actual side size
- wn.exitonclick()
+ my_list1 = [1, 2, 3, 4, 5, 6]
+ printRange(my_list1)
-This function is named ``drawSquare``. It has two parameters --- one to tell
-the function which turtle to move around and the other to tell it the size
-of the square we want drawn. In the function definition they are called ``t`` and ``sz`` respectively. Make sure you know where the body of the function
+This function is named ``printRange``. It has one parameter --- a variable storing a list of numbers. In the function definition this parameter is called
+``lst``. Make sure you know where the body of the function
ends --- it depends on the indentation and the blank lines don't count for
this purpose!
@@ -129,9 +119,8 @@ Defining a new function does not make the function run. To do that we need a
``print``, ``range`` and ``int``. Function calls contain the name of the function to be
executed followed by a list of values in parentheses, called *arguments*, which are assigned
to the parameters in the function definition.
-So in the second to the last line of
-the program, we call the function, and pass ``alex`` as the turtle to be manipulated,
-and 50 as the size of the square we want.
+So in the last line of
+the program, we call the function, and pass ``my_list1`` as the list to be analyzed.
.. The parameters being sent to the function, sometimes referred to as the **actual parameters** or **arguments**,
.. represent the specific data items that the function will use when it is executing.
@@ -142,67 +131,24 @@ and 50 as the size of the square we want.
Once we've defined a function, we can call it as often as we like and its
statements will be executed each time we call it. In this case, we could use it to get
-one of our turtles to draw a square and then we can move the turtle and have it draw a different square in a
-different location. Note that we lift the tail so that when ``alex`` moves there is no trace. We put the tail
-back down before drawing the next square. Make sure you can identify both invocations of the ``drawSquare`` function.
-
-.. activecode:: ch04_1a
- :nocodelens:
-
- import turtle
-
- def drawSquare(t, sz):
- """Make turtle t draw a square of with side sz."""
-
- for i in range(4):
- t.forward(sz)
- t.left(90)
+the size of the range of multiple lists. Make sure you can identify all three invocations of the ``printRange`` function.
-
- wn = turtle.Screen() # Set up the window and its attributes
- wn.bgcolor("lightgreen")
-
- alex = turtle.Turtle() # create alex
- drawSquare(alex, 50) # Call the function to draw the square
-
- alex.penup()
- alex.goto(100,100)
- alex.pendown()
-
- drawSquare(alex,75) # Draw another square
-
- wn.exitonclick()
-
-In the next example, we've changed the ``drawSquare``
-function a little and we get ``tess`` to draw 15 squares with some variations. Once the function has
-been defined, we can call it as many times as we like with whatever actual parameters we like.
-
-.. activecode:: ch04_2
+.. activecode:: ch04_1
:nocodelens:
- import turtle
-
- def drawMulticolorSquare(t, sz):
- """Make turtle t draw a multi-colour square of sz."""
- for i in ['red','purple','hotpink','blue']:
- t.color(i)
- t.forward(sz)
- t.left(90)
-
- wn = turtle.Screen() # Set up the window and its attributes
- wn.bgcolor("lightgreen")
+ def printRange(lst):
+ """Prints the size of the range of lst."""
+ smallest = min(lst)
+ largest = max(lst)
+ print(largest - smallest)
- tess = turtle.Turtle() # create tess and set some attributes
- tess.pensize(3)
- size = 20 # size of the smallest square
- for i in range(15):
- drawMulticolorSquare(tess, size)
- size = size + 10 # increase the size for next time
- tess.forward(10) # move tess along a little
- tess.right(18) # and give her some extra turn
+ my_list1 = [1, 2, 3, 4, 5, 6]
+ my_list2 = [2, 6, 9, 16, 42, 100, 2, 5]
+ printRange(my_list1)
+ printRange(my_list2)
+ printRange([5, 10, 1000, 2])
- wn.exitonclick()
.. warning::
@@ -210,8 +156,8 @@ been defined, we can call it as many times as we like with whatever actual param
the parentheses ``( )`` after the function name are *required*. This
can lead to a difficult bug: A function name without the
parenthesis is a legal expression *referring* to the function; for example,
- ``print`` and ``alex.penup``, but they do
- not *call* the associated functions.
+ ``print``, but it does
+ not *call* the associated function. Try it below if you want to see.
.. note::
@@ -267,10 +213,10 @@ been defined, we can call it as many times as we like with whatever actual param
.. mchoice:: test_question5_1_4
:practice: T
- :answer_a: def drawSquare(t, sz)
- :answer_b: drawSquare
- :answer_c: drawSquare(t, sz)
- :answer_d: Make turtle t draw a square with side sz.
+ :answer_a: def printSquare(size)
+ :answer_b: printSquare
+ :answer_c: printSquare(size)
+ :answer_d: Print a square of asterices with side size.
:correct: b
:feedback_a: This line is the complete function header (except for the semi-colon) which includes the name as well as several other components.
:feedback_b: Yes, the name of the function is given after the keyword def and before the list of parameters.
@@ -281,61 +227,58 @@ been defined, we can call it as many times as we like with whatever actual param
.. code-block:: python
- def drawSquare(t, sz):
- """Make turtle t draw a square of with side sz."""
- for i in range(4):
- t.forward(sz)
- t.left(90)
+ def printSquare(size):
+ """Print a square of asterices with side size."""
+ for i in range(size):
+ print("*"*size)
.. mchoice:: test_question5_1_5
:practice: T
:answer_a: i
- :answer_b: t
- :answer_c: t, sz
- :answer_d: t, sz, i
+ :answer_b: size, i
+ :answer_c: size
+ :answer_d: "*"*size
:correct: c
:feedback_a: i is a variable used inside of the function, but not a parameter, which is passed in to the function.
- :feedback_b: t is only one of the parameters to this function.
- :feedback_c: Yes, the function specifies two parameters: t and sz.
- :feedback_d: the parameters include only those variables whose values that the function expects to receive as input. They are specified in the header of the function.
+ :feedback_b: i is a variable used inside of the function, but not a parameter, which is passed in to the function.
+ :feedback_c: Yes, the function specifies one parameter: size.
+ :feedback_d: This is an argument provided to the call to print().
What are the parameters of the following function?
.. code-block:: python
- def drawSquare(t, sz):
- """Make turtle t draw a square of with side sz."""
- for i in range(4):
- t.forward(sz)
- t.left(90)
+ def printSquare(size):
+ """Print a square of asterices with side size."""
+ for i in range(size):
+ print("*"*size)
.. mchoice:: test_question5_1_6
:practice: T
- :answer_a: def drawSquare(t, sz)
- :answer_b: drawSquare
- :answer_c: drawSquare(10)
- :answer_d: drawSquare(alex, 10):
- :answer_e: drawSquare(alex, 10)
+ :answer_a: def printSquare(size)
+ :answer_b: printSquare
+ :answer_c: printSquare(10)
+ :answer_d: printSquare(my_size):
+ :answer_e: printSquare(size):
:correct: e
- :feedback_a: No, t and sz are the names of the formal parameters to this function. When the function is called, it requires actual values to be passed in.
+ :feedback_a: No, size is the name of the formal parameter to this function. When the function is called, it requires an actual value to be passed in.
:feedback_b: A function call always requires parentheses after the name of the function.
- :feedback_c: This function takes two parameters (arguments)
- :feedback_d: A colon is only required in a function definition. It will cause an error with a function call.
- :feedback_e: Since alex was already previously defined and 10 is a value, we have passed in two correct values for this function.
+ :feedback_c: Yes, this would work
+ :feedback_d: Yes, this would work since my_size is already defined.
+ :feedback_e: A colon is only required in a function definition. It will cause an error with a function call.
- Considering the function below, which of the following statements correctly invokes, or calls, this function (i.e., causes it to run)? Assume we already have a turtle named alex.
+ Considering the function below, which of the following statements correctly invokes, or calls, this function (i.e., causes it to run)? Assume we already have a variable named my_size.
.. code-block:: python
- def drawSquare(t, sz):
- """Make turtle t draw a square of with side sz."""
- for i in range(4):
- t.forward(sz)
- t.left(90)
+ def printSquare(size):
+ """Print a square of asterices with side size."""
+ for i in range(size):
+ print("*"*size)
diff --git a/_sources/Functions/mainfunction.rst b/_sources/Functions/mainfunction.rst
index addbdf8f0..9128bfabd 100644
--- a/_sources/Functions/mainfunction.rst
+++ b/_sources/Functions/mainfunction.rst
@@ -19,65 +19,54 @@ Using a Main Function
---------------------
Using functions is a good idea. It helps us to modularize our code by breaking a program
-into logical parts where each part is responsible for a specific task. For example, in one of our first programs there
-was a function called ``drawSquare`` that was responsible for having some turtle draw a square of some size.
-The actual turtle and the actual size of the square were defined to be provided as parameters. Here is that original program.
+into logical parts where each part is responsible for a specific task. For example, in one of our recent programs there
+was a function called ``square`` that was responsible for calculating the square of a number.
+After the function definition we defined a variable, called the function, and printed its results. Here is that original program.
.. code-block:: python
- import turtle
+ def square(x):
+ y = x * x
+ return y
- def drawSquare(t, sz):
- """Make turtle t draw a square of with side sz."""
+ toSquare = 10
+ squareResult = square(toSquare)
+ print("The result of", toSquare, "squared is", squareResult)
- for i in range(4):
- t.forward(sz)
- t.left(90)
+If you look closely at the structure of this program, we first define the function ``square``. At this point, we could have defined as many functions as were needed. Finally, there are five statements that set up the window, create the turtle, perform the function invocation, and wait for a user click to terminate the program.
- wn = turtle.Screen() # Set up the window and its attributes
- wn.bgcolor("lightgreen")
+The final three statements perform the main processing that the program will do. Notice that much of the detail has been pushed inside the ``square`` function.
+However, there are still these three lines of code that are needed to get things done.
- alex = turtle.Turtle() # create alex
- drawSquare(alex, 50) # Call the function to draw the square
-
- wn.exitonclick()
-
-
-If you look closely at the structure of this program, you will notice that we first perform all of our necessary ``import`` statements, in this case to be able to use the ``turtle`` module. Next, we define the function ``drawSquare``. At this point, we could have defined as many functions as were needed. Finally, there are five statements that set up the window, create the turtle, perform the function invocation, and wait for a user click to terminate the program.
-
-These final five statements perform the main processing that the program will do. Notice that much of the detail has been pushed inside the ``drawSquare`` function. However, there are still these five lines of code that are needed to get things done.
-
-In many programming languages (e.g. Java and C++), it is not possible to simply have statements sitting alone like this at the bottom of the program. They are required to be part of a special function that is automatically invoked by the operating system when the program is executed. This special function is called **main**. Although this is not required by the Python programming language, it is actually a good idea that we can incorporate into the logical structure of our program. In other words, these five lines are logically related to one another in that they provide the main tasks that the program will perform. Since functions are designed to allow us to break up a program into logical pieces, it makes sense to call this piece ``main``.
+In many programming languages (e.g. Java and C++), it is not possible to simply have statements sitting alone like this at the bottom of the program.
+They are required to be part of a special function that is automatically invoked by the operating system when the program is executed.
+This special function is called **main**. Although this is not required by the Python programming language, it is actually a good idea that we
+can incorporate into the logical structure of our program. In other words, these three lines are logically related to one another in that they provide the
+main tasks that the program will perform. Since functions are designed to allow us to break up a program into logical pieces, it makes sense to call this
+piece ``main``.
The following activecode shows this idea. In line 11 we have defined a new function called ``main`` that doesn't need any parameters. The five lines of main processing are now placed inside this function. Finally, in order to execute that main processing code, we need to invoke the ``main`` function (line 20). When you push run, you will see that the program works the same as it did before.
.. activecode:: ch04_1main
:nocodelens:
- import turtle
-
- def drawSquare(t, sz):
- """Make turtle t draw a square of with side sz."""
-
- for i in range(4):
- t.forward(sz)
- t.left(90)
+ def square(x):
+ y = x * x
+ return y
def main(): # Define the main function
- wn = turtle.Screen() # Set up the window and its attributes
- wn.bgcolor("lightgreen")
-
- alex = turtle.Turtle() # create alex
- drawSquare(alex, 50) # Call the function to draw the square
-
- wn.exitonclick()
+ toSquare = 10
+ squareResult = square(toSquare)
+ print("The result of", toSquare, "squared is", squareResult)
main() # Invoke the main function
-Now our program structure is as follows. First, import any modules that will be required. Second, define any functions that will be needed. Third, define a ``main`` function that will get the process started. And finally, invoke the main function (which will in turn call the other functions as needed).
+Now our program structure is as follows. First, import any modules that will be required (you'll read about those in the next chapter). Second, define any functions
+that will be needed. Third, define a ``main`` function that will get the process started. And finally, invoke the main function
+(which will in turn call the other functions as needed).
.. note::
@@ -110,6 +99,3 @@ The activecode below defines two simple functions and a main.
Line 12 uses an ``if`` statement to ask about the value of the ``__name__`` variable. If the value is ``"__main__"``, then the ``main`` function will be called. Otherwise, it can be assumed that the program is being imported into another program and we do not want to call ``main`` because that program will invoke the functions as needed. This ability to conditionally execute our main function can be extremely useful when we are writing code that will potentially be used by others. It allows us to include functionality that the user of the code will not need, most often as part of a testing process to be sure that the functions are working correctly.
-.. note::
-
- In order to conditionally execute the ``main`` function, we used a structure called an ``if`` statement to create what is known as selection. This topic will be studied in much more detail later.
diff --git a/_sources/Functions/toctree.rst b/_sources/Functions/toctree.rst
index 938d5bffc..d85f7f987 100644
--- a/_sources/Functions/toctree.rst
+++ b/_sources/Functions/toctree.rst
@@ -7,7 +7,6 @@ Functions
functions.rst
Functionsthatreturnvalues.rst
- UnitTesting.rst
Variablesandparametersarelocal.rst
TheAccumulatorPattern.rst
Functionscancallotherfunctions.rst
@@ -15,6 +14,6 @@ Functions
mainfunction.rst
ProgramDevelopment.rst
Composition.rst
- ATurtleBarChart.rst
+ UnitTesting.rst
Glossary.rst
Exercises.rst
diff --git a/_sources/Lists/toctree.rst b/_sources/Lists/toctree.rst
index ffd1c81fa..f0bf30178 100644
--- a/_sources/Lists/toctree.rst
+++ b/_sources/Lists/toctree.rst
@@ -17,11 +17,11 @@ Lists
StringsandLists.rst
AppendversusConcatenate.rst
ListMembership.rst
+ NestedLists.rst
ObjectsandReferences.rst
Aliasing.rst
CloningLists.rst
RepetitionandReferences.rst
- TheReturnofLSystems.rst
Listsandforloops.rst
TheAccumulatorPatternwithLists.rst
UsingListsasParameters.rst
@@ -29,7 +29,6 @@ Lists
WhichisBetter.rst
FunctionsthatProduceLists.rst
ListComprehensions.rst
- NestedLists.rst
listTypeConversionFunction.rst
TuplesandMutability.rst
TupleAssignment.rst
diff --git a/_sources/MoreAboutIteration/FlowofExecutionofthewhileLoop.rst b/_sources/MoreAboutIteration/FlowofExecutionofthewhileLoop.rst
index 1f8e38d99..a7b30d4af 100644
--- a/_sources/MoreAboutIteration/FlowofExecutionofthewhileLoop.rst
+++ b/_sources/MoreAboutIteration/FlowofExecutionofthewhileLoop.rst
@@ -16,21 +16,12 @@
Flow of Execution of the while Loop
----------------------------------
+-----------------------------------
-As a program executes, the interpreter always keeps track of which statement is
-about to be executed. We call this the **control flow**, or the **flow of
-execution** of the program. When humans execute programs, they often use their
-finger to point to each statement in turn. So you could think of control flow
-as "Python's moving finger".
+As before with ``if``, loops allow us as programmers to manipulate the control flow of a Python program.
+We can now possibly skip a portion of code, or choose to repeat it an indefinite number of times.
-Control flow until now has been strictly top to bottom, one statement at a
-time. We call this type of control **sequential**. In Python flow is sequential as long as
-successive statements are indented the *same* amount. The ``while`` statement
-introduces indented sub-statements after the while-loop heading.
-
-Flow of control is often easy to visualize and understand if we draw a flowchart.
-This flowchart shows the exact steps and logic of how the ``while`` statement executes.
+The flowchart below provides the general sequence of steps that govern execution of a while loop.
.. image:: Figures/while_flow.png
:width: 300px
@@ -43,10 +34,10 @@ the buttons. You can see the value of ``count`` change as the loop iterates thr
.. codelens:: vtest
- count = 10
- while count > 0:
- print(count)
- count = count - 1
- print("Blastoff!")
+count = 10
+while count > 0:
+ print(count)
+ count = count - 1
+print("Blastoff!")
diff --git a/_sources/MoreAboutIteration/NewtonsMethod.rst b/_sources/MoreAboutIteration/NewtonsMethod.rst
index ef7c8b4e4..fb99ac735 100644
--- a/_sources/MoreAboutIteration/NewtonsMethod.rst
+++ b/_sources/MoreAboutIteration/NewtonsMethod.rst
@@ -38,22 +38,22 @@ value whose square root will be approximated. The second is the number of times
calculation yielding a better result.
.. activecode:: chp07_newtonsdef
-
- def newtonSqrt(n, howmany):
- approx = 0.5 * n
- for i in range(howmany):
- betterapprox = 0.5 * (approx + n/approx)
- approx = betterapprox
- return betterapprox
-
- print(newtonSqrt(100, 10))
- print(newtonSqrt(4, 10))
- print(newtonSqrt(1, 10))
+
+ n = 100
+ howmany = 10
+
+ approx = 0.5 * n
+ for i in range(howmany):
+ betterapprox = 0.5 * (approx + n/approx)
+ approx = betterapprox
+ prin(betterapprox)
.. admonition:: Modify the program ...
- All three of the calls to ``newtonSqrt`` in the previous example produce the correct square root for the first parameter. However, were 10 iterations required to get the correct answer? Experiment with different values for the number of repetitions (the 10 on lines 8, 9, and 10). For each of these calls, find the **smallest** value for the number of repetitions that will produce the **correct** result.
+ The values used in the previous example produce the correct square root for 100. However, were 10 iterations required to get the correct answer?
+ Experiment with different values for the number of repetitions (howmany on line 2). Find the **smallest** value for the number of
+ repetitions that will produce the **correct** result.
Repeating more than the required number of times is a waste of computing resources. So definite iteration is not a good solution to this problem.
@@ -66,15 +66,13 @@ uses a ``while`` condition to execute until the approximation is no longer chang
.. codelens:: chp07_newtonswhile
- def newtonSqrt(n):
- approx = 0.5 * n
- better = 0.5 * (approx + n/approx)
- while better != approx:
- approx = better
- better = 0.5 * (approx + n/approx)
- return approx
-
- print(newtonSqrt(10))
+ n = 10
+ approx = 0.5 * n
+ better = 0.5 * (approx + n/approx)
+ while better != approx:
+ approx = better
+ better = 0.5 * (approx + n/approx)
+ print(approx)
.. note::
diff --git a/_sources/MoreAboutIteration/SentinelValuesAndValidation.rst b/_sources/MoreAboutIteration/SentinelValuesAndValidation.rst
index 67badd49b..8e22d4713 100644
--- a/_sources/MoreAboutIteration/SentinelValuesAndValidation.rst
+++ b/_sources/MoreAboutIteration/SentinelValuesAndValidation.rst
@@ -60,7 +60,7 @@ zero is a **sentinel value**, a value used to signal the end of the loop. Here's
.. activecode:: ch07_sentinel
:timelimit: 60000
-
+
total = 0
count = 0
moreItems = True
@@ -119,7 +119,7 @@ When you run the following code, try typing something other than Y or N to see h
.. activecode:: ch07_validation
:timelimit: 60000
-
+
valid_input = False
response = input('Do you like lima beans? Y)es or N)o: ')
while not valid_input:
@@ -128,8 +128,8 @@ When you run the following code, try typing something other than Y or N to see h
valid_input = True
else:
response = input('Please enter Y for yes or N for no. \n' + message)
-
- if response == 'Y':
- print('Great! They are very healthy.')
- else:
- print('Too bad. If cooked right, they are quite tasty.')
+
+ if response == 'Y':
+ print('Great! They are very healthy.')
+ else:
+ print('Too bad. If cooked right, they are quite tasty.')
diff --git a/_sources/MoreAboutIteration/The3n1Sequence.rst b/_sources/MoreAboutIteration/The3n1Sequence.rst
index 983638731..26ed77599 100644
--- a/_sources/MoreAboutIteration/The3n1Sequence.rst
+++ b/_sources/MoreAboutIteration/The3n1Sequence.rst
@@ -14,7 +14,7 @@
The 3n + 1 Sequence
-------------------
-As another example of indefinite iteration, let's look at a sequence that has fascinated mathematicians for many years.
+As another example of iteration with ``while``, let's look at a sequence that has fascinated mathematicians for many years.
The rule for creating the sequence is to start from
some positive integer, call it ``n``, and to generate
the next term of the sequence from ``n``, either by halving ``n``,
@@ -70,24 +70,6 @@ You'll notice that if you don't stop when you reach one, the sequence gets into
its own loop: 1, 4, 2, 1, 4, 2, 1, 4, and so on. One possibility is that there might
be other cycles that we just haven't found.
-.. admonition:: Choosing between ``for`` and ``while``
-
- Use a ``for`` loop if you know the maximum number of times that you'll
- need to execute the body. For example, if you're traversing a list of elements,
- or can formulate a suitable call to ``range``, then choose the ``for`` loop.
-
- So any problem like "iterate this weather model run for 1000 cycles", or "search this
- list of words", "check all integers up to 10000 to see which are prime" suggest that a ``for`` loop is best.
-
- By contrast, if you are required to repeat some computation until some condition is
- met, as we did in this 3n + 1 problem, you'll need a ``while`` loop.
-
- As we noted before, the first case is called **definite iteration** --- we have some definite bounds for
- what is needed. The latter case is called **indefinite iteration** --- we are not sure
- how many iterations we'll need --- we cannot even establish an upper bound!
-
-
-
.. There are also some great visualization tools becoming available to help you
.. trace and understand small fragments of Python code. The one we recommend is at
.. http://netserv.ict.ru.ac.za/python3_viz
diff --git a/_sources/MoreAboutIteration/TheforLoop.rst b/_sources/MoreAboutIteration/TheforLoop.rst
index 46e28602b..45366ce09 100644
--- a/_sources/MoreAboutIteration/TheforLoop.rst
+++ b/_sources/MoreAboutIteration/TheforLoop.rst
@@ -17,11 +17,6 @@
The ``for`` Loop
----------------
-.. youtube:: xGSfiZt5cdw
- :divid: forloopvid
- :height: 315
- :width: 560
- :align: left
The ``while`` statement is a general-purpose tool for iteration, and is necessary for any instance of iteration where we don't know how many repetitions will be needed.
However, if we do know how many are needed, there is a more efficient method: the ``for`` statement.
@@ -68,6 +63,18 @@ Take a look at the output produced when you press the ``run`` button. There is
call **indefinite iteration**. Indefinite iteration simply means that we don't know how many times we will repeat but eventually the condition
controlling the iteration will fail and the iteration will stop. (Unless we have an infinite loop which is of course a problem.)
+.. admonition:: Choosing between ``for`` and ``while``
+
+ Use a ``for`` loop if you know the maximum number of times that you'll
+ need to execute the body. For example, if you're traversing a list of elements,
+ or can formulate a suitable call to ``range``, then choose the ``for`` loop.
+
+ So any problem like "iterate this weather model run for 1000 cycles", or "search this
+ list of words", "check all integers up to 10000 to see which are prime" suggest that a ``for`` loop is best.
+
+ By contrast, if you are required to repeat some computation until some condition is
+ met, as we did in this 3n + 1 problem, you'll need a ``while`` loop.
+
What you will notice here is that the ``while`` loop is more work for
you --- the programmer --- than the equivalent ``for`` loop. When using a ``while``
loop you have to control the loop variable yourself. You give it an initial value, test
@@ -81,7 +88,7 @@ terminates.
:answer_a: True
:answer_b: False
:correct: a
- :feedback_a: Although the while loop uses a different syntax, it is just as powerful as a for-loop and often more flexible.
+ :feedback_a: The syntax for a for-loop can make it easier and more appealing, but a while loop is just as powerful as a for-loop and often more flexible.
:feedback_b: Often a for-loop is more natural and convenient for a task, but that same task can always be expressed using a while loop.
True or False: You can rewrite any for-loop as a while-loop.
diff --git a/_sources/MoreAboutIteration/ThewhileStatement.rst b/_sources/MoreAboutIteration/ThewhileStatement.rst
index e0f91cc24..c91b36f28 100644
--- a/_sources/MoreAboutIteration/ThewhileStatement.rst
+++ b/_sources/MoreAboutIteration/ThewhileStatement.rst
@@ -29,6 +29,7 @@ a boolean expression to control the flow of execution. The body of while (code
expression evaluates to ``True``.
Here is a simple example that counts down from 10 to 0.
+
.. activecode:: ch07_while1
count = 10
@@ -38,7 +39,7 @@ Here is a simple example that counts down from 10 to 0.
print("Blastoff!")
* **count** is a normal variable here, but since it is governing the ``while`` loop it is also called the **loop variable**.
-* Line 2 here is the *loop condition**. It must always be a boolean expression that will evaluate to ``False`` or ``True``.
+* Line 2 here is the **loop condition**. It must always be a boolean expression that will evaluate to ``False`` or ``True``.
* Lines 3 and 4 are the **loop body**. The loop body is always
indented. The indentation determines exactly what statements are "in the
loop". The loop body is run each time the loop is repeated.
@@ -78,7 +79,6 @@ Here is the summation program that uses a while statement.
.. activecode:: ch07_while2
""" Return the sum of 1+2+3 ... n """
-
aBound = int(input("Please give a number n: "))
theSum = 0
aNumber = 1
@@ -99,15 +99,14 @@ The same program in codelens will allow you to observe the flow of execution.
.. codelens:: ch07_while3
- """ Return the sum of 1+2+3 ... n """
-
- aBound = int(input("Please give a number n: "))
- theSum = 0
- aNumber = 1
- while aNumber <= aBound:
- theSum = theSum + aNumber
- aNumber = aNumber + 1
- print(theSum)
+""" Return the sum of 1+2+3 ... n """
+aBound = int(input("Please give a number n: "))
+theSum = 0
+aNumber = 1
+while aNumber <= aBound:
+ theSum = theSum + aNumber
+ aNumber = aNumber + 1
+print(theSum)
diff --git a/_sources/PythonModules/CreatingModules.rst b/_sources/PythonModules/CreatingModules.rst
index c704b5971..d425cf397 100644
--- a/_sources/PythonModules/CreatingModules.rst
+++ b/_sources/PythonModules/CreatingModules.rst
@@ -7,7 +7,7 @@
Creating Modules
----------------
-You've seen how to *use* modules like ``random``, ``math``, and ``turtle``, but how would you *create* a module?
+You've seen how to *use* modules like ``random`` and ``math``, but how would you *create* a module?
Every time you've written a Python script you've created a module!
@@ -120,10 +120,6 @@ Also - look at all the awesome comments in there!
It is important to include header comments in your module that explain what the module does.
-.. admonition:: Function Comments
-
- Functions are the next chapter, but the comments used here demonstrate a common Python documentation style.
-
Ok - so we've got a function in our module now, let's use it.
*coffee_customer.py*
diff --git a/_sources/PythonModules/MoreAboutUsingModules.rst b/_sources/PythonModules/MoreAboutUsingModules.rst
index 4e3076a14..5ea3269ff 100644
--- a/_sources/PythonModules/MoreAboutUsingModules.rst
+++ b/_sources/PythonModules/MoreAboutUsingModules.rst
@@ -20,18 +20,8 @@ like any other data in Python. Module objects simply contain other Python eleme
The first thing we need to do when we wish to use a module is perform an ``import``. In the example above, the statement
-``import turtle`` creates a new name, ``turtle``, and makes it refer to a `module object`. This looks very much like
+``import math`` creates a new name, ``math``, and makes it refer to a `module object`. This looks very much like
the reference diagrams we saw earlier for simple variables.
-
-.. image:: Figures/modreference.png
-
-In order to use something contained in a module, we use the `dot` notation, providing the module name and the specific item joined together with a "dot". For example, to use the ``Turtle`` class, we say ``turtle.Turtle``. You should read
-this as: "In the module turtle, access the Python element called Turtle".
-
-We will now turn our attention to a few other modules that you might find useful.
-
-.. youtube:: SGVgAV0v-Ww
- :height: 315
- :width: 560
- :align: left
+In order to use something contained in a module, we use the `dot` notation, providing the module name and the specific item joined together with a "dot". For example, to use the ``sqrt`` function, we say ``math.sqrt``. You should read
+this as: "In the module math, access the Python element called sqrt".
diff --git a/_sources/PythonModules/modules.rst b/_sources/PythonModules/modules.rst
index f17176f66..bbd090ff9 100644
--- a/_sources/PythonModules/modules.rst
+++ b/_sources/PythonModules/modules.rst
@@ -25,28 +25,26 @@ Modules and Getting Help
A **module** is a file containing Python definitions and statements intended
for use in other Python programs. There are many Python modules that come with
-Python as part of the **standard library**. We have already used one of these quite extensively,
-the ``turtle`` module. Recall that once we import the module, we can use things
+Python as part of the **standard library**. We have already used one of these briefly,
+the ``math`` module. Recall that once we import the module, we can use things
that are defined inside.
.. activecode:: chmod_01
:nocodelens:
- import turtle # allows us to use the turtles library
+ import math # allows us to use the math library
- wn = turtle.Screen() # creates a graphics window
- alex = turtle.Turtle() # create a turtle named alex
+ print(math.factorial(10)) # prints 10!
+ print(math.exp(4)) # prints e^4
- alex.forward(150) # tell alex to move forward by 150 units
- alex.left(90) # turn by 90 degrees
- alex.forward(75) # complete the second side of a rectangle
- wn.exitonclick()
+ print(math.log2(1024)) # prints log2(1024)
+ print(math.sqrt(100)) # prints the square root of 100
-Here we are using ``Screen`` and ``Turtle``, both of which are defined inside the turtle module.
+Here we are using ``factorial``, ``exp``, ``log2``, and ``sqrt``, all of which are defined inside the math module.
-But what if no one had told us about turtle? How would we know
+But what if no one had told us about math? How would we know
that it exists. How would we know what it can do for us? The answer is to ask for help and the best place to get
help about the Python programming environment is to consult with the Python Documentation.
@@ -66,13 +64,13 @@ and to use it often.
.. image:: Figures/pythondocmedium.png
If you have not done so already, take a look at the Global Module Index. Here you will see an alphabetical listing of all
-the modules that are available as part of the standard library. Find the turtle module.
+the modules that are available as part of the standard library. Find the math module.
.. image:: Figures/moduleindexmedium.png
-.. image:: Figures/turtlemodmedium.png
-You can see that all the turtle functionality that we have talked about is there. However, there is so much more. Take some time to read through and familiarize yourself with some of the other things that turtles can do.
+You can see that all the math functionality that we have talked about is there. However, there is so much more.
+Take some time to read through and familiarize yourself with some of the other things that math can do.
@@ -84,7 +82,7 @@ You can see that all the turtle functionality that we have talked about is there
activecode used here was strictly to help us learn. It is not the way we write production programs.
To that end, it is necessary to mention that many of the modules available in standard Python
- will **not** work in the activecode environment. In fact, only turtle, math, and random have been
+ will **not** work in the activecode environment. In fact, only math and random have been
completely ported at this point. If you wish to explore any
additional modules, you will need to also explore using a more robust development environment.
diff --git a/_sources/PythonModules/toctree.rst b/_sources/PythonModules/toctree.rst
index 246062f60..fc17267f9 100644
--- a/_sources/PythonModules/toctree.rst
+++ b/_sources/PythonModules/toctree.rst
@@ -7,7 +7,6 @@ Python Modules
modules.rst
MoreAboutUsingModules.rst
- Themathmodule.rst
Therandommodule.rst
CreatingModules.rst
Glossary.rst
diff --git a/_sources/Strings/toctree.rst b/_sources/Strings/toctree.rst
index 8614a42a8..b926c10ae 100644
--- a/_sources/Strings/toctree.rst
+++ b/_sources/Strings/toctree.rst
@@ -14,16 +14,15 @@ Strings
TheSliceOperator.rst
StringsareImmutable.rst
StringComparison.rst
+ Theinandnotinoperators.rst
TraversalandtheforLoopByItem.rst
TraversalandtheforLoopByIndex.rst
TraversalandthewhileLoop.rst
- Theinandnotinoperators.rst
TheAccumulatorPatternwithStrings.rst
- TurtlesandStringsandLSystems.rst
+ Characterclassification.rst
Loopingandcounting.rst
Afindfunction.rst
Optionalparameters.rst
- Characterclassification.rst
Summary.rst
Glossary.rst
Exercises.rst
diff --git a/_sources/index.rst b/_sources/index.rst
index 0ea5c8280..98fdd802b 100644
--- a/_sources/index.rst
+++ b/_sources/index.rst
@@ -59,9 +59,8 @@ Table of Contents
Selection/toctree.rst
Debugging/toctree.rst
MoreAboutIteration/toctree.rst
- PythonTurtle/toctree.rst
- PythonModules/toctree.rst
Functions/toctree.rst
+ PythonModules/toctree.rst
Files/toctree.rst
Exceptions/toctree.rst
IntroRecursion/toctree.rst
@@ -72,6 +71,7 @@ Table of Contents
Dictionaries/toctree.rst
WebApps/toctree.rst
GUIandEventDrivenProgramming/toctree.rst
+ PythonTurtle/toctree.rst
Labs
::::
diff --git a/cli.log b/cli.log
new file mode 100644
index 000000000..02e312d4d
--- /dev/null
+++ b/cli.log
@@ -0,0 +1,7 @@
+INFO : PreTeXt project found in `C:\Users\Rob\Documents\GitHub\thinkcspy`.
+WARNING : Project's CLI version could not be detected from `requirements.txt`.
+WARNING : Try `pretext init --refresh` to produce a compatible file.
+INFO :
+CRITICAL: There is not a target named "html" for this project.ptx manifest.
+INFO : However, the targets with names ['web', 'runestone', 'subset'] have "html" as their format. Try to view one of those instead or edit your project.ptx manifest.
+CRITICAL: Exiting.
diff --git a/project-20230129-131712.ptx b/project-20230129-131712.ptx
new file mode 100644
index 000000000..686cb6fa1
--- /dev/null
+++ b/project-20230129-131712.ptx
@@ -0,0 +1,51 @@
+
+
+
+
+
+
+ html
+ source/main.ptx
+ publication/publication.ptx
+ output/web
+
+
+ pdf
+ source/main.ptx
+ publication/publication.ptx
+ output/print
+
+
+ latex
+ source/main.ptx
+ publication/publication.ptx
+ output/print-latex
+
+
+ html
+ source/main.ptx
+ publication/publication.ptx
+ output/subset
+
+
+ ch_first
+
+
+
+ latex
+ pdflatex
+ xelatex
+ pdf2svg
+ asy
+ sage
+ convert
+ pdftops
+ node
+ file2brl
+
+
diff --git a/publication/publication.ptx b/publication/publication.ptx
new file mode 100644
index 000000000..35f128448
--- /dev/null
+++ b/publication/publication.ptx
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
diff --git a/requirements-20230129-131712.txt b/requirements-20230129-131712.txt
new file mode 100644
index 000000000..51ab65802
--- /dev/null
+++ b/requirements-20230129-131712.txt
@@ -0,0 +1 @@
+pretextbook == 0.8.3
\ No newline at end of file
From 9bbbd27ecd42f3c086e0e86cd0417f2a21870174 Mon Sep 17 00:00:00 2001
From: robotuw
Date: Tue, 21 Feb 2023 14:37:49 -0700
Subject: [PATCH 13/90] W10-W13 update
First update to the rest of the chapters, weeks 10-13.
---
.../ClassesBasics/Achangeofperspective.rst | 19 +++++--------------
.../AddingOtherMethodstoourClass.rst | 4 ++--
_sources/ClassesBasics/ObjectsRevisited.rst | 10 ++++------
.../ObjectsasArgumentsandParameters.rst | 9 ++-------
_sources/ClassesBasics/UserDefinedClasses.rst | 2 +-
_sources/Files/FindingaFileonyourDisk.rst | 6 +++---
_sources/Files/WithStatements.rst | 3 ---
_sources/Files/intro-WorkingwithDataFiles.rst | 4 +++-
_sources/IntroRecursion/toctree.rst | 2 --
_sources/index.rst | 2 +-
10 files changed, 21 insertions(+), 40 deletions(-)
diff --git a/_sources/ClassesBasics/Achangeofperspective.rst b/_sources/ClassesBasics/Achangeofperspective.rst
index f8e3aa12d..1e1b89d14 100644
--- a/_sources/ClassesBasics/Achangeofperspective.rst
+++ b/_sources/ClassesBasics/Achangeofperspective.rst
@@ -10,21 +10,12 @@
A change of perspective
-----------------------
-Throughout the earlier chapters, we wrote functions and called them using a syntax such as ``drawCircle(tess)``. This suggests that the
-function is the active agent. It says something like, *"Hey, drawCircle!
-Here's a turtle object for you to use to draw with."*
+Throughout the earlier chapters, we wrote functions and called them using a syntax such as ``printRange(lst)``. This suggests that the
+function is the active agent. It says something like, *"Hey, printRange!
+Here's a list for you to use to print with."*
-In object-oriented programming, the objects are considered the active agents.
-For example, in our early introduction to turtles, we used
-an object-oriented style. We said ``tess.forward(100)``, which
-asks the turtle to move itself forward by the given number of steps.
-An
-invocation like ``tess.circle()`` says *"Hey tess!
-Please use your circle method!"*
-
-
-
-This change in perspective is sometimes considered to be a more "polite" way to write programming instructions. However, it may not initially
+In object-oriented programming, the objects are considered the active agents. This change in perspective is sometimes considered to be a more "polite" way
+to write programming instructions. However, it may not initially
be obvious that it is useful. It turns out that often times shifting responsibility from
the functions onto the objects makes it possible to write more versatile
functions and makes it easier to maintain and reuse code.
diff --git a/_sources/ClassesBasics/AddingOtherMethodstoourClass.rst b/_sources/ClassesBasics/AddingOtherMethodstoourClass.rst
index 312dc3e7d..08973b292 100644
--- a/_sources/ClassesBasics/AddingOtherMethodstoourClass.rst
+++ b/_sources/ClassesBasics/AddingOtherMethodstoourClass.rst
@@ -20,8 +20,8 @@ We can group together the sensible operations, and the kinds of data
they apply to, and each instance of the class can have its own state.
A **method** behaves like a function but it is invoked on a specific
-instance. For example, with a turtle named ``tess``, ``tess.right(90)`` asks the ``tess`` object to perform its
-``right`` method and turn 90 degrees. Methods are accessed using dot notation.
+instance. For example, with a list named ``lst``, ``lst.append(90)`` asks the ``lst`` object to perform its
+``append`` method and add the integer 90 to the end of the list. Methods are accessed using dot notation.
Let's add two simple methods to allow a point to give us information about its state. The ``getX`` method, when invoked, will return the value of the x coordinate. The implementation of this method is straight forward since we already know how
to write functions that return values. One thing to notice is that even though the ``getX`` method does not need any other parameter information to do its work, there is still one formal parameter, ``self``. As we stated earlier, all methods defined in a class that operate on objects of that class will have ``self`` as their first parameter. Again, this serves as reference to the object itself which in turn gives access to the state data inside the object.
diff --git a/_sources/ClassesBasics/ObjectsRevisited.rst b/_sources/ClassesBasics/ObjectsRevisited.rst
index e1236bc4f..e0a5f95fb 100644
--- a/_sources/ClassesBasics/ObjectsRevisited.rst
+++ b/_sources/ClassesBasics/ObjectsRevisited.rst
@@ -12,13 +12,11 @@
Objects Revisited
-----------------
-In Python, every value is actually an object. Whether it be a turtle, a list, or even an integer, they are all objects. Programs manipulate those objects either by performing
+In Python, every value is actually an object. Whether it be a string, a list, or even an integer, they are all objects. Programs manipulate those objects either by performing
computation with them or by asking them to perform methods. To be more specific, we say that an object has
a **state** and a collection of **methods** that it can perform. The state of an object represents those things
-that the object knows about itself. For example, as we have seen with turtle objects, each turtle has a state consisting
-of the turtle's position, its color, its heading and so on. Each turtle also has the ability to go forward, backward, or turn right or left. Individual turtles are different in that even though they are
-all turtles, they differ in the specific values of the individual state attributes (maybe they are in a different location or have a different heading).
+that the object knows about itself. For example, each list has a state consisting
+of the items it contains, a length and so on. Each list also has the ability to add, delete, and sort the items inside of it. Individual lists are different in
+that even though they are all lists, they differ in the specific values of the individual state attributes (maybe they have different items inside them).
-.. image:: Figures/objectpic1.png
- :alt: Simple object has state and methods
diff --git a/_sources/ClassesBasics/ObjectsasArgumentsandParameters.rst b/_sources/ClassesBasics/ObjectsasArgumentsandParameters.rst
index 6cd2819a4..925c3a070 100644
--- a/_sources/ClassesBasics/ObjectsasArgumentsandParameters.rst
+++ b/_sources/ClassesBasics/ObjectsasArgumentsandParameters.rst
@@ -10,13 +10,8 @@
Objects as Arguments and Parameters
-------------------------------------
-You can pass an object as an argument in the usual way. We've already seen
-this in some of the turtle examples where we passed the turtle to
-some function like ``drawRectangle`` so that the function could
-control and use whatever turtle instance we passed to it.
-
-Here is a simple function called ``distance`` involving our new ``Point`` objects. The job of this function is to figure out the
-distance between two points.
+You can pass an object as an argument in the usual way. Here is a simple function called ``distance`` involving our new ``Point`` objects.
+The job of this function is to figure out the distance between two points.
.. activecode:: chp13_classes6
diff --git a/_sources/ClassesBasics/UserDefinedClasses.rst b/_sources/ClassesBasics/UserDefinedClasses.rst
index 6ea76a86b..0dfb99f2c 100644
--- a/_sources/ClassesBasics/UserDefinedClasses.rst
+++ b/_sources/ClassesBasics/UserDefinedClasses.rst
@@ -14,7 +14,7 @@
User Defined Classes
--------------------
-We've already seen classes like ``str``, ``int``, ``float`` and ``Turtle``. These were defined by Python and
+We've already seen classes like ``str``, ``int``, and ``float``. These were defined by Python and
made available for us to use. However, in many cases when we are solving problems we need to create data objects
that are related to the problem we are trying to solve. We need to create our own classes.
diff --git a/_sources/Files/FindingaFileonyourDisk.rst b/_sources/Files/FindingaFileonyourDisk.rst
index 56d915f14..b043969d0 100755
--- a/_sources/Files/FindingaFileonyourDisk.rst
+++ b/_sources/Files/FindingaFileonyourDisk.rst
@@ -45,9 +45,9 @@ but the same principles are in use. For example on windows the path might be
You can access files in sub-folders, also called directories, under your home directory
by adding a slash and the name of the folder. For example, if you had a file
-called ``hello.py`` in a folder called ``CS150`` that is inside a folder called
-``PyCharmProjects`` under your home directory, then the full name for the file
-``hello.py`` is ``/Users/yourname/PyCharmProjects/CS150/hello.py``.
+called ``hello.py`` in a folder called ``CS128`` that is inside a folder called
+``VSCodeProjects`` under your home directory, then the full name for the file
+``hello.py`` is ``/Users/yourname/VSCodeProjects/CS128/hello.py``.
This is called an *absolute file path*. An *absolute file path* typically
only works on a specific computer. Think about it for a second. What other
computer in the world is going to have an *absolute file path* that starts with
diff --git a/_sources/Files/WithStatements.rst b/_sources/Files/WithStatements.rst
index 4b18ca404..718bc0768 100644
--- a/_sources/Files/WithStatements.rst
+++ b/_sources/Files/WithStatements.rst
@@ -1,9 +1,6 @@
With Statements
---------------
-.. note::
- This section is a bit of an advanced topic and can be easily skipped. But with statements are becoming very common and it doesn't hurt to know about them in case you run into one in the wild.
-
Now that you have seen and practiced a bit with opening and closing files, there is another mechanism that Python provides for us that cleans up the often forgotten close. Forgetting to close a file does not necessarily cause a runtime error in the kinds of programs you typically write in an introductory CS course. However if you are writing a program that may run for days or weeks at a time that does a lot of file reading and writing you may run into trouble.
In version 2.5 Python introduced the concept of a context manager. The context manager automates the process of doing common operations at the start of some task, as well as automating certain operations at the end of some task. In the context of reading and writing a file, the normal operation is to open the file and assign it to a variable. At the end of working with a file the common operation is to make sure that file is closed.
diff --git a/_sources/Files/intro-WorkingwithDataFiles.rst b/_sources/Files/intro-WorkingwithDataFiles.rst
index fd5abfb27..8a8b7a8e3 100644
--- a/_sources/Files/intro-WorkingwithDataFiles.rst
+++ b/_sources/Files/intro-WorkingwithDataFiles.rst
@@ -14,7 +14,9 @@
Working with Data Files
=======================
-So far, the data we have used in this book have all been either coded right into the program, or have been entered by the user. In real life data reside in files. For example the images we worked with in the image processing unit ultimately live in files on your hard drive. Web pages, and word processing documents, and music are other examples of data that live in files. In this short chapter we will introduce the Python concepts necessary to use data from files in our programs.
+So far, the data we have used in this book have all been either coded right into the program, or have been entered by the user. In real life data reside in files.
+For example, web pages, word processing documents, and all data that live in files. In this short chapter we will introduce the Python concepts necessary to use
+data from files in our programs.
For our purposes, we will assume that our data files are text files--that is, files filled with characters. The Python programs that you write are stored as text files. We can create these files in any of a number of ways. For example, we could use a text editor to type in and save the data. We could also download the data from a website and then save it in a file. Regardless of how the file is created, Python will allow us to manipulate the contents.
diff --git a/_sources/IntroRecursion/toctree.rst b/_sources/IntroRecursion/toctree.rst
index 0f33af2b5..8da4ecbba 100644
--- a/_sources/IntroRecursion/toctree.rst
+++ b/_sources/IntroRecursion/toctree.rst
@@ -9,8 +9,6 @@ Recursion
CalculatingtheSumofaListofNumbers.rst
TheThreeLawsofRecursion.rst
ConvertinganIntegertoaStringinAnyBase.rst
- intro-VisualizingRecursion.rst
- SierpinskiTriangle.rst
Glossary.rst
ProgrammingExercises.rst
Exercises.rst
diff --git a/_sources/index.rst b/_sources/index.rst
index 98fdd802b..bfd39a59b 100644
--- a/_sources/index.rst
+++ b/_sources/index.rst
@@ -62,9 +62,9 @@ Table of Contents
Functions/toctree.rst
PythonModules/toctree.rst
Files/toctree.rst
- Exceptions/toctree.rst
IntroRecursion/toctree.rst
ClassesBasics/toctree.rst
+ Exceptions/toctree.rst
ClassesDiggingDeeper/toctree.rst
Inheritance/toctree.rst
UnitTesting/toctree.rst
From 1185f881add6a7b2f6ed2bbac35d22ee0111fdfe Mon Sep 17 00:00:00 2001
From: robotuw
Date: Sun, 5 Mar 2023 09:51:35 -0700
Subject: [PATCH 14/90] Fixes Batch
Mostly updates based on Ethan's notes. Hopefully this gets the server automatic update working again.
---
.../ThePythonProgrammingLanguage.rst | 15 ---------------
_sources/GeneralIntro/toctree.rst | 2 +-
.../FlowofExecutionofthewhileLoop.rst | 10 +++++-----
.../MoreAboutIteration/ThewhileStatement.rst | 17 +++++++++--------
_sources/MoreAboutIteration/toctree.rst | 5 -----
5 files changed, 15 insertions(+), 34 deletions(-)
diff --git a/_sources/GeneralIntro/ThePythonProgrammingLanguage.rst b/_sources/GeneralIntro/ThePythonProgrammingLanguage.rst
index c4e689c9d..512b934a4 100644
--- a/_sources/GeneralIntro/ThePythonProgrammingLanguage.rst
+++ b/_sources/GeneralIntro/ThePythonProgrammingLanguage.rst
@@ -58,11 +58,6 @@ without further translation.
.. image:: Figures/compile.png
:alt: Compile illustration
-Many modern languages use both processes. They are first compiled into a lower
-level language, called **byte code**, and then interpreted by a program called
-a **virtual machine**. Python uses both processes, but because of the way
-programmers interact with it, it is usually considered an interpreted language.
-
There are two ways to use the Python interpreter: *shell mode* and *program
mode*. In shell mode, you type Python expressions into the **Python shell**,
and the interpreter immediately shows the result. The example below shows the Python shell at work.
@@ -112,16 +107,6 @@ These examples show Python being run from a Unix command line. In other
development environments, the details of executing programs may differ. Also,
most programs are more interesting than this one.
-.. admonition:: Want to learn more about Python?
-
- If you would like to learn more about installing and using Python, here are some video links.
- `Installing Python for Windows `__ shows you how to install the Python environment under
- Windows Vista,
- `Installing Python for Mac `__ shows you how to install under Mac OS/X, and
- `Installing Python for Linux `__ shows you how to install from the Linux
- command line.
- `Using Python `__ shows you some details about the Python shell and source code.
-
**Check your understanding**
.. mchoice:: question1_2_1
diff --git a/_sources/GeneralIntro/toctree.rst b/_sources/GeneralIntro/toctree.rst
index 4a8ddbfbf..0f01d3ef9 100644
--- a/_sources/GeneralIntro/toctree.rst
+++ b/_sources/GeneralIntro/toctree.rst
@@ -15,9 +15,9 @@ General Introduction
RuntimeErrors.rst
SemanticErrors.rst
ExperimentalDebugging.rst
- FormalandNaturalLanguages.rst
ATypicalFirstProgram.rst
Comments.rst
+ FormalandNaturalLanguages.rst
Glossary.rst
Exercises.rst
\ No newline at end of file
diff --git a/_sources/MoreAboutIteration/FlowofExecutionofthewhileLoop.rst b/_sources/MoreAboutIteration/FlowofExecutionofthewhileLoop.rst
index a7b30d4af..1a6f94ae5 100644
--- a/_sources/MoreAboutIteration/FlowofExecutionofthewhileLoop.rst
+++ b/_sources/MoreAboutIteration/FlowofExecutionofthewhileLoop.rst
@@ -34,10 +34,10 @@ the buttons. You can see the value of ``count`` change as the loop iterates thr
.. codelens:: vtest
-count = 10
-while count > 0:
- print(count)
- count = count - 1
-print("Blastoff!")
+ count = 10
+ while count > 0:
+ print(count)
+ count = count - 1
+ print("Blastoff!")
diff --git a/_sources/MoreAboutIteration/ThewhileStatement.rst b/_sources/MoreAboutIteration/ThewhileStatement.rst
index c91b36f28..7b68775de 100644
--- a/_sources/MoreAboutIteration/ThewhileStatement.rst
+++ b/_sources/MoreAboutIteration/ThewhileStatement.rst
@@ -38,6 +38,7 @@ Here is a simple example that counts down from 10 to 0.
count = count - 1
print("Blastoff!")
+
* **count** is a normal variable here, but since it is governing the ``while`` loop it is also called the **loop variable**.
* Line 2 here is the **loop condition**. It must always be a boolean expression that will evaluate to ``False`` or ``True``.
* Lines 3 and 4 are the **loop body**. The loop body is always
@@ -99,14 +100,14 @@ The same program in codelens will allow you to observe the flow of execution.
.. codelens:: ch07_while3
-""" Return the sum of 1+2+3 ... n """
-aBound = int(input("Please give a number n: "))
-theSum = 0
-aNumber = 1
-while aNumber <= aBound:
- theSum = theSum + aNumber
- aNumber = aNumber + 1
-print(theSum)
+ """ Return the sum of 1+2+3 ... n """
+ aBound = int(input("Please give a number n: "))
+ theSum = 0
+ aNumber = 1
+ while aNumber <= aBound:
+ theSum = theSum + aNumber
+ aNumber = aNumber + 1
+ print(theSum)
diff --git a/_sources/MoreAboutIteration/toctree.rst b/_sources/MoreAboutIteration/toctree.rst
index 6e1842939..1a492e782 100644
--- a/_sources/MoreAboutIteration/toctree.rst
+++ b/_sources/MoreAboutIteration/toctree.rst
@@ -10,15 +10,10 @@ Iteration
FlowofExecutionofthewhileLoop.rst
The3n1Sequence.rst
SentinelValuesAndValidation.rst
-
TheforLoop.rst
TherangeFunction.rst
NewtonsMethod.rst
accumulatorRevisited.rst
-
AlgorithmsRevisited.rst
- SimpleTables.rst
- 2DimensionalIterationImageProcessing.rst
- ImageProcessingonYourOwn.rst
Glossary.rst
Exercises.rst
From 0c107b0fff4b5d5398633961f22fe9ae91867009 Mon Sep 17 00:00:00 2001
From: robotuw
Date: Tue, 23 May 2023 15:59:47 -0600
Subject: [PATCH 15/90] Name change
Changes made to book and course name for compatibility with Runestone hosting
---
pavement.py | 6 +++---
pretext/bookinfo.ptx | 2 +-
2 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/pavement.py b/pavement.py
index e48cbd584..f7af9f986 100644
--- a/pavement.py
+++ b/pavement.py
@@ -21,7 +21,7 @@
######## CHANGE THIS ##########
-project_name = "thinkcspy"
+project_name = "mines_csstem"
###############################
master_url = None
@@ -48,7 +48,7 @@
doctrees=doctrees,
template_args={
"course_id": project_name,
- "course_title": "How\\ to\\ Think\\ like\\ a\\ Computer\\ Scientist",
+ "course_title": "Computer\\ Science\\ for\\ STEM",
"login_required": "false",
"appname": master_app,
"loglevel": 10,
@@ -89,7 +89,7 @@
template_args = {
"course_id": project_name,
- "course_title": "How\\ to\\ Think\\ like\\ a\\ Computer\\ Scientist",
+ "course_title": "Computer\\ Science\\ for\\ STEM",
"login_required": "false",
"appname": master_app,
"loglevel": 10,
diff --git a/pretext/bookinfo.ptx b/pretext/bookinfo.ptx
index 7a12bdd7e..cf275cb34 100644
--- a/pretext/bookinfo.ptx
+++ b/pretext/bookinfo.ptx
@@ -30,7 +30,7 @@ along with MathBook XML. If not, see .
- httlacs
+ mines_csstemSB
From 279e6b3dcfe7a50e739e9c6b0ed674575208c1ba Mon Sep 17 00:00:00 2001
From: Ethan Richards <42894274+ezrichards@users.noreply.github.com>
Date: Wed, 24 May 2023 09:03:47 -0600
Subject: [PATCH 16/90] Switch to pretext
---
pretext/Lists/toctree.ptx | 8 +--
pretext/Selection/Chainedconditionals.ptx | 41 --------------
pretext/Selection/toctree.ptx | 4 +-
pretext/Strings/ACollectionDataType.ptx | 12 ++--
pretext/Strings/StringMethods.ptx | 68 ++++++++---------------
pretext/Strings/TheSliceOperator.ptx | 5 +-
pretext/Strings/toctree.ptx | 2 +-
pretext/thinkcspy.ptx | 14 ++---
8 files changed, 44 insertions(+), 110 deletions(-)
diff --git a/pretext/Lists/toctree.ptx b/pretext/Lists/toctree.ptx
index 6586bdd5a..f54a4433f 100644
--- a/pretext/Lists/toctree.ptx
+++ b/pretext/Lists/toctree.ptx
@@ -5,18 +5,19 @@
4
4
4
-4
4
4
4
4
+4
+4
+4
+4
4
4
4
4
-4
4
-4
4
4
4
@@ -25,7 +26,6 @@
4
4
4
-4
4
4
4
diff --git a/pretext/Selection/Chainedconditionals.ptx b/pretext/Selection/Chainedconditionals.ptx
index 835b296d8..c992f9998 100644
--- a/pretext/Selection/Chainedconditionals.ptx
+++ b/pretext/Selection/Chainedconditionals.ptx
@@ -146,45 +146,4 @@ else:
-
-
-
What will the following code print if x = 3, y = 5, and z = 2?
-
-
-if x < y and x < z:
- print("a")
-elif y < x and y < z:
- print("b")
-else:
- print("c")
-
-
-
-
-
-
-
a
-
-
- While the value in x is less than the value in y (3 is less than 5) it is not less than the value in z (3 is not less than 2).
-
-
-
-
-
b
-
-
- The value in y is not less than the value in x (5 is not less than 3).
-
-
-
-
-
c
-
-
- Since the first two Boolean expressions are false the else will be executed.
-
-
-
-
diff --git a/pretext/Selection/toctree.ptx b/pretext/Selection/toctree.ptx
index 981367449..d1fc3942a 100644
--- a/pretext/Selection/toctree.ptx
+++ b/pretext/Selection/toctree.ptx
@@ -2,12 +2,12 @@
4Selection
4
-4
-4
4
4
4
4
+4
+4
4
4
4
diff --git a/pretext/Strings/ACollectionDataType.ptx b/pretext/Strings/ACollectionDataType.ptx
index 28d162cb1..c64156c3d 100644
--- a/pretext/Strings/ACollectionDataType.ptx
+++ b/pretext/Strings/ACollectionDataType.ptx
@@ -1,12 +1,11 @@
A Collection Data Type
-
So far we have seen built-in types like: int, float,
- bool, str and we've seen lists.
- int, float, and
- bool are considered to be simple or primitive data types because their values are not composed
+
+
So far we have seen built-in types like: int, float, and str.
+
int and float are considered to be simple or primitive data types because their values are not composed
of any smaller parts. They cannot be broken down.
- On the other hand, strings and lists are different from the others because they
+ On the other hand, strings (and lists that we will talk about next chapter) are different from the others because they
are made up of smaller pieces. In the case of strings, they are made up of smaller
strings each containing one character.
Types that are comprised of smaller pieces are called collection data types.
@@ -14,5 +13,6 @@
single entity (the whole), or we may want to access its parts. This ambiguity is useful.
Strings can be defined as sequential collections of characters. This means that the individual characters
that make up the string are assumed to be in a particular order from left to right.
-
A string that contains no characters, often referred to as the empty string, is still considered to be a string. It is simply a sequence of zero characters and is represented by ‘' or (two single or two double quotes with nothing in between).
+
A string that contains no characters, often referred to as the empty string, is still considered to be a string.
+
It is simply a sequence of zero characters and is represented by ‘' or (two single or two double quotes with nothing in between).
We previously saw that each turtle instance has its own attributes and
- a number of methods that can be applied to the instance. For example,
- we wrote tess.right(90) when we wanted the turtle object tess to perform the right method to turn
- to the right 90 degrees. The dot notation is the way we connect the name of an object to the name of a method
- it can perform.
-
Strings are also objects. Each string instance has its own attributes and methods. The most important attribute of the string is the collection of characters. There are a wide variety of methods. Try the following program.
+
We previously used a few functions like print() and input(). A method is a function that is attached to a specific Python object.
+ To access this function, we write the object, then a dot ., and then the name of the method. The "dot notation" is the way we connect the name of an object to the name of a method
+ it can perform. For example, we can write ss.upper() when we wanted the string ss to perform the upper() method to create an upper-case version of itself.
+
Remember that Strings are objects. Each string instance has its own attributes and methods. The most important attribute of the string is the collection of characters. There are a wide variety of methods. Try the following program.
ss = "Hello, World"
@@ -338,7 +336,7 @@ print(s[1] * s.index("n"))
- String Format Method
+ F-Strings
In grade school quizzes a common convention is to use fill-in-the blanks. For instance,
Hello _____!
@@ -346,24 +344,23 @@ print(s[1] * s.index("n"))
and you can fill in the name of the person greeted, and combine
given text with a chosen insertion. We use this as an analogy:
Python has a similar
- construction, better called fill-in-the-braces. The string method format, makes
+ construction, called a formatted string or an f-string. An f-string makes
substitutions into places in a string
enclosed in braces. Run this code:
The string for the format method has a special form, with braces embedded.
- Such a string is called a format string. Places where
- braces are embedded are replaced by the value of an expression
- taken from the parameter list for the format method. There are many
+
The string has been formatted in a new way. We have included an f before the starting quotation mark.
+ Such a string is called an f-string. Places where
+ braces are embedded are replaced by the value of the expression inside the braces. There are many
variations on the syntax between the braces. In this case we use
the syntax where the first (and only) location in the string with
- braces has a substitution made from the first (and only) parameter.
+ braces has the variable person. When this code is evaluated, the value of the person variable is placed in the string in this location.
In the code above, this new string is assigned to the identifier
greeting, and then the string is printed.
The identifier
@@ -374,7 +371,7 @@ print(greeting)
person = input('Enter your name: ')
-print('Hello {}!'.format(person))
+print(f'Hello {person}!')
There can be multiple substitutions, with data of any type.
@@ -384,32 +381,28 @@ print('Hello {}!'.format(person))
origPrice = float(input('Enter the original price: $'))
discount = float(input('Enter discount percentage: '))
newPrice = (1 - discount/100)*origPrice
-calculation = '${} discounted by {}% is ${}.'.format(origPrice, discount, newPrice)
+calculation = f'${origPrice} discounted by {discount}% is ${newPrice}.'
print(calculation)
-
The parameters are inserted into the braces in order.
If you used the data suggested, this result is not satisfying.
Prices should appear with exactly two places beyond the decimal point,
but that is not the default way to display floats.
-
Format strings can give further information inside the braces
+
F-strings can give further information inside the braces
showing how to specially format data.
In particular floats can be shown with a specific number of decimal places.
- For two decimal places, put :.2f inside the braces for the monetary values:
+ For two decimal places, put :.2f inside the braces but after the variable name for the monetary values:
origPrice = float(input('Enter the original price: $'))
discount = float(input('Enter discount percentage: '))
newPrice = (1 - discount/100)*origPrice
-calculation = '${:.2f} discounted by {}% is ${:.2f}.'.format(origPrice, discount, newPrice)
+calculation = f'${origPrice:.2f} discounted by {discount}% is ${newPrice:.2f}.'
print(calculation)
The 2 in the format modifier can be replaced by another integer to round to that
specified number of digits.
-
This kind of format string depends directly on the order of the
- parameters to the format method. There are other approaches that we will
- skip here, explicitly numbering substitutions and taking substitutions from a dictionary.
A technical point: Since braces have special meaning in a format
string, there must be a special rule if you want braces to actually
be included in the final formatted string. The rule is to double
@@ -419,25 +412,10 @@ print(calculation)
formatted string:
a = 5
b = 9
-setStr = 'The set is {{ {},{} }}.'.format(a, b)
+setStr = f'The set is {{ {a},{b} }}.'
print(setStr)
Unfortunately, at the time of this writing, the ActiveCode format implementation has a bug,
printing doubled braces, but standard Python prints {5, 9}.
-
You can have multiple placeholders indexing the same argument, or perhaps even have extra
- arguments that are not referenced at all:
-
-
-letter = """
-Dear {0} {2}.
- {0}, I have an interesting money-making proposition for you!
- If you deposit $10 million into my bank account, I can
- double your money ...
-"""
-
-print(letter.format("Paris", "Whitney", "Hilton"))
-print(letter.format("Bill", "Henry", "Gates"))
-
-
What is printed by the following statements?
@@ -445,7 +423,7 @@ print(letter.format("Bill", "Henry", "Gates"))
x = 2
y = 6
-print('sum of {} and {} is {}; product: {}.'.format( x, y, x+y, x*y))
+print(f'sum of {x} and {y} is {x+y}; product: {x*y}.')
@@ -455,15 +433,15 @@ print('sum of {} and {} is {}; product: {}.'.format( x, y, x+y, x*y))
Nothing - it causes an error
- It is legal format syntax: put the data in place of the braces.
+ It is legal format syntax.
-
sum of {} and {} is {}; product: {}. 2 6 8 12
+
sum of {} and {} is {}; product: {}.
- Put the data into the format string; not after it.
+ Put the value of each expression in place of the braces.
@@ -471,7 +449,7 @@ print('sum of {} and {} is {}; product: {}.'.format( x, y, x+y, x*y))
sum of 2 and 6 is 8; product: 12.
- Yes, correct substitutions!
+ Yes, correct!
@@ -490,7 +468,7 @@ print('sum of {} and {} is {}; product: {}.'.format( x, y, x+y, x*y))
v = 2.34567
-print('{:.1f} {:.2f} {:.7f}'.format(v, v, v))
+print(f'{v:.1f} {v:.2f} {v:.7f}')
diff --git a/pretext/Strings/TheSliceOperator.ptx b/pretext/Strings/TheSliceOperator.ptx
index 9a038c491..8e846d375 100644
--- a/pretext/Strings/TheSliceOperator.ptx
+++ b/pretext/Strings/TheSliceOperator.ptx
@@ -13,10 +13,7 @@ print(singers[17:21])
The slice operator [n:m] returns the part of the string from the n'th character
to the m'th character, including the first but excluding the last. In other words, start with the character at index n and
- go up to but do not include the character at index m.
- This
- behavior may seem counter-intuitive but if you recall the range function, it did not include its end
- point either.
+ go up to but do not include the character at index m.
If you omit the first index (before the colon), the slice starts at the
beginning of the string. If you omit the second index, the slice goes to the
end of the string.
Throughout the earlier chapters, we wrote functions and called them using a syntax such as drawCircle(tess). This suggests that the
- function is the active agent. It says something like, Hey, drawCircle!
- Here's a turtle object for you to use to draw with.
-
In object-oriented programming, the objects are considered the active agents.
- For example, in our early introduction to turtles, we used
- an object-oriented style. We said tess.forward(100), which
- asks the turtle to move itself forward by the given number of steps.
- An
- invocation like tess.circle() says Hey tess!
- Please use your circle method!
-
This change in perspective is sometimes considered to be a more polite way to write programming instructions. However, it may not initially
+
Throughout the earlier chapters, we wrote functions and called them using a syntax such as printRange(lst). This suggests that the
+ function is the active agent. It says something like, "Hey, printRange!
+ Here's a list for you to use to print with."
+
In object-oriented programming, the objects are considered the active agents. This change in perspective is sometimes considered to be a more "polite" way
+ to write programming instructions. However, it may not initially
be obvious that it is useful. It turns out that often times shifting responsibility from
the functions onto the objects makes it possible to write more versatile
functions and makes it easier to maintain and reuse code.
diff --git a/pretext/ClassesBasics/AddingOtherMethodstoourClass.ptx b/pretext/ClassesBasics/AddingOtherMethodstoourClass.ptx
index 8365cd680..5efd49969 100644
--- a/pretext/ClassesBasics/AddingOtherMethodstoourClass.ptx
+++ b/pretext/ClassesBasics/AddingOtherMethodstoourClass.ptx
@@ -10,8 +10,8 @@
We can group together the sensible operations, and the kinds of data
they apply to, and each instance of the class can have its own state.
A method behaves like a function but it is invoked on a specific
- instance. For example, with a turtle named tess, tess.right(90) asks the tess object to perform its
- right method and turn 90 degrees. Methods are accessed using dot notation.
+ instance. For example, with a list named lst, lst.append(90) asks the lst object to perform its
+ append method and add the integer 90 to the end of the list. Methods are accessed using dot notation.
Let's add two simple methods to allow a point to give us information about its state. The getX method, when invoked, will return the value of the x coordinate. The implementation of this method is straight forward since we already know how
to write functions that return values. One thing to notice is that even though the getX method does not need any other parameter information to do its work, there is still one formal parameter, self. As we stated earlier, all methods defined in a class that operate on objects of that class will have self as their first parameter. Again, this serves as reference to the object itself which in turn gives access to the state data inside the object.
In Python, every value is actually an object. Whether it be a turtle, a list, or even an integer, they are all objects. Programs manipulate those objects either by performing
- computation with them or by asking them to perform methods. To be more specific, we say that an object has
- a state and a collection of methods that it can perform. The state of an object represents those things
- that the object knows about itself. For example, as we have seen with turtle objects, each turtle has a state consisting
- of the turtle's position, its color, its heading and so on. Each turtle also has the ability to go forward, backward, or turn right or left. Individual turtles are different in that even though they are
- all turtles, they differ in the specific values of the individual state attributes (maybe they are in a different location or have a different heading).
+
In Python, every value is actually an object. Whether it be a string, a list, or even an integer, they are all objects. Programs manipulate those objects either by performing
+ computation with them or by asking them to perform methods. To be more specific, we say that an object has
+ a state and a collection of methods that it can perform. The state of an object represents those things
+ that the object knows about itself. For example, each list has a state consisting
+ of the items it contains, a length and so on. Each list also has the ability to add, delete, and sort the items inside of it. Individual lists are different in
+ that even though they are all lists, they differ in the specific values of the individual state attributes (maybe they have different items inside them).
diff --git a/pretext/ClassesBasics/ObjectsasArgumentsandParameters.ptx b/pretext/ClassesBasics/ObjectsasArgumentsandParameters.ptx
index 93a00188f..58067f71f 100644
--- a/pretext/ClassesBasics/ObjectsasArgumentsandParameters.ptx
+++ b/pretext/ClassesBasics/ObjectsasArgumentsandParameters.ptx
@@ -1,12 +1,8 @@
Objects as Arguments and Parameters
-
You can pass an object as an argument in the usual way. We've already seen
- this in some of the turtle examples where we passed the turtle to
- some function like drawRectangle so that the function could
- control and use whatever turtle instance we passed to it.
-
Here is a simple function called distance involving our new Point objects. The job of this function is to figure out the
- distance between two points.
+
You can pass an object as an argument in the usual way. Here is a simple function called distance involving our new Point objects.
+ The job of this function is to figure out the distance between two points.
import math
diff --git a/pretext/ClassesBasics/UserDefinedClasses.ptx b/pretext/ClassesBasics/UserDefinedClasses.ptx
index 7a7a52a72..f0cf67485 100644
--- a/pretext/ClassesBasics/UserDefinedClasses.ptx
+++ b/pretext/ClassesBasics/UserDefinedClasses.ptx
@@ -1,7 +1,7 @@
User Defined Classes
-
We've already seen classes like str, int, float and Turtle. These were defined by Python and
+
We've already seen classes like str, int, and float. These were defined by Python and
made available for us to use. However, in many cases when we are solving problems we need to create data objects
that are related to the problem we are trying to solve. We need to create our own classes.
As an example, consider the concept of a mathematical point. In two dimensions, a point is two
diff --git a/pretext/Files/FindingaFileonyourDisk.ptx b/pretext/Files/FindingaFileonyourDisk.ptx
index 0f4e8a364..e0bc90208 100644
--- a/pretext/Files/FindingaFileonyourDisk.ptx
+++ b/pretext/Files/FindingaFileonyourDisk.ptx
@@ -30,9 +30,9 @@
You can access files in sub-folders, also called directories, under your home directory
by adding a slash and the name of the folder. For example, if you had a file
- called hello.py in a folder called CS150 that is inside a folder called
- PyCharmProjects under your home directory, then the full name for the file
- hello.py is /Users/yourname/PyCharmProjects/CS150/hello.py.
+ called hello.py in a folder called CS128 that is inside a folder called
+ VSCodeProjects under your home directory, then the full name for the file
+ hello.py is /Users/yourname/VSCodeProjects/CS128/hello.py.
This is called an absolute file path. An absolute file path typically
only works on a specific computer. Think about it for a second. What other
computer in the world is going to have an absolute file path that starts with
diff --git a/pretext/Files/WithStatements.ptx b/pretext/Files/WithStatements.ptx
index d356755b3..0bee04a3e 100644
--- a/pretext/Files/WithStatements.ptx
+++ b/pretext/Files/WithStatements.ptx
@@ -1,9 +1,6 @@
With Statements
-
-
This section is a bit of an advanced topic and can be easily skipped. But with statements are becoming very common and it doesn't hurt to know about them in case you run into one in the wild.
-
Now that you have seen and practiced a bit with opening and closing files, there is another mechanism that Python provides for us that cleans up the often forgotten close. Forgetting to close a file does not necessarily cause a runtime error in the kinds of programs you typically write in an introductory CS course. However if you are writing a program that may run for days or weeks at a time that does a lot of file reading and writing you may run into trouble.
In version 2.5 Python introduced the concept of a context manager. The context manager automates the process of doing common operations at the start of some task, as well as automating certain operations at the end of some task. In the context of reading and writing a file, the normal operation is to open the file and assign it to a variable. At the end of working with a file the common operation is to make sure that file is closed.
The Python with statement makes using context managers easy. The general form of a with statement is:
diff --git a/pretext/Files/intro-WorkingwithDataFiles.ptx b/pretext/Files/intro-WorkingwithDataFiles.ptx
index 2d7c753bb..ab952e8a3 100644
--- a/pretext/Files/intro-WorkingwithDataFiles.ptx
+++ b/pretext/Files/intro-WorkingwithDataFiles.ptx
@@ -1,7 +1,8 @@
Working with Data Files
-
So far, the data we have used in this book have all been either coded right into the program, or have been entered by the user. In real life data reside in files. For example the images we worked with in the image processing unit ultimately live in files on your hard drive. Web pages, and word processing documents, and music are other examples of data that live in files. In this short chapter we will introduce the Python concepts necessary to use data from files in our programs.
+
So far, the data we have used in this book have all been either coded right into the program, or have been entered by the user. In real life data reside in files.
+
For example, web pages, word processing documents, and all data that live in files. In this short chapter we will introduce the Python concepts necessary to use data from files in our programs.
For our purposes, we will assume that our data files are text files–that is, files filled with characters. The Python programs that you write are stored as text files. We can create these files in any of a number of ways. For example, we could use a text editor to type in and save the data. We could also download the data from a website and then save it in a file. Regardless of how the file is created, Python will allow us to manipulate the contents.
In Python, we must open files before we can use them and close them when we are done with them. As you might expect, once a file is opened it becomes a Python object just like all other data. shows the functions and methods that can be used to open and close files.
diff --git a/pretext/IntroRecursion/toctree.ptx b/pretext/IntroRecursion/toctree.ptx
index ead8eaa13..d16ca3cb8 100644
--- a/pretext/IntroRecursion/toctree.ptx
+++ b/pretext/IntroRecursion/toctree.ptx
@@ -5,8 +5,6 @@
4
4
4
-4
-4
4
4
4
diff --git a/pretext/MoreAboutIteration/toctree.ptx b/pretext/MoreAboutIteration/toctree.ptx
index 46986a334..f7b6b7a76 100644
--- a/pretext/MoreAboutIteration/toctree.ptx
+++ b/pretext/MoreAboutIteration/toctree.ptx
@@ -1,14 +1,13 @@
-4More About Iteration
+4Iteration
4
-4
4
-4
+4
4
+4
4
4
-4
4
4
4
From 6cb1be741f711099bfa68a28742de059074cf346 Mon Sep 17 00:00:00 2001
From: Ethan Richards <42894274+ezrichards@users.noreply.github.com>
Date: Wed, 24 May 2023 11:15:20 -0600
Subject: [PATCH 18/90] Add new loops sections
---
.../ThePythonProgrammingLanguage.ptx | 14 --
pretext/GeneralIntro/toctree.ptx | 2 +-
.../FlowofExecutionofthewhileLoop.ptx | 20 +++
pretext/MoreAboutIteration/TheforLoop.ptx | 86 ++++++++++
.../TherangeFunction.ptx | 22 +--
.../MoreAboutIteration/ThewhileStatement.ptx | 158 +++++++++---------
pretext/MoreAboutIteration/toctree.ptx | 7 +-
7 files changed, 197 insertions(+), 112 deletions(-)
create mode 100644 pretext/MoreAboutIteration/FlowofExecutionofthewhileLoop.ptx
create mode 100644 pretext/MoreAboutIteration/TheforLoop.ptx
rename pretext/{PythonTurtle => MoreAboutIteration}/TherangeFunction.ptx (95%)
diff --git a/pretext/GeneralIntro/ThePythonProgrammingLanguage.ptx b/pretext/GeneralIntro/ThePythonProgrammingLanguage.ptx
index 237728fcb..7063970cc 100644
--- a/pretext/GeneralIntro/ThePythonProgrammingLanguage.ptx
+++ b/pretext/GeneralIntro/ThePythonProgrammingLanguage.ptx
@@ -34,10 +34,6 @@
executable. Once a program is compiled, you can execute it repeatedly
without further translation.
-
Many modern languages use both processes. They are first compiled into a lower
- level language, called byte code, and then interpreted by a program called
- a virtual machine. Python uses both processes, but because of the way
- programmers interact with it, it is usually considered an interpreted language.
There are two ways to use the Python interpreter: shell mode and program
mode. In shell mode, you type Python expressions into the Python shell,
and the interpreter immediately shows the result. The example below shows the Python shell at work.
@@ -75,16 +71,6 @@ My first program adds two numbers, 2 and 3:
These examples show Python being run from a Unix command line. In other
development environments, the details of executing programs may differ. Also,
most programs are more interesting than this one.
-
- Want to learn more about Python?
-
If you would like to learn more about installing and using Python, here are some video links.
- Installing Python for Windows shows you how to install the Python environment under
- Windows Vista,
- Installing Python for Mac shows you how to install under Mac OS/X, and
- Installing Python for Linux shows you how to install from the Linux
- command line.
- Using Python shows you some details about the Python shell and source code.
-
Check your understanding
diff --git a/pretext/GeneralIntro/toctree.ptx b/pretext/GeneralIntro/toctree.ptx
index bf79d640a..0c51b26fd 100644
--- a/pretext/GeneralIntro/toctree.ptx
+++ b/pretext/GeneralIntro/toctree.ptx
@@ -11,9 +11,9 @@
4
4
4
-4
4
4
+4
4
4
diff --git a/pretext/MoreAboutIteration/FlowofExecutionofthewhileLoop.ptx b/pretext/MoreAboutIteration/FlowofExecutionofthewhileLoop.ptx
new file mode 100644
index 000000000..943ea9f8b
--- /dev/null
+++ b/pretext/MoreAboutIteration/FlowofExecutionofthewhileLoop.ptx
@@ -0,0 +1,20 @@
+
+
+ Flow of Execution of the while Loop
+
As before with ``if``, loops allow us as programmers to manipulate the control flow of a Python program.
+ We can now possibly skip a portion of code, or choose to repeat it an indefinite number of times.
+
The flowchart below provides the general sequence of steps that govern execution of a while loop.
+
+
A codelens demonstration is a good way to help you visualize exactly how the flow of control
+ works with the while loop. Try stepping forward and backward through the program by pressing
+ the buttons. You can see the value of count change as the loop iterates through the values from 10 to 0.
+
+
+ count = 10
+ while count > 0:
+ print(count)
+ count = count - 1
+ print("Blastoff!")
+
+
+
diff --git a/pretext/MoreAboutIteration/TheforLoop.ptx b/pretext/MoreAboutIteration/TheforLoop.ptx
new file mode 100644
index 000000000..d98fc4484
--- /dev/null
+++ b/pretext/MoreAboutIteration/TheforLoop.ptx
@@ -0,0 +1,86 @@
+
+
+ The for loop
+
The while statement is a general-purpose tool for iteration, and is necessary for any instance of iteration where we don't know how many repetitions will be needed.
+However, if we do know how many are needed, there is a more efficient method: the for statement.
+
As a simple example, let's say we have some friends, and
+we'd like to send them each an email inviting them to our party. We
+don't quite know how to send email yet, so for the moment we'll just print a
+message for each friend.
+
+
+ for name in ["Joe", "Amy", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]:
+ print(f"Hi {name}! Please come to my party on Saturday!")
+
+
+
Take a look at the output produced when you press the run button. There is one line printed for each friend. Here's how it works:
+
+
name in this for statement is the loop variable.
+
The list of names in the square brackets is a regular list. Later we'll see that other types besides lists can be put in this spot.
+
Line 2 is the loop body. Like with while, the loop body is always indented. The loop body is performed one time for each name in the list.
+
On each iteration or pass of the loop, a check is done to see if
+ there are still more items to be processed. If there are none left (this is
+ called the terminating condition of the loop), the loop has finished.
+ Program execution continues at the next statement after the loop body.
+
If there are items still to be processed, the loop variable is updated to
+ refer to the next item in the list. This means, in this case, that the loop
+ body is executed here 7 times, and each time name will refer to a different
+ friend.
+
At the end of each execution of the body of the loop, Python returns
+ to the for statement, to see if there are more items to be handled.
+
+
+
+
Introduction of the for statement causes us to think about the types of iteration we have seen. The for statement will always iterate through a sequence of
+ values like the list of names for the party.
+
Since we know that it will iterate once for each value in the collection, it is often said that a for loop creates a
+ definite iteration because we definitely know how many times we are going to iterate. On the other
+ hand, the while statement is dependent on a condition that needs to evaluate to False in order
+ for the loop to terminate. Since we do not necessarily know when this will happen, it creates what we
+ call indefinite iteration. Indefinite iteration simply means that we don't know how many times we will repeat but eventually the condition
+ controlling the iteration will fail and the iteration will stop. (Unless we have an infinite loop which is of course a problem.)
+
+
+
+ Choosing between for and while
+
Use a for loop if you know the maximum number of times that you'll
+ need to execute the body. For example, if you're traversing a list of elements,
+ or can formulate a suitable call to range, then choose the for loop.
+
So any problem like "iterate this weather model run for 1000 cycles", or "search this
+ list of words", "check all integers up to 10000 to see which are prime" suggest that a for loop is best.
+
By contrast, if you are required to repeat some computation until some condition is
+ met, as we did in this 3n + 1 problem, you'll need a while loop.
+
+
+
What you will notice here is that the while loop is more work for
+you --- the programmer --- than the equivalent for loop. When using a while
+loop you have to control the loop variable yourself. You give it an initial value, test
+for completion, and then make sure you change something in the body so that the loop
+terminates.
+
+ Check your understanding
+
+
+
+
True or False: You can rewrite any for-loop as a while-loop.
+
+
+
+
+
True
+
+
+ The syntax for a for-loop can make it easier and more appealing, but a while loop is just as powerful as a for-loop and often more flexible.
+
+
+
+
+
False
+
+
+ Often a for-loop is more natural and convenient for a task, but that same task can always be expressed using a while loop.
+
+
+
+
+
diff --git a/pretext/PythonTurtle/TherangeFunction.ptx b/pretext/MoreAboutIteration/TherangeFunction.ptx
similarity index 95%
rename from pretext/PythonTurtle/TherangeFunction.ptx
rename to pretext/MoreAboutIteration/TherangeFunction.ptx
index 1c79cedd4..05f9fdbaa 100644
--- a/pretext/PythonTurtle/TherangeFunction.ptx
+++ b/pretext/MoreAboutIteration/TherangeFunction.ptx
@@ -2,21 +2,8 @@
The range Function
-
In our simple example from the last section (shown again below), we used a list of four integers to cause the iteration
- to happen four times. We said that we could have used any four values. In fact, we even used four colors.
-
-
-import turtle # set up alex
-wn = turtle.Screen()
-alex = turtle.Turtle()
-
-for i in [0, 1, 2, 3]: # repeat four times
- alex.forward(50)
- alex.left(90)
-
-wn.exitonclick()
-
-
+
In our first example of a while loop, we counted down from 10 to 0. If we were to consider doing this with a for loop, we would need to construct our own series of numbers
+ to loop through them.
It turns out that generating lists with a specific number of integers is a very common thing to do, especially when you
want to write simple for loop controlled iteration. Even though you can use any four items, or any four integers for that matter, the conventional thing to do is to use a list of integers starting with 0.
In fact, these lists are so popular that Python gives us special built-in
@@ -37,9 +24,8 @@ for x in range(10):
So to repeat something four times, a good Python programmer would do this:
-for i in range(4):
- alex.forward(50)
- alex.left(90)
+ for i in range(10):
+ #do something
The range function is actually a very powerful function
diff --git a/pretext/MoreAboutIteration/ThewhileStatement.ptx b/pretext/MoreAboutIteration/ThewhileStatement.ptx
index 1a9d87cf7..36f12d604 100644
--- a/pretext/MoreAboutIteration/ThewhileStatement.ptx
+++ b/pretext/MoreAboutIteration/ThewhileStatement.ptx
@@ -2,74 +2,54 @@
The while Statement
-
There is another Python statement that can also be used to build an iteration. It is called the while statement.
- The while statement provides a much more general mechanism for iterating. Similar to the if statement, it uses
- a boolean expression to control the flow of execution. The body of while will be repeated as long as the controlling boolean expression evaluates to True.
-
+
A basic building block of all programs is to be able to repeat some code
+ over and over again. In computer science, we refer to this repetitive idea as iteration. In this section, we will explore some mechanisms for basic iteration.
The following figure shows the flow of control.
-
-
We can use the while loop to create any type of iteration we wish, including anything that we have previously done with a for loop. For example, the program in the previous section could be rewritten using while.
- Instead of relying on the range function to produce the numbers for our summation, we will need to produce them ourselves. To to this, we will create a variable called aNumber and initialize it to 1, the first number in the summation. Every iteration will add aNumber to the running total until all the values have been used.
- In order to control the iteration, we must create a boolean expression that evaluates to True as long as we want to keep adding values to our running total. In this case, as long as aNumber is less than or equal to the bound, we should keep going.
-
Here is a new version of the summation program that uses a while statement.
+
Let's look at our first Python statement that can be used to build an iteration. It is called the while statement. When used with other code it can be used to
+ repeat code in a while loop. Similar to the if statement, it uses
+ a boolean expression to control the flow of execution. The body of while (code indented one space in) will be repeated as long as the controlling boolean
+ expression evaluates to True.
+
Here is a simple example that counts down from 10 to 0.
You can almost read the while statement as if it were in natural language. It means,
- while aNumber is less than or equal to aBound, continue executing the body of the loop. Within
- the body, each time, update theSum using the accumulator pattern and increment aNumber. After the body of the loop, we go back up to the condition of the while and reevaluate it. When aNumber becomes greater than aBound, the condition fails and flow of control continues to the return statement.
-
The same program in codelens will allow you to observe the flow of execution.
-
-
-def sumTo(aBound):
- """ Return the sum of 1+2+3 ... n """
- theSum = 0
- aNumber = 1
- while aNumber <= aBound:
- theSum = theSum + aNumber
- aNumber = aNumber + 1
- return theSum
-
-print(sumTo(4))
-
-
-
More formally, here is the flow of execution for a while statement:
-
-
-
Evaluate the condition, yielding False or True.
-
-
-
-
If the condition is False, exit the while statement and continue
- execution at the next statement.
-
-
-
If the condition is True, execute each of the statements in the body and
- then go back to step 1.
-
-
+
+
count is a normal variable here, but since it is governing the while loop it is also called the loop variable.
+
+
+
Line 2 here is the loop condition. It must always be a boolean expression that will evaluate to False or True.
+
+
+
Lines 3 and 4 are the loop body. The loop body is always
+ indented. The indentation determines exactly what statements are "in the
+ loop". The loop body is run each time the loop is repeated.
+
+
+
On each iteration or pass of the loop, a check is done to see if
+ the loop condition is True (if count is greater than zero). If it is not (this is
+ called the terminating condition of the loop), the loop has finished.
+ Program execution continues at the next statement after the loop body.
+
+
+
If count is greater than zero, the loop body is executed again.
+
+
+
At the end of each execution of the body of the loop, Python returns
+ to the while statement, to see if the loop should repeat.
+
-
The body consists of all of the statements below the header with the same
- indentation.
-
This type of flow is called a loop because the third step loops back around
- to the top. Notice that if the condition is False the first time through the
- loop, the statements inside the loop are never executed.
+
+
Notice that if the condition is False the first time through the
+ loop, the statements inside the loop are never executed.
+
Though Python's while is very close to the English while,
there is an important difference: In English while X, do Y,
@@ -78,31 +58,59 @@ print(sumTo(4))
initial test, any following tests come only after the execution of
the whole body, even if the condition becomes false in the middle of the loop body.
+
The body of the loop should change the value of one or more variables so that
eventually the condition becomes False and the loop terminates. Otherwise the
loop will repeat forever. This is called an infinite loop.
An endless
source of amusement for computer scientists is the observation that the
directions written on the back of the shampoo bottle (lather, rinse, repeat) create an infinite loop.
+
+
We can use the while loop to create any type of iteration we wish, making more general-purpose than the for loop we'll learn next week.
+ For example, let us consider a program that adds all numbers from 1 to n. To do this, we will create a variable called aNumber and initialize it to
+ 1, the first number in the summation. Every iteration will add aNumber to the running total until all the values have been used.
+ In order to control the iteration, we must create a boolean expression that evaluates to True as long as we want to keep adding values to our
+ running total. In this case, as long as aNumber is less than or equal to the bound, we should keep going.
+
+
Here is the summation program that uses a while statement.
+
+
+
+ """ Return the sum of 1+2+3 ... n """
+ aBound = int(input("Please give a number n: "))
+ theSum = 0
+ aNumber = 1
+ while aNumber <= aBound:
+ theSum = theSum + aNumber
+ aNumber = aNumber + 1
+ print(theSum)
+
+
+
+
You can almost read the while statement as if it were in natural language. It means,
+ while aNumber is less than or equal to aBound, continue executing the body of the loop. Within
+ the body, each time, update theSum using the accumulator pattern and increment aNumber. After the body of the loop, we go back up to the condition of the while and reevaluate it. When aNumber becomes greater than aBound, the condition fails and flow of control continues to the return statement.
+
+
The same program in codelens will allow you to observe the flow of execution.
+
+
+
+ """ Return the sum of 1+2+3 ... n """
+ aBound = int(input("Please give a number n: "))
+ theSum = 0
+ aNumber = 1
+ while aNumber <= aBound:
+ theSum = theSum + aNumber
+ aNumber = aNumber + 1
+ print(theSum)
+
+
+
In the case shown above, we can prove that the loop terminates because we
know that the value of aBound is finite, and we can see that the value of aNumber
increments each time through the loop, so eventually it will have to exceed aBound. In
other cases, it is not so easy to tell.
-
-
Introduction of the while statement causes us to think about the types of iteration we have seen. The for statement will always iterate through a sequence of values like the list of names for the party or the list of numbers created by range. Since we know that it will iterate once for each value in the collection, it is often said that a for loop creates a
- definite iteration because we definitely know how many times we are going to iterate. On the other
- hand, the while statement is dependent on a condition that needs to evaluate to False in order
- for the loop to terminate. Since we do not necessarily know when this will happen, it creates what we
- call indefinite iteration. Indefinite iteration simply means that we don't know how many times we will repeat but eventually the condition controlling the iteration will fail and the iteration will stop. (Unless we have an infinite loop which is of course a problem.)
-
-
What you will notice here is that the while loop is more work for
- you — the programmer — than the equivalent for loop. When using a while
- loop you have to control the loop variable yourself. You give it an initial value, test
- for completion, and then make sure you change something in the body so that the loop
- terminates.
-
So why have two kinds of loop if for looks easier? The next section,
-, shows an indefinite iteration where
- we need the extra power that we get from the while loop.
+
This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
diff --git a/pretext/MoreAboutIteration/toctree.ptx b/pretext/MoreAboutIteration/toctree.ptx
index f7b6b7a76..9dd8c2d2d 100644
--- a/pretext/MoreAboutIteration/toctree.ptx
+++ b/pretext/MoreAboutIteration/toctree.ptx
@@ -3,15 +3,14 @@
4Iteration
4
4
-4
+4
4
4
+4
+4
4
4
4
-4
-4
-4
4
4
From 886f733187212beba9b61c6837ec682136df254e Mon Sep 17 00:00:00 2001
From: Ethan Richards <42894274+ezrichards@users.noreply.github.com>
Date: Wed, 24 May 2023 12:12:00 -0600
Subject: [PATCH 19/90] Convert all remaining changes to ptx
---
.error_schema.log | 2 -
.gitignore-20230129-131712 | 91 ---------
cli.log | 7 -
.../Functionscancallotherfunctions.ptx | 107 +---------
.../Functions/Functionsthatreturnvalues.ptx | 22 +--
pretext/Functions/functions.ptx | 184 ++++++------------
pretext/Functions/mainfunction.ptx | 71 +++----
pretext/Functions/toctree.ptx | 3 +-
pretext/Lists/toctree.ptx | 3 +-
.../FlowofExecutionofthewhileLoop.ptx | 10 +-
pretext/MoreAboutIteration/NewtonsMethod.ptx | 36 ++--
.../SentinelValuesAndValidation.ptx | 53 +++--
pretext/MoreAboutIteration/The3n1Sequence.ptx | 32 ++-
.../intro-IterationRevisited.ptx | 6 +-
pretext/PythonModules/CreatingModules.ptx | 6 +-
.../PythonModules/MoreAboutUsingModules.ptx | 19 +-
pretext/PythonModules/modules.ptx | 28 ++-
pretext/PythonModules/toctree.ptx | 1 -
.../ConditionalExecutionBinarySelection.ptx | 18 ++
pretext/Strings/toctree.ptx | 5 +-
pretext/thinkcspy.ptx | 6 +-
project-20230129-131712.ptx | 51 -----
requirements-20230129-131712.txt | 1 -
23 files changed, 208 insertions(+), 554 deletions(-)
delete mode 100644 .error_schema.log
delete mode 100644 .gitignore-20230129-131712
delete mode 100644 cli.log
delete mode 100644 project-20230129-131712.ptx
delete mode 100644 requirements-20230129-131712.txt
diff --git a/.error_schema.log b/.error_schema.log
deleted file mode 100644
index 2a12b54b8..000000000
--- a/.error_schema.log
+++ /dev/null
@@ -1,2 +0,0 @@
-file:/C:/Users/Rob/Documents/GitHub/thinkcspy/pretext/thinkcspy.ptx:3:0:ERROR:RELAXNGV:RELAXNG_ERR_ELEMWRONG: Did not expect element include there
-file:/C:/Users/Rob/Documents/GitHub/thinkcspy/pretext/thinkcspy.ptx:3:0:ERROR:RELAXNGV:RELAXNG_ERR_EXTRACONTENT: Element pretext has extra content: include
\ No newline at end of file
diff --git a/.gitignore-20230129-131712 b/.gitignore-20230129-131712
deleted file mode 100644
index ed41bfbfe..000000000
--- a/.gitignore-20230129-131712
+++ /dev/null
@@ -1,91 +0,0 @@
-# Boilerplate list of files in a PreTeXt project for git to ignore
-# ensure this file is tracked
-!.gitignore
-
-# don't track unpublished builds
-output
-
-# don't track assets generated from source
-generated-assets
-
-# don't track node packages
-node_modules
-
-# don't track error logs
-.error_schema.log
-cli.log
-
-# don't track OS related files (windows/macos/linux)
-.DS_Store
-.DS_Store?
-._*
-.AppleDouble
-.LSOverride
-.Spotlight-V100
-.Trashes
-Icon
-.AppleDB
-.AppleDesktop
-Network Trash Folder
-Temporary Items
-.apdisk
-Thumbs.db
-Thumbs.db:encryptable
-ehthumbs.db
-ehthumbs_vista.db
-*.stackdump
-*.lnk
-*.cab
-*.msi
-*.msix
-*.msm
-*.msp
-[Dd]esktop.ini
-.directory
-.fuse_hidden*
-.Trash-*
-.nfs*
-
-# Don't include VSCode generated files
-.vscode
-*.code-workspace
-
-# Don't inlucde SublimeText files
-# Cache files for Sublime Text
-*.tmlanguage.cache
-*.tmPreferences.cache
-*.stTheme.cache
-
-# Workspace files are user-specific
-*.sublime-workspace
-
-# Project files should be checked into the repository, unless a significant
-# proportion of contributors will probably not be using Sublime Text
-*.sublime-project
-
-# SFTP configuration file
-sftp-config.json
-sftp-config-alt*.json
-
-# Package control specific files
-Package Control.last-run
-Package Control.ca-list
-Package Control.ca-bundle
-Package Control.system-ca-bundle
-Package Control.cache/
-Package Control.ca-certs/
-Package Control.merged-ca-bundle
-Package Control.user-ca-bundle
-oscrypto-ca-bundle.crt
-bh_unicode_properties.cache
-
-# Sublime-github package stores a github token in this file
-# https://packagecontrol.io/packages/sublime-github
-GitHub.sublime-settings
-
-
-# Don't include Dropbox settings and caches
-.dropbox
-.dropbox.attr
-.dropbox.cache
-
diff --git a/cli.log b/cli.log
deleted file mode 100644
index 02e312d4d..000000000
--- a/cli.log
+++ /dev/null
@@ -1,7 +0,0 @@
-INFO : PreTeXt project found in `C:\Users\Rob\Documents\GitHub\thinkcspy`.
-WARNING : Project's CLI version could not be detected from `requirements.txt`.
-WARNING : Try `pretext init --refresh` to produce a compatible file.
-INFO :
-CRITICAL: There is not a target named "html" for this project.ptx manifest.
-INFO : However, the targets with names ['web', 'runestone', 'subset'] have "html" as their format. Try to view one of those instead or edit your project.ptx manifest.
-CRITICAL: Exiting.
diff --git a/pretext/Functions/Functionscancallotherfunctions.ptx b/pretext/Functions/Functionscancallotherfunctions.ptx
index 47ae94418..692aee804 100644
--- a/pretext/Functions/Functionscancallotherfunctions.ptx
+++ b/pretext/Functions/Functionscancallotherfunctions.ptx
@@ -41,100 +41,7 @@
for sum_of_squares. As you step through you will notice that x, and y are local variables in both functions and may even have
different values. This illustrates that even though they are named the same,
they are in fact, very different.
-
Now we will look at another example that uses two functions. This example illustrates an
- important computer science problem solving technique called
- generalization. Assume we want to write a
- function to draw a square. The generalization step is to realize that a
- square is just a special kind of rectangle.
-
To draw a rectangle we need to be able to call a function with different
- arguments for width and height. Unlike the case of the square,
- we cannot repeat the same thing 4 times, because the four sides are not equal.
- However, it is the case that drawing the bottom and right sides are the
- same sequence as drawing the top and left sides. So we eventually come up with
- this rather nice code that can draw a rectangle.
-
-
-def drawRectangle(t, w, h):
- """Get turtle t to draw a rectangle of width w and height h."""
- for i in range(2):
- t.forward(w)
- t.left(90)
- t.forward(h)
- t.left(90)
-
-
-
The parameter names are chosen as single letters for conciseness.
- In real programs, we will insist on better variable names than this.
- The point is that the program doesn't understand that you're drawing a rectangle or that the
- parameters represent the width and the height. Concepts like rectangle, width, and height are meaningful
- for humans. They are not concepts that the program or the computer understands.
-
- Thinking like a computer scientist involves looking for patterns and
- relationships. In the code above, we've done that to some extent. We did
- not just draw four sides. Instead, we spotted that we could draw the
- rectangle as two halves and used a loop to repeat that pattern twice.
-
But now we might spot that a square is a special kind of rectangle. A square
- simply uses the same value for both the height and the width.
- We already have a function that draws a rectangle, so we can use that to draw
- our square.
-
-
-def drawSquare(tx, sz): # a new version of drawSquare
- drawRectangle(tx, sz, sz)
-
-
-
Here is the entire example with the necessary set up code.
-
-
-import turtle
-
-def drawRectangle(t, w, h):
- """Get turtle t to draw a rectangle of width w and height h."""
- for i in range(2):
- t.forward(w)
- t.left(90)
- t.forward(h)
- t.left(90)
-
-def drawSquare(tx, sz): # a new version of drawSquare
- drawRectangle(tx, sz, sz)
-
-wn = turtle.Screen() # Set up the window
-wn.bgcolor("lightgreen")
-
-tess = turtle.Turtle() # create tess
-
-drawSquare(tess, 50)
-
-wn.exitonclick()
-
-
-
There are some points worth noting here:
-
-
-
-
Functions can call other functions.
-
-
-
Rewriting drawSquare like this captures the relationship
- that we've spotted.
-
-
-
A caller of this function might say drawSquare(tess, 50). The parameters
- of this function, tx and sz, are assigned the values of the tess object, and
- the integer 50 respectively.
-
-
-
In the body of the function, tz and sz are just like any other variable.
-
-
-
When the call is made to drawRectangle, the values in variables tx and sz
- are fetched first, then the call happens. So as we enter the top of
- function drawRectangle, its variable t is assigned the tess object, and w and
- h in that function are both given the value 50.
-
-
-
+
So far, it may not be clear why it is worth the trouble to create all of these
new functions. Actually, there are a lot of reasons, but this example
demonstrates two:
@@ -156,16 +63,4 @@ wn.exitonclick()
-
- Lab
-
-
-
-
- Drawing a Circle In this guided lab exercise we will work
- through a simple problem solving exercise related to drawing a circle with the turtle.
In this example, the arguments to the abs function are 5 and -5.
-
Some functions take more than one argument. For example the math module contains a function
- called
- pow which takes two arguments, the base and the exponent.
-
-
+
Some functions take more than one argument. For example the range function that we saw with for loops.
-import math
-print(math.pow(2, 3))
-
-print(math.pow(7, 4))
+ print(list(range(4, 8)))
+ print(list(range(1, 10)))
@@ -43,12 +37,12 @@ print(max(3 * 11, 5 ** 3, 512 - 9, 1024 ** 0))
return the maximum value sent. The arguments can be either simple values or
expressions. In the last example, 503 is returned, since it is larger than 33,
125, and 1. Note that max also works on lists of values.
-
Furthermore, functions like range, int, abs all return values that
+
Furthermore, functions like int and abs all return values that
can be used to build more complex expressions.
-
So an important difference between these functions and one like drawSquare is that
- drawSquare was not executed because we wanted it to compute a value — on the contrary,
- we wrote drawSquare because we wanted it to execute a sequence of steps that caused
- the turtle to draw a specific shape.
+
So an important difference between these functions and one like printRange is that
+ printRange was not executed because we wanted it to compute a value — on the contrary,
+ we wrote printRange because we wanted it to execute a sequence of steps that caused
+ the list's range to print.
Functions that return values are sometimes called fruitful functions.
In many other languages, a chunk that doesn't return a value is called a procedure,
but we will stick here with the Python way of also calling it a function, or if we want
diff --git a/pretext/Functions/functions.ptx b/pretext/Functions/functions.ptx
index 4c4af30eb..145fb6a0e 100644
--- a/pretext/Functions/functions.ptx
+++ b/pretext/Functions/functions.ptx
@@ -34,7 +34,7 @@ def name( parameters ):
-
We've already seen the for loop which follows this pattern.
+
We've already seen the while and for loops which follow this pattern.
In a function definition, the keyword in the header is def, which is
followed by the name of the function and some parameters enclosed in
parentheses. The parameter list may be empty, or it may contain any number of
@@ -45,34 +45,24 @@ def name( parameters ):
The figure below shows this relationship. A function needs certain information to do its work. These values, often called arguments or actual parameters, are passed to the function by the user.
This type of diagram is often called a black-box diagram because it only states the requirements from the perspective of the user. The user must know the name of the function and what arguments need to be passed. The details of how the function works are hidden inside the black-box.
-
Suppose we're working with turtles and a common operation we need is to draw
- squares. It would make sense if we did not have to duplicate all the steps each time we want to make a square. Draw a square can be thought of as an abstraction of a number of smaller steps. We will need to provide two pieces of information for the function to do its work: a turtle to do the drawing and a size for the side of the square. We could represent this using the following black-box diagram.
-
+
Suppose we're working with lists of numeric data and a common operation we need is to find the size of the range of numbers in a list.
+ It would make sense if we did not have to duplicate all the steps each time we want to find the size of the range. "printRange" can be thought of as an
+ abstraction of a number of smaller steps. We will need to provide one piece of information for the function to do its work: the list we need the range of.
Here is a program containing a function to capture this idea. Give it a try.
-import turtle
+ def printRange(lst):
+ """Prints the size of the range of lst."""
+ smallest = min(lst)
+ largest = max(lst)
+ print(largest - smallest)
-def drawSquare(t, sz):
- """Make turtle t draw a square of with side sz."""
-
- for i in range(4):
- t.forward(sz)
- t.left(90)
-
-
-wn = turtle.Screen() # Set up the window and its attributes
-wn.bgcolor("lightgreen")
-
-alex = turtle.Turtle() # create alex
-drawSquare(alex, 50) # Call the function to draw the square passing the actual turtle and the actual side size
-
-wn.exitonclick()
-
+ my_list1 = [1, 2, 3, 4, 5, 6]
+ printRange(my_list1)
+
-
This function is named drawSquare. It has two parameters — one to tell
- the function which turtle to move around and the other to tell it the size
- of the square we want drawn. In the function definition they are called t and sz respectively. Make sure you know where the body of the function
+
This function is named printRange. It has one parameter --- a variable storing a list of numbers. In the function definition this parameter is called
+ lst. Make sure you know where the body of the function
ends — it depends on the indentation and the blank lines don't count for
this purpose!
@@ -93,71 +83,24 @@ wn.exitonclick()
print, range and int. Function calls contain the name of the function to be
executed followed by a list of values in parentheses, called arguments, which are assigned
to the parameters in the function definition.
- So in the second to the last line of
- the program, we call the function, and pass alex as the turtle to be manipulated,
- and 50 as the size of the square we want.
-
-
+ So in the last line of
+ the program, we call the function, and pass my_list1 as the list to be analyzed.
Once we've defined a function, we can call it as often as we like and its
statements will be executed each time we call it. In this case, we could use it to get
- one of our turtles to draw a square and then we can move the turtle and have it draw a different square in a
- different location. Note that we lift the tail so that when alex moves there is no trace. We put the tail
- back down before drawing the next square. Make sure you can identify both invocations of the drawSquare function.
+ the size of the range of multiple lists. Make sure you can identify all three invocations of the printRange function.
-import turtle
-
-def drawSquare(t, sz):
- """Make turtle t draw a square of with side sz."""
-
- for i in range(4):
- t.forward(sz)
- t.left(90)
-
-
-wn = turtle.Screen() # Set up the window and its attributes
-wn.bgcolor("lightgreen")
-
-alex = turtle.Turtle() # create alex
-drawSquare(alex, 50) # Call the function to draw the square
-
-alex.penup()
-alex.goto(100,100)
-alex.pendown()
-
-drawSquare(alex,75) # Draw another square
-
-wn.exitonclick()
-
-
-
In the next example, we've changed the drawSquare
- function a little and we get tess to draw 15 squares with some variations. Once the function has
- been defined, we can call it as many times as we like with whatever actual parameters we like.
-
-
-import turtle
-
-def drawMulticolorSquare(t, sz):
- """Make turtle t draw a multi-colour square of sz."""
- for i in ['red','purple','hotpink','blue']:
- t.color(i)
- t.forward(sz)
- t.left(90)
+def printRange(lst):
+ """Prints the size of the range of lst."""
+ smallest = min(lst)
+ largest = max(lst)
+ print(largest - smallest)
-wn = turtle.Screen() # Set up the window and its attributes
-wn.bgcolor("lightgreen")
-
-tess = turtle.Turtle() # create tess and set some attributes
-tess.pensize(3)
-
-size = 20 # size of the smallest square
-for i in range(15):
- drawMulticolorSquare(tess, size)
- size = size + 10 # increase the size for next time
- tess.forward(10) # move tess along a little
- tess.right(18) # and give her some extra turn
-
-wn.exitonclick()
+my_list1 = [1, 2, 3, 4, 5, 6]
+my_list2 = [2, 6, 9, 16, 42, 100, 2, 5]
+printRange(my_list1)
+printRange(my_list2)
+printRange([5, 10, 1000, 2])
@@ -165,8 +108,8 @@ wn.exitonclick()
the parentheses ( ) after the function name are required. This
can lead to a difficult bug: A function name without the
parenthesis is a legal expression referring to the function; for example,
- print and alex.penup, but they do
- not call the associated functions.
+ print, but it does
+ not call the associated function. Try it below if you want to see.
This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
@@ -302,18 +245,17 @@ wn.exitonclick()
What is the name of the following function?
-def drawSquare(t, sz):
- """Make turtle t draw a square of with side sz."""
- for i in range(4):
- t.forward(sz)
- t.left(90)
-
+def printSquare(size):
+ """Print a square of asterices with side size."""
+ for i in range(size):
+ print("*"*size)
+
-
def drawSquare(t, sz)
+
def printSquare(size)
This line is the complete function header (except for the semi-colon) which includes the name as well as several other components.
@@ -321,7 +263,7 @@ def drawSquare(t, sz):
-
drawSquare
+
printSquare
Yes, the name of the function is given after the keyword def and before the list of parameters.
@@ -329,7 +271,7 @@ def drawSquare(t, sz):
-
drawSquare(t, sz)
+
printSquare(size)
This includes the function name and its parameters
@@ -337,7 +279,7 @@ def drawSquare(t, sz):
-
Make turtle t draw a square with side sz.
+
Print a square of asterices with side size.
This is a comment stating what the function does.
@@ -350,11 +292,10 @@ def drawSquare(t, sz):
What are the parameters of the following function?
-def drawSquare(t, sz):
- """Make turtle t draw a square of with side sz."""
- for i in range(4):
- t.forward(sz)
- t.left(90)
+def printSquare(size):
+ """Print a square of asterices with side size."""
+ for i in range(size):
+ print("*"*size)
@@ -369,55 +310,54 @@ def drawSquare(t, sz):
-
t
+
size, i
- t is only one of the parameters to this function.
+ i is a variable used inside of the function, but not a parameter, which is passed in to the function.
-
t, sz
+
size
- Yes, the function specifies two parameters: t and sz.
+ Yes, the function specifies one parameter: size.
-
t, sz, i
+
"*"*size
- the parameters include only those variables whose values that the function expects to receive as input. They are specified in the header of the function.
+ This is an argument provided to the call to print().
-
Considering the function below, which of the following statements correctly invokes, or calls, this function (i.e., causes it to run)? Assume we already have a turtle named alex.
+
Considering the function below, which of the following statements correctly invokes, or calls, this function (i.e., causes it to run)? Assume we already have a variable named my_size.
-def drawSquare(t, sz):
- """Make turtle t draw a square of with side sz."""
- for i in range(4):
- t.forward(sz)
- t.left(90)
+def printSquare(size):
+ """Print a square of asterices with side size."""
+ for i in range(size):
+ print("*"*size)
-
def drawSquare(t, sz)
+
def printSquare(size)
- No, t and sz are the names of the formal parameters to this function. When the function is called, it requires actual values to be passed in.
+ No, size is the name of the formal parameter to this function. When the function is called, it requires an actual value to be passed in.
-
drawSquare
+
printSquare
A function call always requires parentheses after the name of the function.
@@ -425,26 +365,26 @@ def drawSquare(t, sz):
-
drawSquare(10)
+
printSquare(10)
- This function takes two parameters (arguments)
+ Yes, this would work
-
drawSquare(alex, 10):
+
printSquare(my_size):
- A colon is only required in a function definition. It will cause an error with a function call.
+ Yes, this would work since my_size is already defined.
-
drawSquare(alex, 10)
+
printSquare(size):
- Since alex was already previously defined and 10 is a value, we have passed in two correct values for this function.
+ A colon is only required in a function definition. It will cause an error with a function call.
diff --git a/pretext/Functions/mainfunction.ptx b/pretext/Functions/mainfunction.ptx
index ca984a2b8..41777c53f 100644
--- a/pretext/Functions/mainfunction.ptx
+++ b/pretext/Functions/mainfunction.ptx
@@ -2,59 +2,51 @@
Using a Main Function
Using functions is a good idea. It helps us to modularize our code by breaking a program
- into logical parts where each part is responsible for a specific task. For example, in one of our first programs there
- was a function called drawSquare that was responsible for having some turtle draw a square of some size.
- The actual turtle and the actual size of the square were defined to be provided as parameters. Here is that original program.
+ into logical parts where each part is responsible for a specific task. For example, in one of our recent programs there
+ was a function called square that was responsible for calculating the square of a number.
+ After the function definition we defined a variable, called the function, and printed its results. Here is that original program.
-import turtle
-
-def drawSquare(t, sz):
- """Make turtle t draw a square of with side sz."""
-
- for i in range(4):
- t.forward(sz)
- t.left(90)
+def square(x):
+ y = x * x
+ return y
+toSquare = 10
+squareResult = square(toSquare)
+print("The result of", toSquare, "squared is", squareResult)
+
+
+
If you look closely at the structure of this program, we first define the function square. At this point, we could have defined as many functions as were needed. Finally, there are five statements that set up the window, create the turtle, perform the function invocation, and wait for a user click to terminate the program.
-wn = turtle.Screen() # Set up the window and its attributes
-wn.bgcolor("lightgreen")
+
The final three statements perform the main processing that the program will do. Notice that much of the detail has been pushed inside the square function.
+ However, there are still these three lines of code that are needed to get things done.
-alex = turtle.Turtle() # create alex
-drawSquare(alex, 50) # Call the function to draw the square
+
In many programming languages (e.g. Java and C++), it is not possible to simply have statements sitting alone like this at the bottom of the program.
+ They are required to be part of a special function that is automatically invoked by the operating system when the program is executed.
+ This special function is called main. Although this is not required by the Python programming language, it is actually a good idea that we
+ can incorporate into the logical structure of our program. In other words, these three lines are logically related to one another in that they provide the
+ main tasks that the program will perform. Since functions are designed to allow us to break up a program into logical pieces, it makes sense to call this
+ piece main.
-wn.exitonclick()
-
-
-
If you look closely at the structure of this program, you will notice that we first perform all of our necessary import statements, in this case to be able to use the turtle module. Next, we define the function drawSquare. At this point, we could have defined as many functions as were needed. Finally, there are five statements that set up the window, create the turtle, perform the function invocation, and wait for a user click to terminate the program.
-
These final five statements perform the main processing that the program will do. Notice that much of the detail has been pushed inside the drawSquare function. However, there are still these five lines of code that are needed to get things done.
-
In many programming languages (e.g. Java and C++), it is not possible to simply have statements sitting alone like this at the bottom of the program. They are required to be part of a special function that is automatically invoked by the operating system when the program is executed. This special function is called main. Although this is not required by the Python programming language, it is actually a good idea that we can incorporate into the logical structure of our program. In other words, these five lines are logically related to one another in that they provide the main tasks that the program will perform. Since functions are designed to allow us to break up a program into logical pieces, it makes sense to call this piece main.
The following activecode shows this idea. In line 11 we have defined a new function called main that doesn't need any parameters. The five lines of main processing are now placed inside this function. Finally, in order to execute that main processing code, we need to invoke the main function (line 20). When you push run, you will see that the program works the same as it did before.
-import turtle
-
-def drawSquare(t, sz):
- """Make turtle t draw a square of with side sz."""
-
- for i in range(4):
- t.forward(sz)
- t.left(90)
+def square(x):
+ y = x * x
+ return y
def main(): # Define the main function
- wn = turtle.Screen() # Set up the window and its attributes
- wn.bgcolor("lightgreen")
-
- alex = turtle.Turtle() # create alex
- drawSquare(alex, 50) # Call the function to draw the square
-
- wn.exitonclick()
+ toSquare = 10
+ squareResult = square(toSquare)
+ print("The result of", toSquare, "squared is", squareResult)
main() # Invoke the main function
-
+
-
Now our program structure is as follows. First, import any modules that will be required. Second, define any functions that will be needed. Third, define a main function that will get the process started. And finally, invoke the main function (which will in turn call the other functions as needed).
+
Now our program structure is as follows. First, import any modules that will be required (you'll read about those in the next chapter). Second, define any functions
+ that will be needed. Third, define a main function that will get the process started. And finally, invoke the main function
+ (which will in turn call the other functions as needed).
In Python there is nothing special about the name main. We could have called this function anything we wanted. We chose main just to be consistent with some of the other languages.
@@ -82,7 +74,4 @@ if __name__ == "__main__":
Line 12 uses an if statement to ask about the value of the __name__ variable. If the value is "__main__", then the main function will be called. Otherwise, it can be assumed that the program is being imported into another program and we do not want to call main because that program will invoke the functions as needed. This ability to conditionally execute our main function can be extremely useful when we are writing code that will potentially be used by others. It allows us to include functionality that the user of the code will not need, most often as part of a testing process to be sure that the functions are working correctly.
-
-
In order to conditionally execute the main function, we used a structure called an if statement to create what is known as selection. This topic will be studied in much more detail later.
-
diff --git a/pretext/Functions/toctree.ptx b/pretext/Functions/toctree.ptx
index bea7a5db4..a67c2ddc1 100644
--- a/pretext/Functions/toctree.ptx
+++ b/pretext/Functions/toctree.ptx
@@ -3,7 +3,6 @@
4Functions
4
4
-4
4
4
4
@@ -11,7 +10,7 @@
4
4
4
-4
+4
4
4
diff --git a/pretext/Lists/toctree.ptx b/pretext/Lists/toctree.ptx
index f54a4433f..c0df8dd24 100644
--- a/pretext/Lists/toctree.ptx
+++ b/pretext/Lists/toctree.ptx
@@ -13,11 +13,11 @@
4
4
4
+4
4
4
4
4
-4
4
4
4
@@ -25,7 +25,6 @@
4
4
4
-4
4
4
4
diff --git a/pretext/MoreAboutIteration/FlowofExecutionofthewhileLoop.ptx b/pretext/MoreAboutIteration/FlowofExecutionofthewhileLoop.ptx
index 943ea9f8b..0e6ec1c18 100644
--- a/pretext/MoreAboutIteration/FlowofExecutionofthewhileLoop.ptx
+++ b/pretext/MoreAboutIteration/FlowofExecutionofthewhileLoop.ptx
@@ -10,11 +10,11 @@
the buttons. You can see the value of count change as the loop iterates through the values from 10 to 0.
- count = 10
- while count > 0:
- print(count)
- count = count - 1
- print("Blastoff!")
+ count = 10
+ while count > 0:
+ print(count)
+ count = count - 1
+ print("Blastoff!")
diff --git a/pretext/MoreAboutIteration/NewtonsMethod.ptx b/pretext/MoreAboutIteration/NewtonsMethod.ptx
index e4c677c9c..755a5b205 100644
--- a/pretext/MoreAboutIteration/NewtonsMethod.ptx
+++ b/pretext/MoreAboutIteration/NewtonsMethod.ptx
@@ -21,21 +21,21 @@ better = 1/2 * (approx + n/approx)
calculation yielding a better result.
-def newtonSqrt(n, howmany):
- approx = 0.5 * n
- for i in range(howmany):
- betterapprox = 0.5 * (approx + n/approx)
- approx = betterapprox
- return betterapprox
+ n = 100
+ howmany = 10
-print(newtonSqrt(100, 10))
-print(newtonSqrt(4, 10))
-print(newtonSqrt(1, 10))
+ approx = 0.5 * n
+ for i in range(howmany):
+ betterapprox = 0.5 * (approx + n/approx)
+ approx = betterapprox
+ prin(betterapprox)
Modify the program …
-
All three of the calls to newtonSqrt in the previous example produce the correct square root for the first parameter. However, were 10 iterations required to get the correct answer? Experiment with different values for the number of repetitions (the 10 on lines 8, 9, and 10). For each of these calls, find the smallest value for the number of repetitions that will produce the correct result.
+
The values used in the previous example produce the correct square root for 100. However, were 10 iterations required to get the correct answer?
+ Experiment with different values for the number of repetitions (howmany on line 2). Find the smallest value for the number of
+ repetitions that will produce the correct result.
Repeating more than the required number of times is a waste of computing resources. So definite iteration is not a good solution to this problem.
In general, Newton's algorithm will eventually reach a point where the new approximation is no better than the previous. At that point, we could simply stop.
@@ -45,15 +45,13 @@ print(newtonSqrt(1, 10))
uses a while condition to execute until the approximation is no longer changing. Each time through the loop we compute a better approximation using the formula described earlier. As long as the better is different, we try again. Step through the program and watch the approximations get closer and closer.
Indefinite loops are much more common in the real world than definite loops.
+
The indefinite loops provided by the ``while`` statement are common in the real world.
@@ -55,24 +55,21 @@
zero is a sentinel value, a value used to signal the end of the loop. Here's the code:
-def checkout():
- total = 0
- count = 0
- moreItems = True
- while moreItems:
- price = float(input('Enter price of item (0 when done): '))
- if price != 0:
+ total = 0
+ count = 0
+ moreItems = True
+ while moreItems:
+ price = float(input('Enter price of item (0 when done): '))
+ if price != 0:
count = count + 1
total = total + price
print('Subtotal: $', total)
- else:
+ else:
moreItems = False
- average = total / count
- print('Total items:', count)
- print('Total $', total)
- print('Average price per item: $', average)
-
-checkout()
+ average = total / count
+ print('Total items:', count)
+ print('Total $', total)
+ print('Average price per item: $', average)
There are still a few problems with this program.
@@ -133,23 +130,19 @@ checkout()
When you run the following code, try typing something other than Y or N to see how the code reacts:
-def get_yes_or_no(message):
- valid_input = False
- answer = input(message)
- while not valid_input:
- answer = answer.upper() # convert to upper case
- if answer == 'Y' or answer == 'N':
+ valid_input = False
+ response = input('Do you like lima beans? Y)es or N)o: ')
+ while not valid_input:
+ response = response.upper() # convert to upper case
+ if response == 'Y' or response == 'N':
valid_input = True
+ else:
+ response = input('Please enter Y for yes or N for no. \n' + message)
+ if response == 'Y':
+ print('Great! They are very healthy.')
else:
- answer = input('Please enter Y for yes or N for no. \n' + message)
- return answer
-
-response = get_yes_or_no('Do you like lima beans? Y)es or N)o: ')
-if response == 'Y':
- print('Great! They are very healthy.')
-else:
- print('Too bad. If cooked right, they are quite tasty.')
-
+ print('Too bad. If cooked right, they are quite tasty.')
+
As another example of indefinite iteration, let's look at a sequence that has fascinated mathematicians for many years.
+
As another example of iteration with while, let's look at a sequence that has fascinated mathematicians for many years.
The rule for creating the sequence is to start from
some positive integer, call it n, and to generate
the next term of the sequence from n, either by halving n,
whenever n is even, or else by multiplying it by three and adding 1 when it is odd. The sequence
terminates when n reaches 1.
-
This Python function captures that algorithm. Try running this program several times supplying different values for n.
+
This Python code captures that algorithm. Try running this program several times supplying different values for n.
-def seq3np1(n):
- """ Print the 3n+1 sequence from n, terminating when it reaches 1."""
- while n != 1:
+ n = 3
+
+ """ Print the 3n+1 sequence from n, terminating when it reaches 1."""
+ while n != 1:
print(n)
if n % 2 == 0: # n is even
- n = n // 2
+ n = n // 2
else: # n is odd
- n = n * 3 + 1
- print(n) # the last print is 1
-
-seq3np1(3)
-
+ n = n * 3 + 1
+ print(n) # the last print is 1
+
The condition for this loop is n != 1. The loop will continue running until
n == 1 (which will make the condition false).
@@ -36,16 +35,7 @@ seq3np1(3)
time through the loop until it reaches 1.
You might like to have some fun and see if you can find a small starting
number that needs more than a hundred steps before it terminates.
-
- Lab
-
-
-
-
Experimenting with the 3n+1 Sequence In this guided lab exercise we will try to learn more about this sequence.
-
-
-
-
+
Particular values aside, the interesting question is whether we can prove that
this sequence terminates for all positive values of n. So far, no one has been able
to prove it or disprove it!
diff --git a/pretext/MoreAboutIteration/intro-IterationRevisited.ptx b/pretext/MoreAboutIteration/intro-IterationRevisited.ptx
index daecea209..f463e292a 100644
--- a/pretext/MoreAboutIteration/intro-IterationRevisited.ptx
+++ b/pretext/MoreAboutIteration/intro-IterationRevisited.ptx
@@ -6,8 +6,6 @@
people do poorly.
Repeated execution of a sequence of statements is called iteration. Because
iteration is so common, Python provides several language features to make it
- easier. We've already seen the for statement in a previous chapter. This is a very common
- form of iteration in Python. In this chapter
- we are going to look at the while statement — another way to have your
- program do iteration.
+ easier. easier. In this chapter we are going to look at two common forms of iteration: the while statement
+ and the for` statement.
diff --git a/pretext/PythonModules/CreatingModules.ptx b/pretext/PythonModules/CreatingModules.ptx
index a62e7566a..d2843d3b0 100644
--- a/pretext/PythonModules/CreatingModules.ptx
+++ b/pretext/PythonModules/CreatingModules.ptx
@@ -1,7 +1,7 @@
Creating Modules
-
You've seen how to use modules like random, math, and turtle, but how would you create a module?
+
You've seen how to use modules like random and math, but how would you create a module?
Every time you've written a Python script you've created a module!
A Python module is just a Python source code file. Let's consider the Python file shown below.
It is important to include header comments in your module that explain what the module does.
-
- Function Comments
-
Functions are the next chapter, but the comments used here demonstrate a common Python documentation style.
-
Ok - so we've got a function in our module now, let's use it.
coffee_customer.py
diff --git a/pretext/PythonModules/MoreAboutUsingModules.ptx b/pretext/PythonModules/MoreAboutUsingModules.ptx
index 2ca17a267..b8a719511 100644
--- a/pretext/PythonModules/MoreAboutUsingModules.ptx
+++ b/pretext/PythonModules/MoreAboutUsingModules.ptx
@@ -1,15 +1,16 @@
More About Using Modules
+
Before we move on to exploring other modules, we should say a bit more about what modules are and how we
- typically use them. One of the most important things to realize about modules is the fact that they are data objects, just
- like any other data in Python. Module objects simply contain other Python elements.
+ typically use them. One of the most important things to realize about modules is the fact that they are data objects, just
+ like any other data in Python. Module objects simply contain other Python elements.
+
The first thing we need to do when we wish to use a module is perform an import. In the example above, the statement
- import turtle creates a new name, turtle, and makes it refer to a module object. This looks very much like
- the reference diagrams we saw earlier for simple variables.
-
-
In order to use something contained in a module, we use the dot notation, providing the module name and the specific item joined together with a dot. For example, to use the Turtle class, we say turtle.Turtle. You should read
- this as: In the module turtle, access the Python element called Turtle.
-
We will now turn our attention to a few other modules that you might find useful.
-
+ import math creates a new name, math, and makes it refer to a `module object`. This looks very much like
+ the reference diagrams we saw earlier for simple variables.
+
+
In order to use something contained in a module, we use the `dot` notation, providing the module name and the specific item joined together with a "dot". For example, to use the sqrt function, we say math.sqrt. You should read
+this as: "In the module math, access the Python element called sqrt".
A module is a file containing Python definitions and statements intended
for use in other Python programs. There are many Python modules that come with
- Python as part of the standard library. We have already used one of these quite extensively,
- the turtle module. Recall that once we import the module, we can use things
+ Python as part of the standard library. We have already used one of these briefly,
+ the math module. Recall that once we import the module, we can use things
that are defined inside.
-import turtle # allows us to use the turtles library
+import math # allows us to use the math library
-wn = turtle.Screen() # creates a graphics window
-alex = turtle.Turtle() # create a turtle named alex
+print(math.factorial(10)) # prints 10!
+print(math.exp(4)) # prints e^4
-alex.forward(150) # tell alex to move forward by 150 units
-alex.left(90) # turn by 90 degrees
-alex.forward(75) # complete the second side of a rectangle
-wn.exitonclick()
+print(math.log2(1024)) # prints log2(1024)
+print(math.sqrt(100)) # prints the square root of 100
-
Here we are using Screen and Turtle, both of which are defined inside the turtle module.
-
But what if no one had told us about turtle? How would we know
+
Here we are using factorial, exp, log2, and sqrt, all of which are defined inside the math module.
+
But what if no one had told us about math? How would we know
that it exists. How would we know what it can do for us? The answer is to ask for help and the best place to get
help about the Python programming environment is to consult with the Python Documentation.
The Python Documentation site for Python version 3 (the home page is shown below) is an extremely useful reference
@@ -35,10 +33,10 @@ wn.exitonclick()
and to use it often.
If you have not done so already, take a look at the Global Module Index. Here you will see an alphabetical listing of all
- the modules that are available as part of the standard library. Find the turtle module.
+ the modules that are available as part of the standard library. Find the math module.
-
-
You can see that all the turtle functionality that we have talked about is there. However, there is so much more. Take some time to read through and familiarize yourself with some of the other things that turtles can do.
+
You can see that all the math functionality that we have talked about is there. However, there is so much more.
+ Take some time to read through and familiarize yourself with some of the other things that math can do.
Note: Python modules and limitations with activecode
Throughout the chapters of this book, activecode windows allow you to practice the Python that you are learning.
@@ -46,7 +44,7 @@ wn.exitonclick()
environment and that the
activecode used here was strictly to help us learn. It is not the way we write production programs.
To that end, it is necessary to mention that many of the modules available in standard Python
- will not work in the activecode environment. In fact, only turtle, math, and random have been
+ will not work in the activecode environment. In fact, only math and random have been
completely ported at this point. If you wish to explore any
additional modules, you will need to also explore using a more robust development environment.
diff --git a/pretext/PythonModules/toctree.ptx b/pretext/PythonModules/toctree.ptx
index 0eb0cfa06..d89612617 100644
--- a/pretext/PythonModules/toctree.ptx
+++ b/pretext/PythonModules/toctree.ptx
@@ -3,7 +3,6 @@
4Python Modules
4
4
-4
4
4
4
diff --git a/pretext/Selection/ConditionalExecutionBinarySelection.ptx b/pretext/Selection/ConditionalExecutionBinarySelection.ptx
index 68e3b156b..8240e90ad 100644
--- a/pretext/Selection/ConditionalExecutionBinarySelection.ptx
+++ b/pretext/Selection/ConditionalExecutionBinarySelection.ptx
@@ -37,6 +37,24 @@ else:
line begins with the keyword if followed by a boolean expression and ends with
a colon (:).
The more indented statements that follow are called a block.
+
+
As a program executes, the interpreter always keeps track of which statement is
+ about to be executed. We call this the control flow, or the flow of
+ execution of the program. When humans execute programs, they often use their
+ finger to point to each statement in turn. So you could think of control flow
+ as "Python's moving finger".
+
+
Control flow until now has been strictly top to bottom, one statement at a
+ time. We call this type of control sequential. In Python flow is sequential as long as
+ successive statements are indented the same amount. The if statement
+ introduces indented sub-statements after the if heading.
+
+
Each if statement consists of a header line and a body. The header
+ line begins with the keyword if followed by a boolean expression and ends with
+ a colon (:).
+
+
The more indented statements that follow are called a block or sometimes a body.
+
Each of the statements inside the first block of statements is executed in order if the boolean
expression evaluates to True. The entire first block of statements
is skipped if the boolean expression evaluates to False, and instead
diff --git a/pretext/Strings/toctree.ptx b/pretext/Strings/toctree.ptx
index d4b8c7668..82ac396fa 100644
--- a/pretext/Strings/toctree.ptx
+++ b/pretext/Strings/toctree.ptx
@@ -10,16 +10,15 @@
4
4
4
+4
4
4
4
-4
4
-4
+4
4
4
4
-4
4
4
4
diff --git a/pretext/thinkcspy.ptx b/pretext/thinkcspy.ptx
index 1856dc116..ce0e64946 100644
--- a/pretext/thinkcspy.ptx
+++ b/pretext/thinkcspy.ptx
@@ -18,19 +18,19 @@
-
-
+
-
+
+
diff --git a/project-20230129-131712.ptx b/project-20230129-131712.ptx
deleted file mode 100644
index 686cb6fa1..000000000
--- a/project-20230129-131712.ptx
+++ /dev/null
@@ -1,51 +0,0 @@
-
-
-
-
-
-
- html
- source/main.ptx
- publication/publication.ptx
- output/web
-
-
- pdf
- source/main.ptx
- publication/publication.ptx
- output/print
-
-
- latex
- source/main.ptx
- publication/publication.ptx
- output/print-latex
-
-
- html
- source/main.ptx
- publication/publication.ptx
- output/subset
-
-
- ch_first
-
-
-
- latex
- pdflatex
- xelatex
- pdf2svg
- asy
- sage
- convert
- pdftops
- node
- file2brl
-
-
diff --git a/requirements-20230129-131712.txt b/requirements-20230129-131712.txt
deleted file mode 100644
index 51ab65802..000000000
--- a/requirements-20230129-131712.txt
+++ /dev/null
@@ -1 +0,0 @@
-pretextbook == 0.8.3
\ No newline at end of file
From d7f7a00c657cf12f2372bff64683da86dd4e888f Mon Sep 17 00:00:00 2001
From: robotuw
Date: Wed, 24 May 2023 16:00:13 -0600
Subject: [PATCH 20/90] Name Change
Updating the book name in various locations
---
conf.py | 16 ++++++++--------
pretext/index.ptx | 2 +-
pretext/thinkcspy.ptx | 2 +-
3 files changed, 10 insertions(+), 10 deletions(-)
diff --git a/conf.py b/conf.py
index 1d700d086..30c670ad9 100644
--- a/conf.py
+++ b/conf.py
@@ -51,10 +51,10 @@
generate_component_labels = False
# General information about the project.
-project = u'How to Think Like a Computer Scientist'
-copyright = u'2014 Brad Miller, David Ranum, Created using Runestone Interactive'
+project = u'Computer Science for STEM'
+copyright = u'based on the book by 2014 Brad Miller, David Ranum, Created using Runestone Interactive'
course_description = """Based on the original open source book by Allan Downy and Jeff Elkner. Learn Python, this edition is expanded with additional topics and is fully interactive. Try examples, answer questions, interactively, right in the book!"""
-key_words = "intro google active learning fun data turtle graphics learn"
+key_words = "intro google active learning fun data learn"
shelf_section = "Intro to Computer Science"
@@ -63,9 +63,9 @@
# built documents.
#
# The short X.Y version.
-version = '3.0'
+version = '1.0'
# The full version, including alpha/beta/rc tags.
-release = '3.0'
+release = '1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
@@ -130,7 +130,7 @@
#html_theme_options = {'nosidebar': 'true'}
html_theme_options = {
# Navigation bar title. (Default: ``project`` value)
- 'navbar_title': "How To Think Like a Computer Scientist",
+ 'navbar_title': "Computer Science for STEM",
# Tab name for entire site. (Default: "Site")
'navbar_site_name': "Chapters",
@@ -177,10 +177,10 @@
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
-html_title = 'How to Think like a Computer Scientist: Interactive Edition'
+html_title = 'Computer Science for STEM'
# A shorter title for the navigation bar. Default is the same as html_title.
-html_short_title = 'How to Think Like a Computer Scientist'
+html_short_title = 'Computer Science for STEM'
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
diff --git a/pretext/index.ptx b/pretext/index.ptx
index 88de7bc14..4153d6455 100644
--- a/pretext/index.ptx
+++ b/pretext/index.ptx
@@ -1,3 +1,3 @@
-
+
diff --git a/pretext/thinkcspy.ptx b/pretext/thinkcspy.ptx
index ce0e64946..bb96187a5 100644
--- a/pretext/thinkcspy.ptx
+++ b/pretext/thinkcspy.ptx
@@ -3,7 +3,7 @@
- How to Think Like a Computer Scientist
+ Computer Science for STEMThe PreTeXt Interactive Edition
From 0f7378f8e221a5cf5695a4ce6f4a593f5be572fb Mon Sep 17 00:00:00 2001
From: Ethan Richards <42894274+ezrichards@users.noreply.github.com>
Date: Thu, 25 May 2023 13:16:21 -0600
Subject: [PATCH 21/90] Fix 5_1_6 answers
---
pretext/Functions/functions.ptx | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/pretext/Functions/functions.ptx b/pretext/Functions/functions.ptx
index 145fb6a0e..b4f302265 100644
--- a/pretext/Functions/functions.ptx
+++ b/pretext/Functions/functions.ptx
@@ -363,7 +363,7 @@ def printSquare(size):
A function call always requires parentheses after the name of the function.
-
+
printSquare(10)
@@ -371,7 +371,7 @@ def printSquare(size):
Yes, this would work
-
+
printSquare(my_size):
@@ -379,7 +379,7 @@ def printSquare(size):
Yes, this would work since my_size is already defined.
-
+
printSquare(size):
From 223da60a46af74665efe83873a018527ef766645 Mon Sep 17 00:00:00 2001
From: Ethan Richards <42894274+ezrichards@users.noreply.github.com>
Date: Tue, 30 May 2023 09:34:19 -0600
Subject: [PATCH 22/90] Fix pretext errors
---
pretext/MoreAboutIteration/ThewhileStatement.ptx | 16 ++++++++--------
pretext/PythonTurtle/TheforLoop.ptx | 2 +-
pretext/PythonTurtle/toctree.ptx | 2 +-
3 files changed, 10 insertions(+), 10 deletions(-)
diff --git a/pretext/MoreAboutIteration/ThewhileStatement.ptx b/pretext/MoreAboutIteration/ThewhileStatement.ptx
index 36f12d604..60b4e82c2 100644
--- a/pretext/MoreAboutIteration/ThewhileStatement.ptx
+++ b/pretext/MoreAboutIteration/ThewhileStatement.ptx
@@ -14,8 +14,8 @@
count = 10
while count > 0:
- print(count)
- count = count - 1
+ print(count)
+ count = count - 1
print("Blastoff!")
@@ -80,9 +80,9 @@
aBound = int(input("Please give a number n: "))
theSum = 0
aNumber = 1
- while aNumber <= aBound:
- theSum = theSum + aNumber
- aNumber = aNumber + 1
+ while aNumber <= aBound:
+ theSum = theSum + aNumber
+ aNumber = aNumber + 1
print(theSum)
@@ -99,9 +99,9 @@
aBound = int(input("Please give a number n: "))
theSum = 0
aNumber = 1
- while aNumber <= aBound:
- theSum = theSum + aNumber
- aNumber = aNumber + 1
+ while aNumber <= aBound:
+ theSum = theSum + aNumber
+ aNumber = aNumber + 1
print(theSum)
diff --git a/pretext/PythonTurtle/TheforLoop.ptx b/pretext/PythonTurtle/TheforLoop.ptx
index 3da7d495c..062e40387 100644
--- a/pretext/PythonTurtle/TheforLoop.ptx
+++ b/pretext/PythonTurtle/TheforLoop.ptx
@@ -11,7 +11,7 @@
we'd like to send them each an email inviting them to our party. We
don't quite know how to send email yet, so for the moment we'll just print a
message for each friend.
-
+
for name in ["Joe", "Amy", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]:
print("Hi", name, "Please come to my party on Saturday!")
diff --git a/pretext/PythonTurtle/toctree.ptx b/pretext/PythonTurtle/toctree.ptx
index 84e786e12..5e1bb934e 100644
--- a/pretext/PythonTurtle/toctree.ptx
+++ b/pretext/PythonTurtle/toctree.ptx
@@ -7,7 +7,7 @@
4
4
4
-4
+
4
4
4
From a2cbb5a3d4d34f369fcc36f326d6c76c4070cae7 Mon Sep 17 00:00:00 2001
From: Ethan Richards <42894274+ezrichards@users.noreply.github.com>
Date: Tue, 30 May 2023 11:00:28 -0600
Subject: [PATCH 23/90] Update project settings
---
project.ptx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/project.ptx b/project.ptx
index 1b1e2aac9..616331f72 100644
--- a/project.ptx
+++ b/project.ptx
@@ -16,7 +16,7 @@
htmlpretext/thinkcspy.ptxpretext/publication-rs-academy.xml
- published/httlacs
+ published/mines_csstemlatex
From c8007e892ee8d23e53418467840727e72b5f9f5c Mon Sep 17 00:00:00 2001
From: Ethan Richards <42894274+ezrichards@users.noreply.github.com>
Date: Tue, 6 Jun 2023 14:43:38 -0600
Subject: [PATCH 24/90] Add list slice step info to 4.6
---
pretext/Lists/ListSlices.ptx | 81 ++++++++++++++++++++++++++++++++++++
1 file changed, 81 insertions(+)
diff --git a/pretext/Lists/ListSlices.ptx b/pretext/Lists/ListSlices.ptx
index 44ad1b42e..b3c7f97ef 100644
--- a/pretext/Lists/ListSlices.ptx
+++ b/pretext/Lists/ListSlices.ptx
@@ -54,4 +54,85 @@ print(alist[4:])
+
+
+
+
Slice also takes a third value, the step size.
+ We can also specify -1 as the step term to slice with the values in reverse.
+
+
+ Correct! Everything is sliced backwards in this case.
+
+
+
+
+
[3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
+
+
+ This is the original list!
+
+
+
+
+
False, 3.14, []
+
+
+ This operation is done on all of the items in the list, not just the first few.
+
+
+
+
From f34b57f31a4a689823b126c986e0c99192204f03 Mon Sep 17 00:00:00 2001
From: Ethan Richards <42894274+ezrichards@users.noreply.github.com>
Date: Thu, 8 Jun 2023 09:39:27 -0600
Subject: [PATCH 25/90] Elaborate on list slice step
---
pretext/Lists/ListSlices.ptx | 2 ++
pretext/MoreAboutIteration/intro-IterationRevisited.ptx | 2 +-
2 files changed, 3 insertions(+), 1 deletion(-)
diff --git a/pretext/Lists/ListSlices.ptx b/pretext/Lists/ListSlices.ptx
index b3c7f97ef..ff81dcdf8 100644
--- a/pretext/Lists/ListSlices.ptx
+++ b/pretext/Lists/ListSlices.ptx
@@ -58,6 +58,8 @@ print(alist[4:])
Slice also takes a third value, the step size.
+ This specifies the rate at which we increment (if the step size is positive)
+ or the rate at which we decrement (if the step size is negative).
We can also specify -1 as the step term to slice with the values in reverse.
Repeated execution of a sequence of statements is called iteration. Because
iteration is so common, Python provides several language features to make it
easier. easier. In this chapter we are going to look at two common forms of iteration: the while statement
- and the for` statement.
+ and the for statement.
From f7f3b141f38e7f109186b41fb0c12b9d5e5a9adb Mon Sep 17 00:00:00 2001
From: Ethan Richards <42894274+ezrichards@users.noreply.github.com>
Date: Thu, 8 Jun 2023 09:59:12 -0600
Subject: [PATCH 26/90] Write break/continue section
---
.../MoreAboutIteration/BreakAndContinue.ptx | 36 +++++++++++++++++++
pretext/MoreAboutIteration/toctree.ptx | 1 +
2 files changed, 37 insertions(+)
create mode 100644 pretext/MoreAboutIteration/BreakAndContinue.ptx
diff --git a/pretext/MoreAboutIteration/BreakAndContinue.ptx b/pretext/MoreAboutIteration/BreakAndContinue.ptx
new file mode 100644
index 000000000..1c0420543
--- /dev/null
+++ b/pretext/MoreAboutIteration/BreakAndContinue.ptx
@@ -0,0 +1,36 @@
+
+
+ break and continue
+
+
In loops, we sometimes want to traverse until we reach a certain value.
+ We could make some sort of loop condition with a boolean that is toggled as True once we
+ reach that value, but there's an easier way: the break statement.
+
+
When a break statement is reached, the loop immediately ends and proceeds with the code after the loop.
+ break is only a valid statement inside of loops, such as the following:
+
+
+
+for i in range(0, 10):
+ if i == 5:
+ break
+ print(i)
+
+
+
+
The continue statement is another keyword that we can use in loops.
+ When a continue statement is reached, the current iteration is stopped (similar to break),
+ however, the loop will continue running for all iterations after the current one.
+
+
+
+for i in range(0, 10):
+ if i == 5:
+ continue
+ print(i)
+
+
+
+ Notice the difference between the activecode example above for break and this example with continue.
+ Neither loop reaches 5, but in the loop with continue, it continues iterating after where 5 would have been.
+
diff --git a/pretext/MoreAboutIteration/toctree.ptx b/pretext/MoreAboutIteration/toctree.ptx
index 9dd8c2d2d..5cf14a161 100644
--- a/pretext/MoreAboutIteration/toctree.ptx
+++ b/pretext/MoreAboutIteration/toctree.ptx
@@ -11,6 +11,7 @@
4
4
4
+4
4
4
From 0e5daa57e38dfd674da2a85f8d4dec9c0091bb8b Mon Sep 17 00:00:00 2001
From: Ethan Richards <42894274+ezrichards@users.noreply.github.com>
Date: Thu, 8 Jun 2023 10:01:02 -0600
Subject: [PATCH 27/90] Fix toctree for iteration chapter
---
pretext/MoreAboutIteration/toctree.ptx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pretext/MoreAboutIteration/toctree.ptx b/pretext/MoreAboutIteration/toctree.ptx
index 5cf14a161..0501fedff 100644
--- a/pretext/MoreAboutIteration/toctree.ptx
+++ b/pretext/MoreAboutIteration/toctree.ptx
@@ -11,7 +11,7 @@
4
4
4
-4
+4
4
4
From 1aa39f5c3e6794adbd9c8f17a476786259ab264c Mon Sep 17 00:00:00 2001
From: Ethan Richards <42894274+ezrichards@users.noreply.github.com>
Date: Thu, 8 Jun 2023 10:53:47 -0600
Subject: [PATCH 28/90] Update build files
---
README.rst | 14 --------------
pretext/GenFigs/play-button/play-button.png | Bin 0 -> 6621 bytes
pretext/GenFigs/qrcode/GoogleLogic.png | Bin 0 -> 580 bytes
pretext/GenFigs/qrcode/HriDtn-0Dcw.png | Bin 0 -> 596 bytes
pretext/GenFigs/qrcode/advrange.png | Bin 0 -> 569 bytes
pretext/GenFigs/qrcode/assignvid.png | Bin 0 -> 574 bytes
pretext/GenFigs/qrcode/booleanexpressions.png | Bin 0 -> 564 bytes
pretext/GenFigs/qrcode/codelensvid.png | Bin 0 -> 596 bytes
pretext/GenFigs/qrcode/expression_vid.png | Bin 0 -> 554 bytes
pretext/GenFigs/qrcode/forloopvid.png | Bin 0 -> 550 bytes
.../qrcode/function_accumulator_pattern.png | Bin 0 -> 562 bytes
pretext/GenFigs/qrcode/function_intro.png | Bin 0 -> 557 bytes
pretext/GenFigs/qrcode/inputvid.png | Bin 0 -> 578 bytes
pretext/GenFigs/qrcode/precedencevid.png | Bin 0 -> 570 bytes
pretext/GenFigs/qrcode/reassignmentvid.png | Bin 0 -> 567 bytes
pretext/GenFigs/qrcode/typesnconvert.png | Bin 0 -> 599 bytes
pretext/GenFigs/qrcode/unaryselection.png | Bin 0 -> 583 bytes
pretext/GenFigs/qrcode/updatevid.png | Bin 0 -> 601 bytes
pretext/GenFigs/qrcode/vid_modules.png | Bin 0 -> 547 bytes
pretext/GenFigs/qrcode/vid_turtleintro.png | Bin 0 -> 596 bytes
pretext/GenFigs/qrcode/whileloop.png | Bin 0 -> 545 bytes
pretext/GenFigs/trace/ch07_while3.js | 4 ++++
pretext/GenFigs/trace/chp07_newtonswhile.js | 2 +-
requirements.txt | 2 +-
24 files changed, 6 insertions(+), 16 deletions(-)
create mode 100644 pretext/GenFigs/play-button/play-button.png
create mode 100644 pretext/GenFigs/qrcode/GoogleLogic.png
create mode 100644 pretext/GenFigs/qrcode/HriDtn-0Dcw.png
create mode 100644 pretext/GenFigs/qrcode/advrange.png
create mode 100644 pretext/GenFigs/qrcode/assignvid.png
create mode 100644 pretext/GenFigs/qrcode/booleanexpressions.png
create mode 100644 pretext/GenFigs/qrcode/codelensvid.png
create mode 100644 pretext/GenFigs/qrcode/expression_vid.png
create mode 100644 pretext/GenFigs/qrcode/forloopvid.png
create mode 100644 pretext/GenFigs/qrcode/function_accumulator_pattern.png
create mode 100644 pretext/GenFigs/qrcode/function_intro.png
create mode 100644 pretext/GenFigs/qrcode/inputvid.png
create mode 100644 pretext/GenFigs/qrcode/precedencevid.png
create mode 100644 pretext/GenFigs/qrcode/reassignmentvid.png
create mode 100644 pretext/GenFigs/qrcode/typesnconvert.png
create mode 100644 pretext/GenFigs/qrcode/unaryselection.png
create mode 100644 pretext/GenFigs/qrcode/updatevid.png
create mode 100644 pretext/GenFigs/qrcode/vid_modules.png
create mode 100644 pretext/GenFigs/qrcode/vid_turtleintro.png
create mode 100644 pretext/GenFigs/qrcode/whileloop.png
create mode 100644 pretext/GenFigs/trace/ch07_while3.js
diff --git a/README.rst b/README.rst
index b1dce3d73..c63c49ea5 100644
--- a/README.rst
+++ b/README.rst
@@ -43,17 +43,3 @@ Building for Production on a Runestone Server
1. clone this repo to `httlacs` instead of `thinkcspy`
2. Run `rsmanage addcourse` and add `httlacs` as course name and base course name
3. Run `rsmanage build --ptx httlacs`
-
-
-Building with runestone
------------------------
-As mentioned above this method is deprecated, but will still work.
-Any updates to this book should be made in PreTeXt NOT RST.
-
-You can build it and host it yourself in just a few simple steps:
-
- 1. ``pip install -r requirements.txt`` -- Should install everything you need
- 2. ``runestone build`` -- will build the html and put it in ``./build/thinkcspy``
- 3. ``runestone serve`` -- will start a webserver and serve the pages locally from ``./build/thinkcspy``
-
-
diff --git a/pretext/GenFigs/play-button/play-button.png b/pretext/GenFigs/play-button/play-button.png
new file mode 100644
index 0000000000000000000000000000000000000000..9e26551e125a2b03f6e8004afcecc5fe6d3d90ed
GIT binary patch
literal 6621
zcmZ{IWn7bQ*f##LNfm}711YHi3IZ}h>5`Bft)m2_M-31a5XR^fkr*LT;y^@N#0f}l
z(kW7d!N?IC@!Y)cr{}|Sf4T1ajN?3i*YAvDLm3%pF|fgC1oaR8paZx6v+ba}^Kf?N
zXqkAty>(2b9{!u9jgL_Y1N$wFd$rZO6{VC91v}Xp+nK3bsK_l;#O9k<8%V^uzbDz<
zam~SI&BlymtV`0@Sb2DV`GG7^N`!dl_L2zCA}`01xByXBd_`Sh)y#nG@?;~(cOx`l
zD?Vl?_ucO2iv6~hgI_;s)02lwizi1%2fe@dzSZuQf20)VZN)`zM!X9Ni-^zNb{*OKTh
zlCJ97Q_Jn-xSgE0l#)W)=5=;07wq1*FKc!dE2>cPGx&B&{1ItoQGjzr`{8Cp
z*nVr%F@>_ocYWzL*Q%BAPF^;3WN0hq_3{I`sZ*RyJ6a?tr}Gd!45l)v`W>UejTIy^{}5-uLJ2_d)$}&4y=^J5zOA>;|2M0vS+pCt3
z*FBs!0)43X{_XT6YJcx`YQieaXea;uZuO_5mF2yLx~&8h+1dV}w|m{wh5Cm;n;75!
z(Ml;V*?ftljg725v82sRkqk5sdb&tDDy!xOBt5l_7eNQVJNCZTko48}>c4JAh99l3
zAI{IMS{SaV$nVyC-m9yj6y=c&wRYZTZl@)#*~2!YUT*k%(WWL>)Sw%|en+dMHCyv7
z^qU<_&cUztt;E<}Y$c^2cSTcq=Uw_nXdv0iZojp8ANOP3$9=Ey+q$>gI>O_@;-o0h
z8)x8pTIzH$=fK*)$0cuVOTYi$Co50RM0QOF0Ky9h9es@pOaGl`35ZGUv6mZ=F4xuJQQ0IY@5a
zsxrUY)ch`==()3KVJmix%GmJ+bH^*0obE$zINS9hJfzhkGA4#gjK9V_yW->5vG_0B#Z_T*l0%qX5|1g(%U``JDhUoU_rNza7?(S{{zN;uizZ{n(>(HEVMQ*JKQiGl%
zn*#O_Q2eDmF2qH?c{wUUW@}G+cvIRzspEj^;=+?Bb4$90wHg1etLyn6UfS6i)N$&6
zLKh!&o;H5V-sRKw+_9KBT*Iy+;UJlSWrjC@+Z
zdxz`LR;vj;qC0!$S?}?d4t;BivUkX%+kO4LjZfzHUtc1wqlRyT<_)3LA13Y5w)YO;
zCq67B+TxkH}4ji_Lh%;NRcL{0(Ml9D6tI2rU%|(S}>4%P`qB
zg8kuEbtmFj(YFC5?c68YdKepE0d0hXqiy_mhxlCz1JMNU-uILLP8tL**kYV@tCUtP
z=J45S&g`~7uZ@3j)m61Z7z6>AHR>4W)-=VlwqFL+pLZe_O?uZV-B*Ue=b=nr4;I
z&A|K;$VIV(&;HimIGc@)pTmg(jqd)mV1|KmftO}N6Cw1Ck(ndSZU#a$H!~NHX>R)bNT_m^Of*ZTpLC+6M{689Bo!d1Je(>sKB-hi
zzb_!x4O85@tajWwReo1e^V4OnHnaJrkwz>D<&^RP2Ht4-AF*28za}H>&dc|`XZjG5
z9tK5TnSYon`)+mUk`i9;mez``TbYGg5J&XC#=tKqJEtRNa2^+_XXiwA(i;p_lpl4<
zCaey9rVZe`@YD~M6}`m2^WN=$R?>OE+3!8aHeGkh^v^(L@1^lUE>c&lr8+6b+_3Cc@M;2y3$gsfe@f-v&U
ziYi48XsBjvi%|A0Ew_dYqliKC=GUyauBM<9
zv_7#v!&vCuF8Gt|u7p>`2AyOP%)`|F!IeVYf9n@L(lND&jh!W9Kd0r%c@P
zgRt{_j}GxpQS#e}v-@v(EM3CXu*3N^Ntz#I*wBBpx}f2n!oy)iNKrC-(}qDnQ1k2$
z+7kqbpiO=SkJr@V&EX2mhbas^))qpuu#sdCY=o|#^thGR3944|8yQEJ5myPnU)8*`
z(-PvXoV2yCxGt;j2c}G)U-BU%KGEB2zQ}t
z>f@~_W=!+l>FlS25)Dsg>=2B-9;IR#nJ?rAL3)>urtm6Xc0+Bkix@xQLC+H&h}o-U
zqA+L3C(qRIXaFt@t3FI=JP+2i_OBU{iXD(=a}&`miQ;u+W-*7eqj
z*{<=aFm|w7@h{xf8?3v8es?p2@~MeB{9RKwD@gKO-up!6;vAh?g%EM*8{J;Cpm7G;
zpg3ElmWC7o1e>vfzDueIiRPY9Q$s$)>!LWxj2JHtXqLgEWITBp14sl#GaS=4+Afgd
z58K7Q@_KnhYl<(s?kQGU2v4m51Qib=Q07G8NsThMQB0aAJ>SV$^IGG
z@TCGZ;dE83dgyw=T*Hu+!`|_0W{jyWE`{;LpZJ}O$ioI(U;q;fxx>V=?48@_>#bD>TB`87=rPJHjsF=5^X?rTe`_v|!XR%Rsqz
zOJB-tWvf3#*nFoLy+HK8KQ%MYj5u2h5i#FUPRx80TRbZ&qM>EfT>$s_W-bQOu|8Fb
zfuh}OpG7gM0E!<#WMTW4c8MlTY&_7{Rv92Y$II*6KLc|^V-oT+aJX3Jk$+*i_o><(
zr>>G9`-T{j)4@fsiulb~!GE;t&5({P!Eh}ADg%CFXlsxzPQd1NUOxXvCll;_n{t%l
z0t|3m6$P<8c72XHqz4>nu{bqTI9S{oe`T<`2FCSi=zBB_$ZRmsh9gsW6GvDXw@^a
z43668Bi8aw&0*_W*+6x9K_H@zZVRH
z#BokV1D?Y4ziXA%qi{d)Q~-ftnKf*E`!fvI|NhPNmF&;3XKOR+>nL#;L~+J$=hNs*
zobOB3@W7oGSOU)X?9pjxX3PWt+I@Ei3ZVG1=9~uND(*EIB7&Hw4S6313)#l!p6BTC8dy!UjfBGg(K{9!34kgGM>VdwV&S}+!U{CaF1sGBP~1eybjiF}Ff&lM3bD0_Z@K)RdSGIir*$2M-2wYJ{kprQc-nd#dUF6|6C~%fFTTMV
z>k2vMjSRacfb=b`AiY{PSw6WHr=9i#zKnQ?T4>3LIJK;RA;CuQ`Vyym00@ZPy^urG
zCJS#^cA9h%Oa{jt;ws@^uF>Ql-TfNAN!GvmE4IT9a?iGcYd!9pRH6DjJ>q=vBT)H3
zUZUMAg&hu5zO=AY8I1cTkQr-o6p>LkOC+P;`h?}3@$D@>U>YrRkOaMsc%Bhx|FCr;
z1o2_!>1Lg-^T~CmbFB(S6D`BH**d@NJOW&cO&}~>M)2Ad#^i21Z<=m1Ecbr?Pq&)*
zc-qDPH(vco-_wbmo~EwPr(lSS#l~X84KKL4fza9x+jeTexJ`!#hXU6r9lzFnI(-k|
z!7DGXmRHKi4pN<@`nMe<~K9KUd{rI
zR$VI^=%?3R-LZwI4+~@e5<#GlU-uwz+PFXhg
z72EhzLPbK$u;xU5@%@XbJJAHF)@r#Vz^Mg_(i14ShHE*I2xDM}%*z7wOy@=WLqan+P;9)U+s+{s4F)&F?O_Fk1rYxKLWhmovp+!%TFaX@W8V~jeWPvid&ixpLZxR$N
z7ivb~l^Ot9W$OTyO9Bc9fTreZ0s<}$>k6>}fW1cl1d%)uoCM8|QMeQ4Pm%;TdM$n4
zv~WA=cHc8oNU8b~ufEObHy8sxSo_+^Gn8x8ZB*E_{0mN`=8#M@1-m{WQe~iQ~0&9M{^6^=Cd6
z^abG>UeR-PzQ1vmW2Q#PkNQ(`ScGUZ@9QwfQ7#STsGm5LoZ}!ZJ|;TOyM+k8T01>m
zghb6P5K_LiyQtWqGdXdStMBwtv4STNeVP)(LQkuL?%&HAkoUntF*V5{y}9qc!F<6`
zaQ*Ni2q_q@TEai_ZrB(*4*W*4t}Jsag;jIpB-*&SqnlHB1`axl1L|xln40Xhmx(!e
zU#uet%3DvEv0hGpq$VUFXZ0Cd3uo_p=pw*@tgf{~g}(07mKbcMz=t4e(E=l5f5x@;
zKJws2y8Qce3M{H?IKinl&PW3(TuOL>UrM)4u4&c0Ai}^m(<7^k9ev@zST|R{+G6Xn
z{nwItaJ|47e6xkQINzPnoKo$EfceHRx2H&g3~Nh@m<%x%DfO4ZnKp2BDUPX|8*k-x
ze@{|GD7sQ)HKE%U-|hn09KK0RF(#d#%5}p!NGQDR!vIo$E-E`CI2)CvQFayFX3DB{@Jm-7Txs-L?k0d8300e*LgRvF*-nTRMh5
zmoy}MP}$OYRU~8onjbm(S2CL6{O}~cibh=zV*1n0bHwy31FITQyF0o9?GLz{p{n&%
z*+w_^+WCw&;<>A;3km_lqAT44>N|WowN99XfW6_0W87XQ>bHjGJj&4TM3Rdtu|M&E7EYC=B~|qJ6TJ#ZjNOM)^|tu2Wdb>;s4)(`nl&QNI{=}zZH<|PxMexle4p@>N@Y(6F29|h?;_3rxE0Y1qobObetEePpP6MRtGu`)nmwF8+BK&Bj;BezKf{B+iBJioN6J20npoFWZyPv~TZzl;aUzcpM
SA}3%(r=ww@{z>)8>;D0-9!YWl
literal 0
HcmV?d00001
diff --git a/pretext/GenFigs/qrcode/GoogleLogic.png b/pretext/GenFigs/qrcode/GoogleLogic.png
new file mode 100644
index 0000000000000000000000000000000000000000..7f70825006fc908f67257481581e6d19c150ef57
GIT binary patch
literal 580
zcmV-K0=xZ*P)X2M5QRSmq+Vhv2biNcH^`CZYUU`p0baI5^k%`2-O6TWVKt;-(ZcR;@r27lujB
zl{P?|Pe{>9iuFH!@h@Xi|3|?psVueW8OxW6V21Fb+v~1AG|(j4|$6
zx?YJgeF0($>x1v||V^fr9uMeP@IxX|hoO2z8+9-XFT8}xsv}-A6%ETtvT@w3(!h(VQ
zE#K=`{n*s$JB8ZcQ~aD(dizyBHdQkEQE++eF?09dtNNcq1#^@1>GGE$xzpeFo6P$N
z>c^uV;yxai#ZUw0*~wMZIp630Ue(FpXy=H%svnzb!?rT3c4%8a5u9;<3H29m$F}?E
SNui_w0000?X{GCj#ESvbJ7Yk_d{7Nw%}{ap=s
zbkfvI($Xpa5|{FfAN)-;>R+iSNm{^0HnWki-<}H3TciIB%p+(v5bJ??y#n>6_F}!s=s$x2SbRS)uNR?uNfTfrEa!(fDLxLju=gt1wRM37aNI?HE!NUaQ*?iXQuT6Qlm+#~flrIUt
zoHhGvQyx*zic3T#e;={=`)U-@0)Cq9z2g2B%Gs**eH|*7-KAw;N(rKx=2WKU0f-+r
z@B8`fVP*qpq7$sQra6@;N{{;hhq!cd;h|I0`-)U>3%}kI0B$eWE?Ha#(`;Q*^O#jA
z-(2&!vRItFbf44oz9!Wvk1OLxAPf9F;M?p^YkFUc0{YVEKCpL-<9)w$t@f3uFLl-g
zUrtn#QgNVX&Hma{fb}k$-%_xsEeKM8b;!dUi_^n&+U&1QWmWMr?6SN1GDG%3&snp-
zHih=G`P)77>82+5%f}$ys68K2c
z1V~F#T;dzw_?OYC|D#}(!q_S>E=i1%80$N!UG=x8Rx^78m~B8)em6~g7yxEAT&3%k
zDEqYlki=|5JG!2h`fTG=jQnT#Lba;?-qZkDzzUil2?1jMxnKagO4ln;+eq?d_HemS
z*DFwiwp-0Vir>MzY4dvKR@L8}GJ62CnZfFj-t3VScNgh;0m}3HDSuA#RnU|Rj0#(GNX^_}Z-cdsAp4
zDg6GJUdAkxOLV;gMUC<`zptzA)=*n~W_rvyhw=bFDbF%>ne_GLDgsCrvf
ze{ZTG!(!EXpIg_j8~+zqTB+{tKS->P)d295JlfC1*BvEA0S6zZjiI?4Wt7Zkje#U{1hBYN~+z$D>4!b!;)X|LDHXp1_U2L
zBuUZ?8VTi_k6--FxTt@l2GR(y+yEW}L}5t}6NC(aHLJdF3epUuIS8Uenn5G$JA&F(
z-#0bvAC@5lAzRX85X*tOPDYj8KD}j_>_yG!`mt0ocv!#yG<^WXy9q!?={f_oj-X=j
z`;P;4oq@8ww=A!ygdNr`4=}Z=zHf?>ZYY7ih8<#tr0i!vv+Db%*yg#^R%4V`S>utq
z&Oos*UkPQ#r8!7r^z~?0ec#l6o=a`DI*r#``4C-apxFGrOuMAj^d(6djjgKho5GuC
z+XBq63z|piIs-KrglsTmO&@myK+{{s?S_!AUfOdgAZBX1$w(?QUR%n#{Qg-~@t0ye
zlE+Km^3j*#^84pdb?)Uk$1~=Z@2{NmG^+0Qdbs*VU(4Kb;I^v1Z>sL`nAcSRf872M
zt*Y;vqQ)6&11IMFyOQ)utX*+sbRo^*fJ_a-{R`R{Q#|$h3Og0>&
z>jV__W{CH0yuDL@@Q!Ay>ied?+*7C()#dm9n=0w17|-&u{tXV-bqXrY!1M|l;~y(N
zG@04ax_&D4^`1h=mgbw^MoYhM*@*X{UG;ra>+t^l_s4YgbDlssE$MJFdlvK?w+wq=d9MNs`)C-#r!0Yy_AeP7Dh$o5x1L%=}rp-k$RN
zkLVM`2Mqf5BA%%0Vw5I;`BP%H4>hCfZ7B~yKm-F&zWm|Kls`|>bp>iQCx+$6&xyLO
zK%t#2kW-xLbzy2%edm9w)1FLecu$hkjTTcDkA_;QS~oq&%)
z+9pXl25AFWj{J@vd}nm(-zZq*7KbUqqKG7kp0(9|6{PO>WhnRT9`DOh0E73^ym=PMx4r<~?+a1V@idqo22;e=Fk)-^48VTs
z(QB(hRO;uX4i4cnvd=?gpAQ6a)NVtMIfbaRVej!?I{caE_eZyVDax&zF3LTHB`2Dm
z1=Xs)ZE8%toBb;y!i?YvJ_B2}hpAfiZBw34>hKCz+az5*WG{GYRo^ys7P41yd#0SZ
z)~#24+tfLRY<9)7$CID+cwdCNol{8R=KAa28a=hDZ=TBM6l^_@DD3kfb~A&}_pM4%
zx4m+f4FtjnhTu7BpI@Wv-Kc$jnytaivzsttEA$?6IVzu1xOFc9Y|VRyRjY59I)^td
iZ@VaGU%C5z8R{?h%Z&bQ20tPI0000X_9)f@f2B62gOGfxI0q81Scc8X#$_4)TbD^#~
zP=2p1BCaMP=<$weTlG9zRo^#7b~nY)SCc=7#KG}2tG;gv2#K2PJ?&E6dau!S2Z}w#
znsGVz(&7$ZpHOE4p&ks^(DgSYtN!eZI`rJ``vABMzdA*eN$W10SKH0r5>n`10et_E)KVl=8G(haP6bW1dHa(!<(k^w?)C
s*F(zV=xa}-ws84M+Uw&q<~gTP-)JO#&2PJ^TL1t607*qoM6N<$f>U`2`2YX_
literal 0
HcmV?d00001
diff --git a/pretext/GenFigs/qrcode/forloopvid.png b/pretext/GenFigs/qrcode/forloopvid.png
new file mode 100644
index 0000000000000000000000000000000000000000..f954d70fc1db081e4a7b2d4b8b1ec2475189b09e
GIT binary patch
literal 550
zcmV+>0@?kEP)q%zrx0QszpNyk-xdTKGVJHR}GrZhgt?tq!Oy>$Kel-rz#
z4+lYD`|G+QWi|rgS?_?>|9D+$>-Uq7X!6P~AG+VSrPdnKWPdyCsOt(8S_`~X$MOv!
zNz+l)pPK@FB>BtarEK-SXUz5#)#aD$d{iz8&QZ|1iyO(TU}T;f1l>A}~bTOV>rH#X
diff --git a/pretext/GeneralIntro/ThePythonProgrammingLanguage.ptx b/pretext/GeneralIntro/ThePythonProgrammingLanguage.ptx
index 7063970cc..ff6c7ed7a 100644
--- a/pretext/GeneralIntro/ThePythonProgrammingLanguage.ptx
+++ b/pretext/GeneralIntro/ThePythonProgrammingLanguage.ptx
@@ -74,7 +74,7 @@ My first program adds two numbers, 2 and 3:
Check your understanding
-
+
Source code is another name for:
@@ -113,7 +113,7 @@ My first program adds two numbers, 2 and 3:
-
+
What is the difference between a high-level programming language and a low-level programming language?
@@ -154,7 +154,7 @@ My first program adds two numbers, 2 and 3:
-
+
Pick the best replacements for 1 and 2 in the following sentence: When comparing compilers and interpreters, a compiler is like 1 while an interpreter is like 2.
diff --git a/pretext/GeneralIntro/intro-TheWayoftheProgram.ptx b/pretext/GeneralIntro/intro-TheWayoftheProgram.ptx
index 8d320b2c4..84fafc779 100644
--- a/pretext/GeneralIntro/intro-TheWayoftheProgram.ptx
+++ b/pretext/GeneralIntro/intro-TheWayoftheProgram.ptx
@@ -1,7 +1,7 @@
The Way of the Program
-
The goal of this book is to be really awesome, and if there's time after that I guess we can also teach you to think like a computer scientist. This
+
The goal of this book is to teach you to think like a computer scientist. This
way of thinking combines some of the best features of mathematics, engineering,
and natural science. Like mathematicians, computer scientists use formal
languages to denote ideas (specifically computations). Like engineers, they
From 98bd4e55005963e54f37afc782040e06511f0258 Mon Sep 17 00:00:00 2001
From: metesaka <61266931+metesaka@users.noreply.github.com>
Date: Mon, 12 Jun 2023 16:21:09 -0600
Subject: [PATCH 30/90] Update ThewhileStatement.rst
user input does not work with codelens
---
_sources/MoreAboutIteration/ThewhileStatement.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/_sources/MoreAboutIteration/ThewhileStatement.rst b/_sources/MoreAboutIteration/ThewhileStatement.rst
index 7b68775de..8d08fa036 100644
--- a/_sources/MoreAboutIteration/ThewhileStatement.rst
+++ b/_sources/MoreAboutIteration/ThewhileStatement.rst
@@ -101,7 +101,7 @@ The same program in codelens will allow you to observe the flow of execution.
.. codelens:: ch07_while3
""" Return the sum of 1+2+3 ... n """
- aBound = int(input("Please give a number n: "))
+ aBound = 10
theSum = 0
aNumber = 1
while aNumber <= aBound:
From 091c6eeaa7c22820255cff934ac552c09e3ef2fc Mon Sep 17 00:00:00 2001
From: robotuw
Date: Tue, 13 Jun 2023 11:42:43 -0600
Subject: [PATCH 31/90] Bug Test
Checking if simply changing codelens activities to activecode fixes the issue of them not showing up in the Runestone hosted instance.
---
pretext/Strings/TraversalandtheforLoopByIndex.ptx | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/pretext/Strings/TraversalandtheforLoopByIndex.ptx b/pretext/Strings/TraversalandtheforLoopByIndex.ptx
index baaa97702..fbaead88e 100644
--- a/pretext/Strings/TraversalandtheforLoopByIndex.ptx
+++ b/pretext/Strings/TraversalandtheforLoopByIndex.ptx
@@ -5,7 +5,7 @@
These positions can be used together with the indexing operator to access the individual
characters in the string.
Consider the following codelens example.
-
+
fruit = "apple"
for idx in range(5):
@@ -27,7 +27,7 @@ for idx in range(len(fruit)):
You may also note that iteration by position allows the programmer to control the direction of the
traversal by changing the sequence of index values. Recall that we can create ranges that count down as
well as up so the following code will print the characters from right to left.
Recall that the for loop processes each item in a list. Each item in
+ turn is (re-)assigned to the loop variable, and the body of the loop is executed.
+ We saw this example in an earlier chapter.
+
+
+for f in ["Joe", "Amy", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]:
+ print("Hi", f, "Please come to my party on Saturday")
+
+
+
We have also seen iteration paired with the update idea to form the accumulator pattern. For example, to compute
+ the sum of the first n integers, we could create a for loop using the range to produce the numbers 1 through n.
+ Using the accumulator pattern, we can start with a running total variable initialized to 0 and on each iteration, add the current value of the loop
+ variable. A function to compute this sum is shown below.
To review, the variable theSum is called the accumulator. It is initialized to zero before we start the loop. The loop variable, aNumber will take on the values produced by the range(1, aBound + 1) function call. Note that this produces all the integers from 1 up to the value of aBound. If we had not added 1 to aBound, the range would have stopped one value short since range does not include the upper bound.
+
The assignment statement, theSum = theSum + aNumber, updates theSum each time through the loop. This accumulates the running total. Finally, we return the value of the accumulator.
+
+ Check Your Understanding
+
+
+
+
The following code contains an nested loop. How many times will the phrase We made it here! be printed on the console?
+
+
+def printnums(x,y):
+ for h in range(y):
+ print("We made it here!")
+ for i in range(x):
+ print("We made it here!")
+
+printnums(5, 3)
+
+
+
+
+
+
+
5
+
+
+ This is how many times the inner loop will print for each iteration of the outer loop.
+
+
+
+
+
8
+
+
+ Keep in mind that the inner loop is part of the body of the outer loop.
+
+
+
+
+
15
+
+
+ The inner loop will print a total of 15 times; however the outer loop is also printing the same phrase.
+
+
+
+
+
18
+
+
+ Correct! The nested loop will be run 3 times, making a total of 18.
+
+
+
+
+
20
+
+
+ Pay attention to the order of x and y
+
+
+
+
+
diff --git a/pretext/ComplexLogic/toctree.ptx b/pretext/ComplexLogic/toctree.ptx
new file mode 100644
index 000000000..9601f6732
--- /dev/null
+++ b/pretext/ComplexLogic/toctree.ptx
@@ -0,0 +1,21 @@
+
+
+4Complex Logic
+4
+
+4
+4
+4
+4
+
+4
+4
+4
+4
+4
+4
+4
+4
+4
+4
+
diff --git a/pretext/Selection/BooleanFunctions.ptx b/pretext/Functions/BooleanFunctions.ptx
similarity index 100%
rename from pretext/Selection/BooleanFunctions.ptx
rename to pretext/Functions/BooleanFunctions.ptx
diff --git a/pretext/Functions/toctree.ptx b/pretext/Functions/toctree.ptx
index a67c2ddc1..d636c2e55 100644
--- a/pretext/Functions/toctree.ptx
+++ b/pretext/Functions/toctree.ptx
@@ -7,6 +7,7 @@
4
4
4
+4
4
4
4
diff --git a/pretext/MoreAboutIteration/2DimensionalIterationImageProcessing.ptx b/pretext/Iteration/2DimensionalIterationImageProcessing.ptx
similarity index 100%
rename from pretext/MoreAboutIteration/2DimensionalIterationImageProcessing.ptx
rename to pretext/Iteration/2DimensionalIterationImageProcessing.ptx
diff --git a/pretext/MoreAboutIteration/AlgorithmsRevisited.ptx b/pretext/Iteration/AlgorithmsRevisited.ptx
similarity index 100%
rename from pretext/MoreAboutIteration/AlgorithmsRevisited.ptx
rename to pretext/Iteration/AlgorithmsRevisited.ptx
diff --git a/pretext/MoreAboutIteration/BreakAndContinue.ptx b/pretext/Iteration/BreakAndContinue.ptx
similarity index 81%
rename from pretext/MoreAboutIteration/BreakAndContinue.ptx
rename to pretext/Iteration/BreakAndContinue.ptx
index 1c0420543..8f13f7198 100644
--- a/pretext/MoreAboutIteration/BreakAndContinue.ptx
+++ b/pretext/Iteration/BreakAndContinue.ptx
@@ -3,7 +3,7 @@
break and continue
In loops, we sometimes want to traverse until we reach a certain value.
- We could make some sort of loop condition with a boolean that is toggled as True once we
+ We could make a loop condition with a boolean that is toggled as True once we
reach that value, but there's an easier way: the break statement.
When a break statement is reached, the loop immediately ends and proceeds with the code after the loop.
@@ -11,10 +11,12 @@
-for i in range(0, 10):
+i = 0
+while i < 10:
if i == 5:
break
print(i)
+ i += 1
@@ -24,13 +26,15 @@ for i in range(0, 10):
-for i in range(0, 10):
+i = 0
+while i < 10:
if i == 5:
continue
print(i)
+ i += 1
Notice the difference between the activecode example above for break and this example with continue.
- Neither loop reaches 5, but in the loop with continue, it continues iterating after where 5 would have been.
+ Neither loop prints 5, but in the loop with continue, it continues iterating after where 5 would have been.
diff --git a/pretext/MoreAboutIteration/Exercises.ptx b/pretext/Iteration/Exercises.ptx
similarity index 100%
rename from pretext/MoreAboutIteration/Exercises.ptx
rename to pretext/Iteration/Exercises.ptx
diff --git a/pretext/MoreAboutIteration/FlowofExecutionofthewhileLoop.ptx b/pretext/Iteration/FlowofExecutionofthewhileLoop.ptx
similarity index 82%
rename from pretext/MoreAboutIteration/FlowofExecutionofthewhileLoop.ptx
rename to pretext/Iteration/FlowofExecutionofthewhileLoop.ptx
index 0e6ec1c18..674266a21 100644
--- a/pretext/MoreAboutIteration/FlowofExecutionofthewhileLoop.ptx
+++ b/pretext/Iteration/FlowofExecutionofthewhileLoop.ptx
@@ -1,10 +1,10 @@
Flow of Execution of the while Loop
-
As before with ``if``, loops allow us as programmers to manipulate the control flow of a Python program.
+
As before with if, loops allow us as programmers to manipulate the control flow of a Python program.
We can now possibly skip a portion of code, or choose to repeat it an indefinite number of times.
The flowchart below provides the general sequence of steps that govern execution of a while loop.
-
+
A codelens demonstration is a good way to help you visualize exactly how the flow of control
works with the while loop. Try stepping forward and backward through the program by pressing
the buttons. You can see the value of count change as the loop iterates through the values from 10 to 0.
diff --git a/pretext/MoreAboutIteration/Glossary.ptx b/pretext/Iteration/Glossary.ptx
similarity index 100%
rename from pretext/MoreAboutIteration/Glossary.ptx
rename to pretext/Iteration/Glossary.ptx
diff --git a/pretext/MoreAboutIteration/ImageProcessingonYourOwn.ptx b/pretext/Iteration/ImageProcessingonYourOwn.ptx
similarity index 100%
rename from pretext/MoreAboutIteration/ImageProcessingonYourOwn.ptx
rename to pretext/Iteration/ImageProcessingonYourOwn.ptx
diff --git a/pretext/Lists/Listsandforloops.ptx b/pretext/Iteration/Listsandforloops.ptx
similarity index 98%
rename from pretext/Lists/Listsandforloops.ptx
rename to pretext/Iteration/Listsandforloops.ptx
index 0d84e038d..872c053ab 100644
--- a/pretext/Lists/Listsandforloops.ptx
+++ b/pretext/Iteration/Listsandforloops.ptx
@@ -1,6 +1,6 @@
- Lists and for loops
+ Traversing lists with the for loop
It is also possible to perform list traversal using iteration by item as well as iteration by index.
diff --git a/pretext/MoreAboutIteration/NewtonsMethod.ptx b/pretext/Iteration/NewtonsMethod.ptx
similarity index 95%
rename from pretext/MoreAboutIteration/NewtonsMethod.ptx
rename to pretext/Iteration/NewtonsMethod.ptx
index 755a5b205..7a46fbdbe 100644
--- a/pretext/MoreAboutIteration/NewtonsMethod.ptx
+++ b/pretext/Iteration/NewtonsMethod.ptx
@@ -21,14 +21,14 @@ better = 1/2 * (approx + n/approx)
calculation yielding a better result.
- n = 100
- howmany = 10
+n = 100
+howmany = 10
- approx = 0.5 * n
- for i in range(howmany):
- betterapprox = 0.5 * (approx + n/approx)
- approx = betterapprox
- prin(betterapprox)
+approx = 0.5 * n
+for i in range(howmany):
+ betterapprox = 0.5 * (approx + n/approx)
+ approx = betterapprox
+prin(betterapprox)
diff --git a/pretext/MoreAboutIteration/RandomlyWalkingTurtles.ptx b/pretext/Iteration/RandomlyWalkingTurtles.ptx
similarity index 100%
rename from pretext/MoreAboutIteration/RandomlyWalkingTurtles.ptx
rename to pretext/Iteration/RandomlyWalkingTurtles.ptx
diff --git a/pretext/MoreAboutIteration/SentinelValuesAndValidation.ptx b/pretext/Iteration/SentinelValuesAndValidation.ptx
similarity index 95%
rename from pretext/MoreAboutIteration/SentinelValuesAndValidation.ptx
rename to pretext/Iteration/SentinelValuesAndValidation.ptx
index fb2201e90..cbc33af57 100644
--- a/pretext/MoreAboutIteration/SentinelValuesAndValidation.ptx
+++ b/pretext/Iteration/SentinelValuesAndValidation.ptx
@@ -3,7 +3,7 @@
Other uses of whileSentinel Values
-
The indefinite loops provided by the ``while`` statement are common in the real world.
+
The indefinite loops provided by the while statement are common in the real world.
@@ -86,8 +86,8 @@
division by zero and tell the user that you can't compute an average without data.
-
This program doesn't display the amounts to two decimal places. In the next chapter you will
- see the that will do the trick.
+
This program doesn't display the amounts to two decimal places. Thankfully, you already know how to fix this issue.
+ Recall how you learned to format floats to a specific number of decimal points in .
Check your understanding
@@ -125,7 +125,7 @@
that asks a yes-or-no question. In this case, you want to make sure that the person using
your program enters either a Y for yes or N for no (in either upper or lower case).
Here is a program that uses a while loop to keep asking until it receives a valid answer.
- As a preview of coming attractions, it uses
+ Note that it uses
the upper() method which is described in to convert a string to upper case.
When you run the following code, try typing something other than Y or N to see how the code reacts:
diff --git a/pretext/MoreAboutIteration/SimpleTables.ptx b/pretext/Iteration/SimpleTables.ptx
similarity index 100%
rename from pretext/MoreAboutIteration/SimpleTables.ptx
rename to pretext/Iteration/SimpleTables.ptx
diff --git a/pretext/MoreAboutIteration/The3n1Sequence.ptx b/pretext/Iteration/The3n1Sequence.ptx
similarity index 99%
rename from pretext/MoreAboutIteration/The3n1Sequence.ptx
rename to pretext/Iteration/The3n1Sequence.ptx
index 2c8cdcaa4..40e4c4150 100644
--- a/pretext/MoreAboutIteration/The3n1Sequence.ptx
+++ b/pretext/Iteration/The3n1Sequence.ptx
@@ -47,7 +47,7 @@
You'll notice that if you don't stop when you reach one, the sequence gets into
its own loop: 1, 4, 2, 1, 4, 2, 1, 4, and so on. One possibility is that there might
be other cycles that we just haven't found.
-
+
diff --git a/pretext/MoreAboutIteration/TheforLoop.ptx b/pretext/Iteration/TheforLoop.ptx
similarity index 79%
rename from pretext/MoreAboutIteration/TheforLoop.ptx
rename to pretext/Iteration/TheforLoop.ptx
index d98fc4484..3b4d6bc78 100644
--- a/pretext/MoreAboutIteration/TheforLoop.ptx
+++ b/pretext/Iteration/TheforLoop.ptx
@@ -2,7 +2,7 @@
The for loop
The while statement is a general-purpose tool for iteration, and is necessary for any instance of iteration where we don't know how many repetitions will be needed.
-However, if we do know how many are needed, there is a more efficient method: the for statement.
+However, if we do know how many are needed, there is a more efficient approach: the for statement.
As a simple example, let's say we have some friends, and
we'd like to send them each an email inviting them to our party. We
don't quite know how to send email yet, so for the moment we'll just print a
@@ -15,12 +15,13 @@ message for each friend.
Take a look at the output produced when you press the run button. There is one line printed for each friend. Here's how it works:
-
name in this for statement is the loop variable.
-
The list of names in the square brackets is a regular list. Later we'll see that other types besides lists can be put in this spot.
-
Line 2 is the loop body. Like with while, the loop body is always indented. The loop body is performed one time for each name in the list.
+
name is the loop variable in this case.
+
Frustratingly, in here is not the same as the keyword used to check for membership. This just a necessary part of every for loop construction and not an operator.
+
The list of names in the square brackets is a regular list. Later we'll see that other types besides lists can be put in this spot.
+
Line 2 is the loop body. Like with while, the loop body is always indented. The loop body is performed one time for each name in the list.
On each iteration or pass of the loop, a check is done to see if
there are still more items to be processed. If there are none left (this is
- called the terminating condition of the loop), the loop has finished.
+ called the terminating condition of the loop), the loop has finished.
Program execution continues at the next statement after the loop body.
If there are items still to be processed, the loop variable is updated to
refer to the next item in the list. This means, in this case, that the loop
@@ -34,10 +35,10 @@ message for each friend.
Introduction of the for statement causes us to think about the types of iteration we have seen. The for statement will always iterate through a sequence of
values like the list of names for the party.
Since we know that it will iterate once for each value in the collection, it is often said that a for loop creates a
- definite iteration because we definitely know how many times we are going to iterate. On the other
+ definite iteration because we definitely know how many times we are going to iterate. On the other
hand, the while statement is dependent on a condition that needs to evaluate to False in order
for the loop to terminate. Since we do not necessarily know when this will happen, it creates what we
- call indefinite iteration. Indefinite iteration simply means that we don't know how many times we will repeat but eventually the condition
+ call indefinite iteration. Indefinite iteration simply means that we don't know how many times we will repeat but eventually the condition
controlling the iteration will fail and the iteration will stop. (Unless we have an infinite loop which is of course a problem.)
@@ -49,7 +50,7 @@ message for each friend.
So any problem like "iterate this weather model run for 1000 cycles", or "search this
list of words", "check all integers up to 10000 to see which are prime" suggest that a for loop is best.
By contrast, if you are required to repeat some computation until some condition is
- met, as we did in this 3n + 1 problem, you'll need a while loop.
+ met, as we did in the 3n + 1 problem last week, you'll need a while loop.
What you will notice here is that the while loop is more work for
@@ -58,7 +59,7 @@ loop you have to control the loop variable yourself. You give it an initial val
for completion, and then make sure you change something in the body so that the loop
terminates.
- Check your understanding
+ Check your understanding
diff --git a/pretext/MoreAboutIteration/Theforlooprevisited.ptx b/pretext/Iteration/Theforlooprevisited.ptx
similarity index 100%
rename from pretext/MoreAboutIteration/Theforlooprevisited.ptx
rename to pretext/Iteration/Theforlooprevisited.ptx
diff --git a/pretext/MoreAboutIteration/TherangeFunction.ptx b/pretext/Iteration/TherangeFunction.ptx
similarity index 96%
rename from pretext/MoreAboutIteration/TherangeFunction.ptx
rename to pretext/Iteration/TherangeFunction.ptx
index 05f9fdbaa..a3bd46c3b 100644
--- a/pretext/MoreAboutIteration/TherangeFunction.ptx
+++ b/pretext/Iteration/TherangeFunction.ptx
@@ -1,11 +1,11 @@
The range Function
-
-
In our first example of a while loop, we counted down from 10 to 0. If we were to consider doing this with a for loop, we would need to construct our own series of numbers
+
+
In our first example of a while loop, we counted down from 10 to 0. If we were to consider doing this with a for loop, we would need to construct our own series of numbers
to loop through them.
It turns out that generating lists with a specific number of integers is a very common thing to do, especially when you
- want to write simple for loop controlled iteration. Even though you can use any four items, or any four integers for that matter, the conventional thing to do is to use a list of integers starting with 0.
+ want to write simple for loop controlled iteration. Even though you can use any four items, or any four integers for that matter, the conventional thing to do is to use a list of integers starting with 0.
In fact, these lists are so popular that Python gives us special built-in
range objects
that can deliver a sequence of values to
@@ -24,7 +24,7 @@ for x in range(10):
So to repeat something four times, a good Python programmer would do this:
- for i in range(10):
+ for i in range(4):
#do something
@@ -50,7 +50,7 @@ for x in range(10):
The range function is lazy: It produces the next element only when needed.
With a regular Python 3 interpreter, printing a range does not calculate all the elements.
To immediately calculate all the elements in a range,
- wrap the range in a list, like list(range(4)).
+ convert the range object to a list, like list(range(4)).
Activecode is not designed to work on very long sequences, and it may allow you to be
sloppy, avoiding the list function, and see the elements in the range with print(range(4)).
diff --git a/pretext/MoreAboutIteration/ThewhileStatement.ptx b/pretext/Iteration/ThewhileStatement.ptx
similarity index 90%
rename from pretext/MoreAboutIteration/ThewhileStatement.ptx
rename to pretext/Iteration/ThewhileStatement.ptx
index 60b4e82c2..07e20b14d 100644
--- a/pretext/MoreAboutIteration/ThewhileStatement.ptx
+++ b/pretext/Iteration/ThewhileStatement.ptx
@@ -1,12 +1,9 @@
The while Statement
-
-
A basic building block of all programs is to be able to repeat some code
- over and over again. In computer science, we refer to this repetitive idea as iteration. In this section, we will explore some mechanisms for basic iteration.
-
The following figure shows the flow of control.
+
Let's look at our first Python statement that can be used to build an iteration. It is called the while statement. When used with other code it can be used to
- repeat code in a while loop. Similar to the if statement, it uses
+ repeat code in a while loop. Similar to the if statement, it uses
a boolean expression to control the flow of execution. The body of while (code indented one space in) will be repeated as long as the controlling boolean
expression evaluates to True.
Here is a simple example that counts down from 10 to 0.
@@ -22,20 +19,20 @@
-
count is a normal variable here, but since it is governing the while loop it is also called the loop variable.
+
count is a normal variable here, but since it is governing the while loop it is also called the loop variable.
-
Line 2 here is the loop condition. It must always be a boolean expression that will evaluate to False or True.
+
Line 2 here is the loop condition. It must always be a boolean expression that will evaluate to False or True.
-
Lines 3 and 4 are the loop body. The loop body is always
+
Lines 3 and 4 are the loop body. The loop body is always
indented. The indentation determines exactly what statements are "in the
loop". The loop body is run each time the loop is repeated.
On each iteration or pass of the loop, a check is done to see if
the loop condition is True (if count is greater than zero). If it is not (this is
- called the terminating condition of the loop), the loop has finished.
+ called the terminating condition of the loop), the loop has finished.
Program execution continues at the next statement after the loop body.
@@ -66,7 +63,7 @@
source of amusement for computer scientists is the observation that the
directions written on the back of the shampoo bottle (lather, rinse, repeat) create an infinite loop.
-
We can use the while loop to create any type of iteration we wish, making more general-purpose than the for loop we'll learn next week.
+
We can use the while loop to create any type of iteration we wish, making it more general-purpose than the for loop we'll learn next week.
For example, let us consider a program that adds all numbers from 1 to n. To do this, we will create a variable called aNumber and initialize it to
1, the first number in the summation. Every iteration will add aNumber to the running total until all the values have been used.
In order to control the iteration, we must create a boolean expression that evaluates to True as long as we want to keep adding values to our
diff --git a/pretext/Strings/TraversalandtheforLoopByIndex.ptx b/pretext/Iteration/TraversalandtheforLoopByIndex.ptx
similarity index 98%
rename from pretext/Strings/TraversalandtheforLoopByIndex.ptx
rename to pretext/Iteration/TraversalandtheforLoopByIndex.ptx
index fbaead88e..9850cc364 100644
--- a/pretext/Strings/TraversalandtheforLoopByIndex.ptx
+++ b/pretext/Iteration/TraversalandtheforLoopByIndex.ptx
@@ -1,6 +1,6 @@
- Traversal and the for Loop: By Index
+ Traversing strings with the for Loop: By Index
It is also possible to use the range function to systematically generate the indices of the characters. The for loop can then be used to iterate over these positions.
These positions can be used together with the indexing operator to access the individual
characters in the string.
diff --git a/pretext/Strings/TraversalandtheforLoopByItem.ptx b/pretext/Iteration/TraversalandtheforLoopByItem.ptx
similarity index 98%
rename from pretext/Strings/TraversalandtheforLoopByItem.ptx
rename to pretext/Iteration/TraversalandtheforLoopByItem.ptx
index 55ae76d80..b92453001 100644
--- a/pretext/Strings/TraversalandtheforLoopByItem.ptx
+++ b/pretext/Iteration/TraversalandtheforLoopByItem.ptx
@@ -1,6 +1,6 @@
- Traversal and the for Loop: By Item
+ Traversing strings with the for Loop: By Item
A lot of computations involve processing a collection one item at a time. For strings this means
that we would like to process one character at a time.
Often we start at the beginning, select each character in turn, do something
diff --git a/pretext/Strings/TraversalandthewhileLoop.ptx b/pretext/Iteration/TraversalandthewhileLoop.ptx
similarity index 95%
rename from pretext/Strings/TraversalandthewhileLoop.ptx
rename to pretext/Iteration/TraversalandthewhileLoop.ptx
index c76db6f79..166c22bba 100644
--- a/pretext/Strings/TraversalandthewhileLoop.ptx
+++ b/pretext/Iteration/TraversalandthewhileLoop.ptx
@@ -2,7 +2,7 @@
Traversal and the while Loop
The while loop can also control the
- generation of the index values. Remember that the programmer is responsible for setting up the initial
+ generation of index values used to navigate strings or lists. The programmer is responsible for setting up the initial
condition, making sure that the condition is correct, and making sure that something changes inside the
body to guarantee that the condition will eventually fail.
diff --git a/pretext/MoreAboutIteration/accumulatorRevisited.ptx b/pretext/Iteration/accumulatorRevisited.ptx
similarity index 100%
rename from pretext/MoreAboutIteration/accumulatorRevisited.ptx
rename to pretext/Iteration/accumulatorRevisited.ptx
diff --git a/pretext/MoreAboutIteration/intro-IterationRevisited.ptx b/pretext/Iteration/intro-Iteration.ptx
similarity index 77%
rename from pretext/MoreAboutIteration/intro-IterationRevisited.ptx
rename to pretext/Iteration/intro-Iteration.ptx
index ea9399dc3..f34976720 100644
--- a/pretext/MoreAboutIteration/intro-IterationRevisited.ptx
+++ b/pretext/Iteration/intro-Iteration.ptx
@@ -1,11 +1,11 @@
- Iteration Revisited
+ Iteration Introduction
Computers are often used to automate repetitive tasks. Repeating identical or
similar tasks without making errors is something that computers do well and
people do poorly.
Repeated execution of a sequence of statements is called iteration. Because
iteration is so common, Python provides several language features to make it
- easier. easier. In this chapter we are going to look at two common forms of iteration: the while statement
+ easier. In this chapter we are going to look at two common forms of iteration: the while statement
and the for statement.
Slice also takes a third value, the step size.
- This specifies the rate at which we increment (if the step size is positive)
- or the rate at which we decrement (if the step size is negative).
- We can also specify -1 as the step term to slice with the values in reverse.
+
Slices also take an optional third value, the step size.
+ This specifies the rate at which the slice region increments (if the step size is positive)
+ or the rate at which it decrements (if the step size is negative).
+ It is also possible to specify -1 as the step term to slice with the values in reverse.
The Python type for storing true and false values is called bool, named
after the British mathematician, George Boole. George Boole created Boolean
Algebra, which is the basis of all modern computer arithmetic.
In order to write useful programs, we almost always need the ability to check
- conditions and change the behavior of the program accordingly. Selection statements, sometimes
- also referred to as conditional statements, give us this ability. The simplest form of selection is the if statement.
+ conditions and change the behavior of the program accordingly. Branching statements, sometimes
+ also referred to as conditional statements or Selection statements, give us this ability. The simplest form of branching is the if statement.
This is sometimes referred to as binary selection since there are two possible paths of execution.
@@ -32,11 +32,10 @@ else:
Flowchart of a if statement with an else
-
As with the function definition from the last chapter and other compound
- statements like for, the if statement consists of a header line and a body. The header
+
The if statement consists of a header line and a body. The header
line begins with the keyword if followed by a boolean expression and ends with
a colon (:).
-
The more indented statements that follow are called a block.
+
The more indented statements that follow are called a block. We will see this construction repeated several times in the future.
As a program executes, the interpreter always keeps track of which statement is
about to be executed. We call this the control flow, or the flow of
@@ -45,17 +44,17 @@ else:
as "Python's moving finger".
Control flow until now has been strictly top to bottom, one statement at a
- time. We call this type of control sequential. In Python flow is sequential as long as
+ time. We call this type of control sequential. In Python, flow is sequential as long as
successive statements are indented the same amount. The if statement
introduces indented sub-statements after the if heading.
-
Each if statement consists of a header line and a body. The header
+
-
Each of the statements inside the first block of statements is executed in order if the boolean
+
Back to the example, each of the statements inside the first block of statements is executed in order if the boolean
expression evaluates to True. The entire first block of statements
is skipped if the boolean expression evaluates to False, and instead
all the statements under the else clause are executed.
@@ -65,7 +64,7 @@ else:
the block after the heading. The if - else statement is an unusual compound statement because it
has more than one part at the same level of indentation as the if heading,
(the else clause, with its own indented block).
-
+
Check your understanding
diff --git a/pretext/Lists/ListMembership.ptx b/pretext/Selection/ListMembership.ptx
similarity index 100%
rename from pretext/Lists/ListMembership.ptx
rename to pretext/Selection/ListMembership.ptx
diff --git a/pretext/Selection/OmittingtheelseClauseUnarySelection.ptx b/pretext/Selection/OmittingtheelseClauseUnarySelection.ptx
index 5ad91c115..22fc45a44 100644
--- a/pretext/Selection/OmittingtheelseClauseUnarySelection.ptx
+++ b/pretext/Selection/OmittingtheelseClauseUnarySelection.ptx
@@ -1,7 +1,7 @@
Omitting the else Clause: Unary Selection
-
+
Flowchart of an if with no else
diff --git a/pretext/Strings/StringComparison.ptx b/pretext/Selection/StringComparison.ptx
similarity index 100%
rename from pretext/Strings/StringComparison.ptx
rename to pretext/Selection/StringComparison.ptx
diff --git a/pretext/Strings/Theinandnotinoperators.ptx b/pretext/Selection/Theinandnotinoperators.ptx
similarity index 100%
rename from pretext/Strings/Theinandnotinoperators.ptx
rename to pretext/Selection/Theinandnotinoperators.ptx
diff --git a/pretext/Selection/toctree.ptx b/pretext/Selection/toctree.ptx
index d1fc3942a..57bde1c71 100644
--- a/pretext/Selection/toctree.ptx
+++ b/pretext/Selection/toctree.ptx
@@ -1,14 +1,16 @@
-4Selection
+4Branching
4
4
4
4
4
+4
+4
+4
4
4
-4
4
4
diff --git a/pretext/Strings/StringMethods.ptx b/pretext/Strings/StringMethods.ptx
index 8ee74a412..959fcf5a1 100644
--- a/pretext/Strings/StringMethods.ptx
+++ b/pretext/Strings/StringMethods.ptx
@@ -198,17 +198,6 @@ print(tt)
Like rfind except causes a runtime error if item is not found
-
-
- format
-
-
- substitutions
-
-
- Involved! See , below
-
-
You should experiment with these
@@ -335,169 +324,4 @@ print(s[1] * s.index("n"))
-
- F-Strings
-
In grade school quizzes a common convention is to use fill-in-the blanks. For instance,
-
-
Hello _____!
-
-
and you can fill in the name of the person greeted, and combine
- given text with a chosen insertion. We use this as an analogy:
- Python has a similar
- construction, called a formatted string or an f-string. An f-string makes
- substitutions into places in a string
- enclosed in braces. Run this code:
The string has been formatted in a new way. We have included an f before the starting quotation mark.
- Such a string is called an f-string. Places where
- braces are embedded are replaced by the value of the expression inside the braces. There are many
- variations on the syntax between the braces. In this case we use
- the syntax where the first (and only) location in the string with
- braces has the variable person. When this code is evaluated, the value of the person variable is placed in the string in this location.
-
In the code above, this new string is assigned to the identifier
- greeting, and then the string is printed.
-
The identifier
- greeting was introduced to break the operations into a clearer
- sequence of steps. However, since the value of greeting is only
- referenced once, it can be eliminated with the more concise
- version:
There can be multiple substitutions, with data of any type.
- Next we use floats. Try original price $2.50 with a 7% discount:
-
-
-origPrice = float(input('Enter the original price: $'))
-discount = float(input('Enter discount percentage: '))
-newPrice = (1 - discount/100)*origPrice
-calculation = f'${origPrice} discounted by {discount}% is ${newPrice}.'
-print(calculation)
-
-
-
If you used the data suggested, this result is not satisfying.
- Prices should appear with exactly two places beyond the decimal point,
- but that is not the default way to display floats.
-
F-strings can give further information inside the braces
- showing how to specially format data.
- In particular floats can be shown with a specific number of decimal places.
- For two decimal places, put :.2f inside the braces but after the variable name for the monetary values:
-
-
-origPrice = float(input('Enter the original price: $'))
-discount = float(input('Enter discount percentage: '))
-newPrice = (1 - discount/100)*origPrice
-calculation = f'${origPrice:.2f} discounted by {discount}% is ${newPrice:.2f}.'
-print(calculation)
-
-
-
The 2 in the format modifier can be replaced by another integer to round to that
- specified number of digits.
-
A technical point: Since braces have special meaning in a format
- string, there must be a special rule if you want braces to actually
- be included in the final formatted string. The rule is to double
- the braces: { { and }}. For example mathematical set
- notation uses braces. The initial and final doubled
- braces in the format string below generate literal braces in the
- formatted string:
-
a = 5
-b = 9
-setStr = f'The set is {{ {a},{b} }}.'
-print(setStr)
-
Unfortunately, at the time of this writing, the ActiveCode format implementation has a bug,
- printing doubled braces, but standard Python prints {5, 9}.
-
-
-
What is printed by the following statements?
-
-
-x = 2
-y = 6
-print(f'sum of {x} and {y} is {x+y}; product: {x*y}.')
-
-
-
-
-
-
-
Nothing - it causes an error
-
-
- It is legal format syntax.
-
-
-
-
-
sum of {} and {} is {}; product: {}.
-
-
- Put the value of each expression in place of the braces.
-
-
-
-
-
In grade school quizzes a common convention is to use fill-in-the blanks. For instance,
+
+
Hello _____!
+
+
and you can fill in the name of the person greeted, and combine
+ given text with a chosen insertion. We use this as an analogy:
+ Python has a similar
+ construction, called a formatted string or an f-string. An f-string makes
+ substitutions into places in a string
+ enclosed in braces. Run this code:
The string has been formatted in a new way. We have included an f before the starting quotation mark.
+ Such a string is called an f-string. Places where
+ braces are embedded are replaced by the value of the expression inside the braces. There are many
+ variations on the syntax between the braces. In this case we use
+ the syntax where the first (and only) location in the string with
+ braces has the variable person. When this code is evaluated, the value of the person variable is placed in the string in this location.
+
In the code above, this new string is assigned to the identifier
+ greeting, and then the string is printed.
+
The identifier
+ greeting was introduced to break the operations into a clearer
+ sequence of steps. However, since the value of greeting is only
+ referenced once, it can be eliminated with the more concise
+ version:
There can be multiple substitutions, with data of any type.
+ Next we use floats. Try original price $2.50 with a 7% discount:
+
+
+origPrice = float(input('Enter the original price: $'))
+discount = float(input('Enter discount percentage: '))
+newPrice = (1 - discount/100)*origPrice
+calculation = f'${origPrice} discounted by {discount}% is ${newPrice}.'
+print(calculation)
+
+
+
If you used the data suggested, this result is not satisfying.
+ Prices should appear with exactly two places beyond the decimal point,
+ but that is not the default way to display floats.
+
F-strings can give further information inside the braces
+ showing how to specially format data.
+ In particular, floats can be shown with a specific number of decimal places.
+ For two decimal places, put :.2f inside the braces but after the variable name for the monetary values:
+
+
+origPrice = float(input('Enter the original price: $'))
+discount = float(input('Enter discount percentage: '))
+newPrice = (1 - discount/100)*origPrice
+calculation = f'${origPrice:.2f} discounted by {discount}% is ${newPrice:.2f}.'
+print(calculation)
+
+
+
The 2 in the format modifier can be replaced by another integer to round to that
+ specified number of digits.
+
A technical point: Since braces have special meaning in a format
+ string, there must be a special rule if you want braces to actually
+ be included in the final formatted string. The rule is to double
+ the braces: { { and }}. For example mathematical set
+ notation uses braces. The initial and final doubled
+ braces in the format string below generate literal braces in the
+ formatted string:
+
a = 5
+b = 9
+setStr = f'The set is {{ {a},{b} }}.'
+print(setStr)
+
Unfortunately, at the time of this writing, the ActiveCode format implementation has a bug,
+ printing doubled braces, but standard Python prints {5, 9}.
+
+
+
What is printed by the following statements?
+
+
+x = 2
+y = 6
+print(f'sum of {x} and {y} is {x+y}; product: {x*y}.')
+
+
+
+
+
+
+
Nothing - it causes an error
+
+
+ It is legal format syntax.
+
+
+
+
+
sum of {} and {} is {}; product: {}.
+
+
+ Put the value of each expression in place of the braces.
+
+
+
+
+
Nested lists can be traversed the say way as other lists. However, the code to do so can easily get complicated and confusing. In this section let us
+ examine several example programs that perform this task.
+
+
The following program concerns a list of lists of names. In some cases, we may want to take nested list data and "un-nest" it. To do this, we need to
+ iterate through the outer list, and then construct another loop to iterate through each name in each sublist. In this program's case, we are simply printing each
+ name as we encounter it.
+
+
+names = [["Thomas", "Abraham", "George"], ["Theodore", "Grover", "William"], ["Franklin", "Dwight", "John", "Harry"], ["George", "Bill"]]
+for sublist in names:
+ for name in sublist:
+ print(name)
+
+
+
Nested lists can also be navigated by index rather than by value. This complicates the code somewhat, but gives us more flexibility for what can be done to each item.
+ In this example program, we visit each name and turn it lowercase.
Note that in the above program it is very important that we use len(names[sublist_index]) in the second range call. Because the nested lists in this example
+ do not have the same length, we have to check the length of each sublist when setting up our nested for loop bounds. If we do not do this carefully, then we can easily
+ miss data or get an out of bounds exception. Consider a different, erroneous example:
Nested lists can be used in many different contexts, but one more common use is to model 2D grids of data. Here is one last example that treats nested lists as a 2D coordinate plane
+ and finds the location of a single value in that plane. Note this example reverses the y axis, so y values increase as you travel downward. This is to match the indexing on the lists,
+ though we could model this as a more familiar coordinate system with some small changes.
+
+
+coord = [['_', '_', '_', '_'],
+ ['_', '_', 'p', '_'],
+ ['_', '_', '_', '_'],
+ ['_', '_', '_', '_']]
+for y in range(len(names)):
+ for x in range(len(coord[y])):
+ if coord[y][x] == 'p':
+ print(f'p is as coordinates (x={x}, y={y})')
+
+
+
+ Check your understanding
+
+
+
+
What is printed by the following statements?
+
+
+alist = [ [4, [True, False], 6, 8], [888, 999] ]
+for a in alist:
+ for b in range(1, len(a)):
+ if type(a[b]) == type(a[b-1]):
+ print(a[b], end=" ")
+
+
+
+
+
+
+
8 999
+
+
+ Yes, you are correct.
+
+
+
+
+
4 6 8 888 999
+
+
+ You are correct that the code will treat the list with boolean value differently, but you are missing other aspects. Look again at the bounds of the inner loop.
+
+
+
+
+
4 True False 6 8 888 999
+
+
+ This would be the output for a full traversal of the data. However, this code cannot fully traverse the data since it has three levels of nesting and the code only reaches two levels.
+
+
+
+
+
4 [True, False] 6 8 888 999
+
+
+ This would be the correct output if the code traversed two levels of nesting and printed everything. However, the if statement is also doing something here.
+
+
+
+
+
diff --git a/pretext/ComplexLogic/intro_ComplexLogic.ptx b/pretext/ComplexLogic/intro_ComplexLogic.ptx
index a1e119c58..31d30702c 100644
--- a/pretext/ComplexLogic/intro_ComplexLogic.ptx
+++ b/pretext/ComplexLogic/intro_ComplexLogic.ptx
@@ -1,94 +1,8 @@
Complex Logic Introduction
-
Recall that the for loop processes each item in a list. Each item in
- turn is (re-)assigned to the loop variable, and the body of the loop is executed.
- We saw this example in an earlier chapter.
-
-
-for f in ["Joe", "Amy", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]:
- print("Hi", f, "Please come to my party on Saturday")
-
-
-
We have also seen iteration paired with the update idea to form the accumulator pattern. For example, to compute
- the sum of the first n integers, we could create a for loop using the range to produce the numbers 1 through n.
- Using the accumulator pattern, we can start with a running total variable initialized to 0 and on each iteration, add the current value of the loop
- variable. A function to compute this sum is shown below.
To review, the variable theSum is called the accumulator. It is initialized to zero before we start the loop. The loop variable, aNumber will take on the values produced by the range(1, aBound + 1) function call. Note that this produces all the integers from 1 up to the value of aBound. If we had not added 1 to aBound, the range would have stopped one value short since range does not include the upper bound.
-
The assignment statement, theSum = theSum + aNumber, updates theSum each time through the loop. This accumulates the running total. Finally, we return the value of the accumulator.
-
- Check Your Understanding
-
-
-
-
The following code contains an nested loop. How many times will the phrase We made it here! be printed on the console?
-
-
-def printnums(x,y):
- for h in range(y):
- print("We made it here!")
- for i in range(x):
- print("We made it here!")
-
-printnums(5, 3)
-
-
-
-
-
-
-
5
-
-
- This is how many times the inner loop will print for each iteration of the outer loop.
-
-
-
-
-
8
-
-
- Keep in mind that the inner loop is part of the body of the outer loop.
-
-
-
-
-
15
-
-
- The inner loop will print a total of 15 times; however the outer loop is also printing the same phrase.
-
-
-
-
-
18
-
-
- Correct! The nested loop will be run 3 times, making a total of 18.
-
-
-
-
-
20
-
-
- Pay attention to the order of x and y
-
-
-
-
+
Believe it or not, in the past seven weeks we've covered nearly all of the fundamental constructs within programming.
+ While there is certainly much more to learn and discover, virtually any programming language you will see in the future offers some form
+ of branching, looping, and function definition. That is not to say we have mastered these topics yet. This week of class and this chapter
+ focuses on revisiting these fundamental topics and deepening our mastery of them.
diff --git a/pretext/ComplexLogic/toctree.ptx b/pretext/ComplexLogic/toctree.ptx
index 9601f6732..61940cb1b 100644
--- a/pretext/ComplexLogic/toctree.ptx
+++ b/pretext/ComplexLogic/toctree.ptx
@@ -2,18 +2,15 @@
4Complex Logic
4
+4
+4
-4
-4
4
-4
-4
-4
-4
-4
-4
+4
4
+
+4
4
4
4
diff --git a/pretext/Debugging/intro-HowtobeaSuccessfulProgrammer.ptx b/pretext/Debugging/intro-HowtobeaSuccessfulProgrammer.ptx
index 6f79d7f52..32cc1ecd1 100644
--- a/pretext/Debugging/intro-HowtobeaSuccessfulProgrammer.ptx
+++ b/pretext/Debugging/intro-HowtobeaSuccessfulProgrammer.ptx
@@ -1,6 +1,6 @@
How to be a Successful Programmer
-
One of the most important skills you need to aquire to complete this book successfully is the ability to debug your programs. Debugging might be the most under-appreciated, and under-taught, skill in introductory computer science. For that reason we are introducing a series of debugging interludes. Debugging is a skill that you need to master over time, and some of the tips and tricks are specific to different aspects of Python programming. So look for additional debugging interludes throughout the rest of this book.
+
One of the most important skills you need to aquire to complete this book successfully is the ability to debug your programs. Debugging might be the most under-appreciated, and under-taught, skill in introductory computer science. For that reason we are including this debugging interlude. Debugging is a skill that you need to master over time, and some of the tips and tricks are specific to different aspects of Python programming.
Programming is an odd thing in a way. Here is why. As programmers we spend 99% of our time trying to get our program to work. We struggle, we stress, we spend hours deep in frustration trying to get our program to execute correctly. Then when we do get it going we celebrate, hand it in, and move on to the next homework assignment or programming task. But here is the secret, when you are successful, you are happy, your brain releases a bit of chemical that makes you feel good. You need to organize your programming so that you have lots of little successess. It turns out your brain doesn't care all that much if you have successfully written hello world, or a fast fourier transform (trust me its hard) you still get that little release that makes you happy. When you are happy you want to go on and solve the next little problem. Essentially I'm telling you once again, start small, get something small working, and then add to it.
Will add characters to the end of a file that has been opened for writing.
+
+
+ csv
+
An optional Python module that provides useful functions for interacting with data in the Comma Separated Value format.
+
+
+ Comma Separated Value
+
A format that text files can have. Promises that the file contains alphanumeric values separate by single commas and organized into one row of data per line.
+
+
+ reader
+
A function part of the csv module that creates an object for traversing csv file data.
+
+
+ writerow
+
A function part of the csv module that takes a list of data, formats it in the appropriate csv format, and writes it to a data file.
+
+
+ writerows
+
A function part of the csv module. Similar to writerow, but can write multiple rows of data at once if given a list of lists.
absolute file path
diff --git a/pretext/Files/ReadingCSV.ptx b/pretext/Files/ReadingCSV.ptx
new file mode 100644
index 000000000..3a91fe72a
--- /dev/null
+++ b/pretext/Files/ReadingCSV.ptx
@@ -0,0 +1,66 @@
+
+
+ Reading Files as csv
+
The climate change data file we have used as an example in this chapter has a more specific designation than just a .txt file. Because the file
+ consists of a series of values separated by commas, it can also be referred to as a Comma Separate Value file, or a .csv. Note that csv
+ files are still just text files, but knowing it is also a csv tells us something valuable about the structure of the data it contains. This makes it
+ easier to parse and interact with that data.
+
+
To interact with text files as csv's, we need to import the Python csv module and use it to create reader or writer objects.
+ This section focuses on reading csv, so we should use a reader. The reason we are interested in doing this is because the reader will automatically detect and remove
+ the commas separating values for us. Essentially, the reader will split the data up into lists for us. This makes it simpler to navigate and interact with the data in the file.
+
Let's see an example of this working.
+
+
+import csv
+with open("ccdata.csv", "r") as file:
+ csv_reader = csv.reader(file, delimiter=',')
+ for line in csv_reader:
+ print(line)
+ print(line[0]) # just years
+
+
+
+
Note that the value assigned to for loop line variable is a list rather than a single string like we would get with a standard file object. This allows us to acces column
+ data quickly with a single index value.
+
+
The following table describes the two csv functions you are most likely to want to use.
+
+
+
+
+ Method Name
+
+
+ Use
+
+
+ Explanation
+
+
+
+
+ reader
+
+
+ csv.reader(file_object)
+
+
+ Creates a csv reader object that automatically splits lines of data but can be looped through like a regular file object.
+
+
+
+
+ writer
+
+
+ csv.writer(file_object)
+
+
+ Creates a csv writer object that takes lists of strings and writes them to the provided file in the correct csv format.
+
+
+
+
+
diff --git a/pretext/Files/WritingCSV.ptx b/pretext/Files/WritingCSV.ptx
new file mode 100644
index 000000000..ee265ce73
--- /dev/null
+++ b/pretext/Files/WritingCSV.ptx
@@ -0,0 +1,44 @@
+
+
+ Writing Files as csv
+
We already introduced the csv module in the previous section. Let's examine some examples using a csv.writer object.
+
Like the reader object, the csv.writer function takes a opened file object. Once set up, the csv file can be written to with writerow.
+ Make note that writerow does not need an explicit newline character \n to know when to end a line of text. This sets it apart for the the regular file.write() function.
+
+
+import csv
+data = [["Column_1_Name","Column_2_Name","Column_3_Name"],
+ [1,2,3],
+ [50,40,23]
+]
+
+with open("new_file.csv", "w", newline='') as file:
+ csv_writer = csv.writer(file, delimiter=',')
+ for line in data:
+ csv_writer.writerow(line)
+
+
+
This program will create a file called new_file.csv with the contents:
You may have noticed there is one new piece of code in our with open(... line. The newline='' parameter is needed here to avoid adding extra blank lines to our output file.
+ Try running this code locally without that part to see the difference.
+
+
There is one other writer method you may find useful, which is writerows. This allows you to write multiple rows of data at the same time. When applied to the previous
+ example, it saves us from having to set up a loop.
+
+
+import csv
+
+data = [["Column_1_Name","Column_2_Name","Column_3_Name"],
+ [1,2,3],
+ [50,40,23]
+]
+
+with open("new_file.csv", "w", newline='') as file:
+ csv_writer = csv.writer(file, delimiter=',')
+ csv_writer.writerows(data)
+
+
+
diff --git a/pretext/Files/intro-WorkingwithDataFiles.ptx b/pretext/Files/intro-WorkingwithDataFiles.ptx
index ab952e8a3..9fa57818f 100644
--- a/pretext/Files/intro-WorkingwithDataFiles.ptx
+++ b/pretext/Files/intro-WorkingwithDataFiles.ptx
@@ -1,8 +1,8 @@
Working with Data Files
-
So far, the data we have used in this book have all been either coded right into the program, or have been entered by the user. In real life data reside in files.
-
For example, web pages, word processing documents, and all data that live in files. In this short chapter we will introduce the Python concepts necessary to use data from files in our programs.
+
So far, the data we have used in this book have all been either coded right into the program, or have been entered by the user. In real life, data reside in files.
+
For example, web pages, word processing documents, and all data that live in files. In this chapter we will introduce the Python concepts necessary to use data from files in our programs.
For our purposes, we will assume that our data files are text files–that is, files filled with characters. The Python programs that you write are stored as text files. We can create these files in any of a number of ways. For example, we could use a text editor to type in and save the data. We could also download the data from a website and then save it in a file. Regardless of how the file is created, Python will allow us to manipulate the contents.
In Python, we must open files before we can use them and close them when we are done with them. As you might expect, once a file is opened it becomes a Python object just like all other data. shows the functions and methods that can be used to open and close files.
Use the drawsquare function we wrote in this chapter in a program to draw
- the image shown below.
- Assume each side is 20 units.
- (Hint: notice that the turtle has already moved away from the ending point of the last
- square when the program ends.)
-
-
-
-
-
-import turtle
-
-def drawSquare(t, sz):
- """Get turtle t to draw a square of sz side"""
-
- for i in range(4):
- t.forward(sz)
- t.left(90)
-
-wn = turtle.Screen()
-wn.bgcolor("lightgreen")
-
-alex = turtle.Turtle()
-alex.color("pink")
-
-drawSquare(alex,20)
-
-wn.exitonclick()
-
-
-
-
-
-import turtle
-
-def drawSquare(t, sz):
- """Make turtle t draw a square of with side sz."""
- for i in range(4):
- t.forward(sz)
- t.left(90)
-
-wn = turtle.Screen() # Set up the window and its attributes
-wn.bgcolor("lightgreen")
-
-alex = turtle.Turtle() # create alex
-alex.color('hotpink')
-alex.pensize(3)
-
-for i in range(5):
- drawSquare(alex, 20) # Call the function to draw the square
- alex.penup()
- alex.forward(40) # move alex to the starting position for the next square
- alex.pendown()
-
-wn.exitonclick()
-
-
-
-
-
-
-
Write a program to draw this. Assume the innermost square is 20 units per side,
- and each successive square is 20 units bigger, per side, than the one inside it.
-
-
-
-
-
-
-
-
-
-
-
Write a non-fruitful function drawPoly(someturtle, somesides, somesize) which makes a turtle
- draw a regular polygon.
- When called with drawPoly(tess, 8, 50), it will draw a shape like this:
-
-
-
-
-
-
-
-
-
-
-import turtle
-
-def drawPoly(t, num_sides, side_length):
- for i in range(num_sides):
- t.forward(side_length)
- t.left(360/num_sides)
-
-wn = turtle.Screen() # Set up the window and its attributes
-wn.bgcolor("lightgreen")
-
-tess = turtle.Turtle()
-tess.color('hotpink')
-tess.pensize(3)
-
-drawPoly(tess, 8, 50)
-
-
-
-
-
-
-
Draw this pretty pattern.
-
-
-
-
-
-
-
-
-
-
-
The two spirals in this picture differ only by the turn angle. Draw both.
-
-
-
-
-
-
-
-
-
-
-import turtle
-
-def drawSpiral(t, angle):
- ''' takes a turtle, t, and an angle in degrees '''
- length = 1
- for i in range(84):
- t.forward(length)
- t.right(angle)
- length = length + 2
-
-
-wn = turtle.Screen() # Set up the window and its attributes
-wn.bgcolor("lightgreen")
-
-guido = turtle.Turtle() # create guido
-guido.color('blue')
-
-## draw the first spiral ##
-# position guido
-guido.penup()
-guido.backward(110)
-guido.pendown()
-
-# draw the spiral using a 90 degree turn angle
-drawSpiral(guido, 90)
-
-
-## draw the second spiral ##
-# position guido
-guido.home()
-guido.penup()
-guido.forward(90)
-guido.pendown()
-
-drawSpiral(guido, 89)
-
-
-
-
-
-
-
Write a non-fruitful function drawEquitriangle(someturtle, somesize) which calls drawPoly from the
- previous question to have its turtle draw a equilateral triangle.
-
-
-
-
-
-
-
-
Write a fruitful function sumTo(n) that returns the sum of all integer numbers up to and
including n. So sumTo(10) would be 1+2+3...+10 which would return the value 55. Use the
equation (n * (n + 1)) / 2.
-
+
def sumTo(n):
@@ -207,7 +26,7 @@ myTests().main()
-
+
from test import testEqual
@@ -226,11 +45,11 @@ print("The sum from 1 to 5 is",t)
-
+
Write a function areaOfCircle(r) which returns the area of a circle of radius r. Make sure you use the math module in your solution.
Extend your program above. Draw five stars, but between each, pick up the pen,
- move forward by 350 units, turn right by 144, put the pen down, and draw the next star.
- You'll get something like this (note that you will need to move to the left before drawing your first star in order to fit everything in the window):
-
-
What would it look like if you didn't pick up the pen?
-
-
-
-
-
-
-
-
-
-
Extend the star function to draw an n pointed star. (Hint: n must be an odd number greater or
- equal to 3).
Write a function called drawSprite that will draw a sprite. The function will need parameters for
- the turtle, the number of legs, and the length of the legs. Invoke the function to create a sprite
- with 15 legs of length 120.
-
-
-
-
-
-
-
-
+
Rewrite the function sumTo(n) that returns the sum of all integer numbers up to and
including n. This time use the accumulator pattern.
-
+
def sumTo(n):
@@ -351,7 +92,7 @@ myTests().main()
-
+
def sumTo(n):
sum = 0
@@ -370,37 +111,12 @@ print("The sum from 1 to 5 is",t)
-
-
-
Write a function called mySqrt that will approximate the square root of a number, call it n, by using
- Newton's algorithm.
- Newton's approach is an iterative guessing algorithm where the initial guess is n/2 and each subsequent guess
- is computed using the formula: newguess = (1/2) * (oldguess + (n/oldguess)).
-
-
-
-
-def mySqrt(n):
- # your code here ====
-from unittest.gui import TestCaseGui
-
-class myTests(TestCaseGui):
- def testOne(self):
- self.assertAlmostEqual(mySqrt(4.0),2.0,0,"Tested mySqrt on input 4.0")
- self.assertAlmostEqual(mySqrt(9.0),3.0,4,"Tested accuracy of mySqrt on input 3.0")
- self.assertAlmostEqual(mySqrt(36.0),6.0,5,"Tested accuracy of mySqrt on input 6.0")
- self.assertAlmostEqual(mySqrt(100.0),10.0,4,"Tested accuracy of mySqrt on input 10.0. Try iterating more times.")
-
-myTests().main()
-
-
-
-
+
Write a function called myPi that will return an approximation of PI (3.14159…). Use the Leibniz
approximation.
-
+
def myPi(iters):
@@ -411,7 +127,7 @@ myTests().main()
-
+
def myPi(iters):
''' Calculate an approximation of PI using the Leibniz
@@ -433,12 +149,12 @@ print(pi_approx)
-
+
Write a function called myPi that will return an approximation of PI (3.14159…). Use the Madhava
approximation.
Write a function called fancySquare that will draw a square with fancy corners (sprites on the corners). You should
- implement and use the drawSprite function from above. For an even more interesting look, how about adding small
- triangles to the ends of the sprite legs.
There was a whole program in to create a bar chart with specific data. Creating a bar chart is a useful idea in general. Write a non-fruitful function called barChart, that takes the numeric list of data as a parameter, and draws the bar chart. Write a full program calling this function.
- The current version of the drawBar function unfortuately draws the top of the bar through the bottom of the label. A nice elaboration is to make the label appear completely above the top line. To keep the spacing consistent you might pass an extra parameter to drawBar for the distance to move up. For the barChart function make that parameter be some small fraction of maxheight+border. The fill action makes this modification particularly tricky: You will want to move past the top of the bar and write before or after drawing and filling the bar.
-
-
-
-
-import turtle
-
-def drawBar(t, height):
- """ Get turtle t to draw one bar, of height. """
- t.begin_fill() # start filling this shape
- t.left(90)
- t.forward(height)
- t.write(str(height))
- t.right(90)
- t.forward(40)
- t.right(90)
- t.forward(height)
- t.left(90)
- t.end_fill() # stop filling this shape
-
-
-
-xs = [48, 117, 200, 240, 160, 260, 220] # here is the data
-maxheight = max(xs)
-numbars = len(xs)
-border = 10
-
-wn = turtle.Screen() # Set up the window and its attributes
-wn.setworldcoordinates(0-border, 0-border, 40*numbars+border, maxheight+border)
-wn.bgcolor("lightgreen")
-
-tess = turtle.Turtle() # create tess and set some attributes
-tess.color("blue")
-tess.fillcolor("red")
-tess.pensize(3)
-
-
-
-for a in xs:
- drawBar(tess, a)
-
-wn.exitonclick()
-
-
-
diff --git a/pretext/Functions/TheAccumulatorPattern.ptx b/pretext/Functions/TheAccumulatorPattern.ptx
index f875e2b51..4cf6f9576 100644
--- a/pretext/Functions/TheAccumulatorPattern.ptx
+++ b/pretext/Functions/TheAccumulatorPattern.ptx
@@ -2,7 +2,7 @@
The Accumulator Pattern
-
+
In the previous example, we wrote a function that computes the square of a number. The algorithm we used
in the function was simple: multiply the number by itself.
In this section we will reimplement the square function and use a different algorithm, one that relies on addition instead
@@ -136,7 +136,7 @@ def square(x):
-
+
A Variation on the Accumulator Pattern
diff --git a/pretext/Functions/UnitTesting.ptx b/pretext/Functions/UnitTesting.ptx
index e39b6a024..5d995f943 100644
--- a/pretext/Functions/UnitTesting.ptx
+++ b/pretext/Functions/UnitTesting.ptx
@@ -22,7 +22,9 @@
-
One way to implement unit tests in Python is with assert.
+
You have been following this pattern in the class so far, even if it is unconsciously. The test cases we give for each assessment can be thought of as unit tests.
+ We give these to you when the assessment is assigned because it is so helpful to have while you are writing code.
+
One way to implement unit tests in Python, the same way our test cases do it, is with assert.
In Python, a function is a named sequence of statements
that belong together. Their primary purpose is to help us
organize programs into chunks that match how we think about
diff --git a/pretext/Functions/toctree.ptx b/pretext/Functions/toctree.ptx
index d636c2e55..5dc551f0d 100644
--- a/pretext/Functions/toctree.ptx
+++ b/pretext/Functions/toctree.ptx
@@ -6,12 +6,11 @@
4
4
4
+4
4
-4
4
-4
-4
4
+4
+4
4
-4
diff --git a/pretext/GeneralIntro/toctree.ptx b/pretext/GeneralIntro/toctree.ptx
index 0c51b26fd..7458c8409 100644
--- a/pretext/GeneralIntro/toctree.ptx
+++ b/pretext/GeneralIntro/toctree.ptx
@@ -15,5 +15,4 @@
4
4
4
-4
diff --git a/pretext/IntroRecursion/ProgrammingExercises.ptx b/pretext/IntroRecursion/ProgrammingExercises.ptx
index 13afd1da1..f0aa6dbe5 100644
--- a/pretext/IntroRecursion/ProgrammingExercises.ptx
+++ b/pretext/IntroRecursion/ProgrammingExercises.ptx
@@ -54,123 +54,43 @@ myTests().main()
-
-
Modify the recursive tree program using one or all of the following
- ideas:
-
-
-
-
Modify the thickness of the branches so that as the branchLen
- gets smaller, the line gets thinner.
-
-
-
Modify the color of the branches so that as the branchLen gets
- very short it is colored like a leaf.
-
-
-
Modify the angle used in turning the turtle so that at each branch
- point the angle is selected at random in some range. For example
- choose the angle between 15 and 45 degrees. Play around to see
- what looks good.
-
-
-
Modify the branchLen recursively so that instead of always
- subtracting the same amount you subtract a random amount in some
- range.
-
-
-
-
If you implement all of the above ideas you will have a very
- realistic looking tree.
-
-
-
-
-
-
-
-
-
-
Find or invent an algorithm for drawing a fractal mountain. Hint: One
- approach to this uses triangles again.
-
-
-
-
-
-
-
-
Write a recursive function to compute the Fibonacci sequence. How
does the performance of the recursive function compare to that of an
iterative version?
-
-
-
-
-
-
-
-
-
Implement a solution to the Tower of Hanoi using three stacks to keep
- track of the disks.
-
-
-
-
-
-
-
-
-
-
Using the turtle graphics module, write a recursive program to
- display a Hilbert curve.
-
-
-
-
-
-
-
-
-
-
Using the turtle graphics module, write a recursive program to
- display a Koch snowflake.
-
-
+
-
+
Write a program to solve the following problem: You have two jugs: a
4-gallon jug and a 3-gallon jug. Neither of the jugs have markings on
them. There is a pump that can be used to fill the jugs with water.
How can you get exactly two gallons of water in the 4-gallon jug?
-
+
-
+
Generalize the problem above so that the parameters to your solution
include the sizes of each jug and the final amount of water to be
left in the larger jug.
-
+
-
+
Write a program that solves the following problem: Three missionaries
and three cannibals come to a river and find a boat that holds two
@@ -180,25 +100,25 @@ myTests().main()
crossings that will get everyone safely to the other side of the
river.
-
+
-
+
Modify the Tower of Hanoi program using turtle graphics to animate
the movement of the disks. Hint: You can make multiple turtles and
have them shaped like rectangles.
-
+
-
+
Pascal's triangle is a number triangle with numbers arranged in
staggered rows such that
@@ -218,7 +138,7 @@ myTests().main()
should accept a parameter that tells how many rows of the triangle to
print.
-
+
diff --git a/pretext/IntroRecursion/toctree.ptx b/pretext/IntroRecursion/toctree.ptx
index d16ca3cb8..5b67d043d 100644
--- a/pretext/IntroRecursion/toctree.ptx
+++ b/pretext/IntroRecursion/toctree.ptx
@@ -7,5 +7,4 @@
4
4
4
-4
diff --git a/pretext/Iteration/Exercises.ptx b/pretext/Iteration/Exercises.ptx
index 9a8eacf95..4e1e8b319 100644
--- a/pretext/Iteration/Exercises.ptx
+++ b/pretext/Iteration/Exercises.ptx
@@ -1,39 +1,10 @@
Exercises
-
+
-
Add a print statement to Newton's sqrt function that
- prints out better each time it is calculated. Call your modified
- function with 25 as an argument and record the results.
(hint: use a web search to find out what a triangular number is.)
-
-
-
-
-Write a function ``print_triangular_numbers(n)`` that prints out the first
-n triangular numbers. A call to ``print_triangular_numbers(5)`` would
-produce the following output::
-
- 1 1
- 2 3
- 3 6
- 4 10
- 5 15
-
-(*hint: use a web search to find out what a triangular number is.*)
-~~~~
-def print_triangular_numbers(n):
- # your code here
-
-
-
-
-
-
Write a function, is_prime, that takes a single integer argument
- and returns True when the argument is a prime number and False
- otherwise.
-
-
-
-
-def is_prime(n):
- # your code here
-
-====
-from unittest.gui import TestCaseGui
-
-class myTests(TestCaseGui):
-
- def testOne(self):
- self.assertEqual(is_prime(2),True,"Tested on 2, which is a prime number.")
- self.assertEqual(is_prime(4187),False,"Tested on 4187, which is not a prime number. It is divisible by 53 and 79.")
- self.assertEqual(is_prime(22),False,"Tested on 22, which is not a prime number. It is divisible by 2 and 11.")
- self.assertEqual(is_prime(4813),True,"Tested on 4813, which is a prime number.")
-
-myTests().main()
-
-
-
-
-
-def is_prime(n):
- for i in range(2, n):
- if n % i == 0:
- return False
- return True
-
-print(is_prime(25))
-print(is_prime(7))
-print(is_prime(251))
-print(is_prime(20))
-
-
-
-
-
-
-
Modify the walking turtle program so that rather than a 90 degree left or right turn the
- angle of the turn is determined randomly at each step.
-
-
-
-
-
-
-
-
-
-
Modify the turtle walk program so that you have two turtles each with a
- random starting location. Keep the turtles moving until one of them leaves the screen.
Modify the previous turtle walk program so that the turtle turns around
- when it hits the wall or when one turtle collides with another turtle
- (when the positions of the two turtles are closer than some small number).
-
-
-
-
-
-
-
-
-
-
Write a function to remove all the red from an image.
- <img src="../_static/LutherBellPic.jpg" id="luther.jpg">
-<h4 style="text-align: left;">For this and the following exercises, use the
-luther.jpg photo.</h4>
-
-
-
-
-
-
-
-
-
-import image
-
-img = image.Image("luther.jpg")
-newimg = image.EmptyImage(img.getWidth(), img.getHeight())
-win = image.ImageWin()
-
-for col in range(img.getWidth()):
- for row in range(img.getHeight()):
- p = img.getPixel(col, row)
-
- newred = 0
- green = p.getGreen()
- blue = p.getBlue()
-
- newpixel = image.Pixel(newred, green, blue)
-
- newimg.setPixel(col, row, newpixel)
-
-newimg.draw(win)
-win.exitonclick()
-
-
-
-
-
-
-
Write a function to convert the image to grayscale.
-
-
-
-
+
+ # your code here
-
-
-
Write a function to convert an image to black and white.
-
-
-
-
-
-
-
-
-
-import image
-
-def convertBlackWhite(input_image):
- grayscale_image = image.EmptyImage(input_image.getWidth(), input_image.getHeight())
-
- for col in range(input_image.getWidth()):
- for row in range(input_image.getHeight()):
- p = input_image.getPixel(col, row)
-
- red = p.getRed()
- green = p.getGreen()
- blue = p.getBlue()
-
- avg = (red + green + blue) / 3.0
-
- newpixel = image.Pixel(avg, avg, avg)
- grayscale_image.setPixel(col, row, newpixel)
-
- blackwhite_image = image.EmptyImage(input_image.getWidth(), input_image.getHeight())
- for col in range(input_image.getWidth()):
- for row in range(input_image.getHeight()):
- p = grayscale_image.getPixel(col, row)
- red = p.getRed()
- if red > 140:
- val = 255
- else:
- val = 0
-
- newpixel = image.Pixel(val, val, val)
- blackwhite_image.setPixel(col, row, newpixel)
- return blackwhite_image
-
-
-win = image.ImageWin()
-img = image.Image("luther.jpg")
-
-bw_img = convertBlackWhite(img)
-bw_img.draw(win)
-
-win.exitonclick()
-
-
-
-
-
-
-
Sepia Tone images are those brownish colored images that may remind you of
- times past. The formula for creating a sepia tone is as follows:
-
newR = (R × 0.393 + G × 0.769 + B × 0.189)
-newG = (R × 0.349 + G × 0.686 + B × 0.168)
-newB = (R × 0.272 + G × 0.534 + B × 0.131)
-
Write a function to convert an image to sepia tone. Hint:
- Remember that rgb values must be integers between 0 and 255.
-
-
-
-
-
-
-
-
-
-
Write a function to uniformly enlarge an image by a factor of 2 (double the size).
After you have scaled an image too much it looks blocky. One way of
- reducing the blockiness of the image is to replace each pixel with the
- average values of the pixels around it. This has the effect of smoothing
- out the changes in color. Write a function that takes an image as a
- parameter and smooths the image. Your function should return a new image
- that is the same as the old but smoothed.
-
-
-
-
-
-
-
-
-
-
Write a general pixel mapper function that will take an image and a pixel mapping function as
- parameters. The pixel mapping function should perform a manipulation on a single pixel and return
- a new pixel.
When you scan in images using a scanner they may have lots of noise due to
- dust particles on the image itself or the scanner itself,
- or the images may even be damaged. One way of eliminating this noise is
- to replace each pixel by the median value of the pixels surrounding it.
-
-
-
-
-
-
-
-
-
-
Research the Sobel edge detection algorithm and implement it.
-
-
-
-
-
-
-
-
-
-import image
-import math
-import sys
-
-# Code adapted from http://www.cl.cam.ac.uk/projects/raspberrypi/tutorials/image-processing/edge_detection.html
-# Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License.
-
-# this algorithm takes some time for larger images - this increases the amount of time
-# the program is allowed to run before it times out
-sys.setExecutionLimit(20000)
-
-img = image.Image("luther.jpg")
-newimg = image.EmptyImage(img.getWidth(), img.getHeight())
-win = image.ImageWin()
-
-for x in range(1, img.getWidth()-1): # ignore the edge pixels for simplicity (1 to width-1)
- for y in range(1, img.getHeight()-1): # ignore edge pixels for simplicity (1 to height-1)
-
- # initialise Gx to 0 and Gy to 0 for every pixel
- Gx = 0
- Gy = 0
-
- # top left pixel
- p = img.getPixel(x-1, y-1)
- r = p.getRed()
- g = p.getGreen()
- b = p.getBlue()
-
- # intensity ranges from 0 to 765 (255 * 3)
- intensity = r + g + b
-
- # accumulate the value into Gx, and Gy
- Gx += -intensity
- Gy += -intensity
-
- # remaining left column
- p = img.getPixel(x-1, y)
- r = p.getRed()
- g = p.getGreen()
- b = p.getBlue()
-
- Gx += -2 * (r + g + b)
-
- p = img.getPixel(x-1, y+1)
- r = p.getRed()
- g = p.getGreen()
- b = p.getBlue()
-
- Gx += -(r + g + b)
- Gy += (r + g + b)
-
- # middle pixels
- p = img.getPixel(x, y-1)
- r = p.getRed()
- g = p.getGreen()
- b = p.getBlue()
-
- Gy += -2 * (r + g + b)
-
- p = img.getPixel(x, y+1)
- r = p.getRed()
- g = p.getGreen()
- b = p.getBlue()
-
- Gy += 2 * (r + g + b)
-
- # right column
- p = img.getPixel(x+1, y-1)
- r = p.getRed()
- g = p.getGreen()
- b = p.getBlue()
-
- Gx += (r + g + b)
- Gy += -(r + g + b)
-
- p = img.getPixel(x+1, y)
- r = p.getRed()
- g = p.getGreen()
- b = p.getBlue()
-
- Gx += 2 * (r + g + b)
-
- p = img.getPixel(x+1, y+1)
- r = p.getRed()
- g = p.getGreen()
- b = p.getBlue()
-
- Gx += (r + g + b)
- Gy += (r + g + b)
-
- # calculate the length of the gradient (Pythagorean theorem)
- length = math.sqrt((Gx * Gx) + (Gy * Gy))
-
- # normalise the length of gradient to the range 0 to 255
- length = length / 4328 * 255
-
- length = int(length)
-
- # draw the length in the edge image
- newpixel = image.Pixel(length, length, length)
- newimg.setPixel(x, y, newpixel)
-
-newimg.draw(win)
-win.exitonclick()
-
-
-
-
diff --git a/pretext/Iteration/toctree.ptx b/pretext/Iteration/toctree.ptx
index 4e99b0eef..65b198c9f 100644
--- a/pretext/Iteration/toctree.ptx
+++ b/pretext/Iteration/toctree.ptx
@@ -14,5 +14,4 @@
4
4
4
-4
diff --git a/pretext/ComplexLogic/CloningLists.ptx b/pretext/Lists/CloningLists.ptx
similarity index 100%
rename from pretext/ComplexLogic/CloningLists.ptx
rename to pretext/Lists/CloningLists.ptx
diff --git a/pretext/Lists/toctree.ptx b/pretext/Lists/toctree.ptx
index 67b7e0066..0c98ce72d 100644
--- a/pretext/Lists/toctree.ptx
+++ b/pretext/Lists/toctree.ptx
@@ -7,6 +7,7 @@
4
4
4
+4
4
4
4
@@ -14,5 +15,4 @@
4
4
4
-4
diff --git a/pretext/PythonModules/modules.ptx b/pretext/PythonModules/modules.ptx
index 60b994877..c2c896e39 100644
--- a/pretext/PythonModules/modules.ptx
+++ b/pretext/PythonModules/modules.ptx
@@ -1,7 +1,7 @@
Modules and Getting Help
-
+
A module is a file containing Python definitions and statements intended
for use in other Python programs. There are many Python modules that come with
Python as part of the standard library. We have already used one of these briefly,
diff --git a/pretext/PythonModules/toctree.ptx b/pretext/PythonModules/toctree.ptx
index d89612617..ae3a42904 100644
--- a/pretext/PythonModules/toctree.ptx
+++ b/pretext/PythonModules/toctree.ptx
@@ -6,5 +6,4 @@
4
4
4
-4
diff --git a/pretext/Selection/Exercises.ptx b/pretext/Selection/Exercises.ptx
index 6a7bcd9f2..daf98b7ee 100644
--- a/pretext/Selection/Exercises.ptx
+++ b/pretext/Selection/Exercises.ptx
@@ -89,7 +89,7 @@
-
Write a function which is given an exam mark, and it returns a string — the grade for that mark — according to this
+
Write code that takes an exam mark and prints a string — the grade for that mark — according to this
scheme:
@@ -145,135 +145,13 @@
The square and round brackets denote closed and open intervals.
A closed interval includes the number, and open interval excludes it. So 79.99999 gets grade C , but 80 gets grade B.
-
Test your function by printing the mark and the grade for a number of different marks.
+
Test your code by printing the mark and the grade for a number of different marks.
-
-
-def getGrade(grade):
- #your code here
-
-
-====
-
-from unittest.gui import TestCaseGui
-
-class myTests(TestCaseGui):
-
- def testOne(self):
- self.assertEqual(getGrade(95),'A','Tested getGrade on input of 95')
- self.assertEqual(getGrade(85),'B','Tested getGrade on input of 85')
- self.assertEqual(getGrade(65),'D','Tested getGrade on input of 65')
- self.assertEqual(getGrade(79.99999),'C','Tested getGrade on input of 79.9999')
- self.assertEqual(getGrade(80),'B','Tested getGrade on input of 80')
-
-
-myTests().main()
-
-
-
-
-
-def grade(mark):
- if mark >= 90:
- return "A"
- else:
- if mark >= 80:
- return "B"
- else:
- if mark >= 70:
- return "C"
- else:
- if mark >= 60:
- return "D"
- else:
- return "F"
-
-mark = 83
-print( "Mark:", str(mark), "Grade:", grade(mark))
-
-
-
-
-
-
-
Modify the turtle bar chart program from the previous chapter so that the bar for any value
- of 200 or more is filled with red, values between [100 and 200) are filled yellow,
- and bars representing values less than 100 are filled green.
-
-
-
-
-
-
-
-
-
-
In the turtle bar chart program, what do you expect to happen if one or more
- of the data values in the list is negative? Go back and try it out. Change the
- program so that when it prints the text value for the negative bars, it puts
- the text above the base of the bar (on the 0 axis).
-
-
-
-
-
-
-
-
-
-import turtle
-
-def drawBar(t, height):
- """ Get turtle t to draw one bar, of height. """
- t.begin_fill() # start filling this shape
- if height < 0:
- t.write(str(height))
- t.left(90)
- t.forward(height)
- if height >= 0:
- t.write(str(height))
- t.right(90)
- t.forward(40)
- t.right(90)
- t.forward(height)
- t.left(90)
- t.end_fill() # stop filling this shape
-
-
-
-xs = [48, -50, 200, 240, 160, 260, 220] # here is the data
-maxheight = max(xs)
-minheight = min(xs)
-numbars = len(xs)
-border = 10
-
-tess = turtle.Turtle() # create tess and set some attributes
-tess.color("blue")
-tess.fillcolor("red")
-tess.pensize(3)
-
-wn = turtle.Screen() # Set up the window and its attributes
-wn.bgcolor("lightgreen")
-if minheight > 0:
- lly = 0
-else:
- lly = minheight - border
-
-wn.setworldcoordinates(0-border, lly, 40*numbars+border, maxheight+border)
-
-
-for a in xs:
- drawBar(tess, a)
-
-wn.exitonclick()
-
-
-
-
Write a function findHypot. The function will be given the length of two sides of a right-angled triangle and it should return
- the length of the hypotenuse. (Hint: x ** 0.5 will return the square root, or use sqrt from the math module)
+
Write code that will calculate the length of the hypotenuse function will be given the length of two sides of a right-angled triangle and it should return
+ the . (Hint: x ** 0.5 will return the square root, or use sqrt from the math module)
@@ -298,48 +176,13 @@ myTests().main()
-
Write a function called is_even(n) that takes an integer as an argument
- and returns True if the argument is an even number and False if
+
Write code that takes an integer and prints True if the integer is an even number and False if
it is odd.
The previous example creates a list from a sequence of values based on some selection criteria. An easy way to do this type of processing in Python is to use a list comprehension. List comprehensions are concise ways to create lists. The general syntax is:
[<expression> for <item> in <sequence> if <condition>]
This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
-
+
@@ -36,7 +36,7 @@ def primes_upto(n):
Check your understanding
-
+
What is printed by the following statements?
diff --git a/pretext/ClassesBasics/AddingOtherMethodstoourClass.ptx b/pretext/ClassesBasics/AddingOtherMethodstoourClass.ptx
index 5efd49969..c4d897295 100644
--- a/pretext/ClassesBasics/AddingOtherMethodstoourClass.ptx
+++ b/pretext/ClassesBasics/AddingOtherMethodstoourClass.ptx
@@ -14,7 +14,7 @@
append method and add the integer 90 to the end of the list. Methods are accessed using dot notation.
Let's add two simple methods to allow a point to give us information about its state. The getX method, when invoked, will return the value of the x coordinate. The implementation of this method is straight forward since we already know how
to write functions that return values. One thing to notice is that even though the getX method does not need any other parameter information to do its work, there is still one formal parameter, self. As we stated earlier, all methods defined in a class that operate on objects of that class will have self as their first parameter. Again, this serves as reference to the object itself which in turn gives access to the state data inside the object.
-
+
class Point:
""" Point class for representing and manipulating x,y coordinates. """
@@ -40,7 +40,7 @@ print(p.getY())
Let's add another method, distanceFromOrigin, to see better how methods
work. This method will again not need any additional information to do its work.
It will perform a more complex task.
-
+
class Point:
""" Point class for representing and manipulating x,y coordinates. """
diff --git a/pretext/ClassesBasics/ConvertinganObjecttoaString.ptx b/pretext/ClassesBasics/ConvertinganObjecttoaString.ptx
index d46f2cc7a..c213d5d0d 100644
--- a/pretext/ClassesBasics/ConvertinganObjecttoaString.ptx
+++ b/pretext/ClassesBasics/ConvertinganObjecttoaString.ptx
@@ -3,7 +3,7 @@
Converting an Object to a String
When we're working with classes and objects, it is often necessary to print an object (that is to print the state of an object).
Consider the example below.
-
+
class Point:
""" Point class for representing and manipulating x,y coordinates. """
@@ -35,7 +35,7 @@ print(p)
The __str__ method is responsible for returning a string representation as defined by the class creator. In other words, you as the programmer, get to choose what a Point should look like when it gets printed. In this case, we
have decided that the string representation will include the values of x and y as well as some identifying text. It
is required that the __str__ method create and return a string.
-
+
class Point:
""" Point class for representing and manipulating x,y coordinates. """
diff --git a/pretext/ClassesBasics/ImprovingourConstructor.ptx b/pretext/ClassesBasics/ImprovingourConstructor.ptx
index e4fc90bde..977f74f60 100644
--- a/pretext/ClassesBasics/ImprovingourConstructor.ptx
+++ b/pretext/ClassesBasics/ImprovingourConstructor.ptx
@@ -5,7 +5,7 @@
provide some additional capability for the user to pass information to the constructor. Since constructors are simply specially named functions, we can use parameters (as we've seen before) to provide the specific information.
We can make our class constructor more general by putting extra parameters into
the __init__ method, as shown in this codelens example.
-
+
class Point:
""" Point class for representing and manipulating x,y coordinates. """
diff --git a/pretext/ClassesBasics/InstancesasReturnValues.ptx b/pretext/ClassesBasics/InstancesasReturnValues.ptx
index c246aeadf..71ca70edf 100644
--- a/pretext/ClassesBasics/InstancesasReturnValues.ptx
+++ b/pretext/ClassesBasics/InstancesasReturnValues.ptx
@@ -8,7 +8,7 @@
and wish to find the midpoint halfway between it and some other target point. We would like to write a method, call
it halfway that takes another Point as a parameter and returns the Point that is halfway between the point and
the target.
-
+
class Point:
@@ -50,7 +50,7 @@ print(mid.getY())
We can always see whether the coordinates of Point self or target are being referred to.
This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
-
+
diff --git a/pretext/ClassesBasics/ObjectsRevisited.ptx b/pretext/ClassesBasics/ObjectsRevisited.ptx
index a15cb0817..bc12ff29b 100644
--- a/pretext/ClassesBasics/ObjectsRevisited.ptx
+++ b/pretext/ClassesBasics/ObjectsRevisited.ptx
@@ -7,5 +7,5 @@
that the object knows about itself. For example, each list has a state consisting
of the items it contains, a length and so on. Each list also has the ability to add, delete, and sort the items inside of it. Individual lists are different in
that even though they are all lists, they differ in the specific values of the individual state attributes (maybe they have different items inside them).
-
+
diff --git a/pretext/ClassesBasics/ObjectsasArgumentsandParameters.ptx b/pretext/ClassesBasics/ObjectsasArgumentsandParameters.ptx
index 58067f71f..7be61958f 100644
--- a/pretext/ClassesBasics/ObjectsasArgumentsandParameters.ptx
+++ b/pretext/ClassesBasics/ObjectsasArgumentsandParameters.ptx
@@ -3,7 +3,7 @@
Objects as Arguments and Parameters
You can pass an object as an argument in the usual way. Here is a simple function called distance involving our new Point objects.
The job of this function is to figure out the distance between two points.
-
+
import math
diff --git a/pretext/ClassesBasics/UserDefinedClasses.ptx b/pretext/ClassesBasics/UserDefinedClasses.ptx
index f0cf67485..757165bb2 100644
--- a/pretext/ClassesBasics/UserDefinedClasses.ptx
+++ b/pretext/ClassesBasics/UserDefinedClasses.ptx
@@ -49,7 +49,7 @@ class Point:
other name, but nobody ever does!) is automatically set to reference
the newly-created object that needs to be initialized.
So let's use our new Point class now.
-
+
class Point:
""" Point class for representing and manipulating x,y coordinates. """
@@ -77,7 +77,7 @@ print("Nothing seems to have happened with the points")
having an x and y coordinate with value 0. However, because we have not asked the point to do anything, we don't see any other result.
You can see this for yourself, via codelens:
-
+
class Point:
""" Point class for representing and manipulating x,y coordinates. """
@@ -95,7 +95,7 @@ print("Nothing seems to have happened with the points")
The following program adds a few print statements. You can see that the output suggests that each one is a Point object.
However, notice that the is operator returns False meaning that they are different objects (we will have more to say about this in a later chapter).
-
+
class Point:
""" Point class for representing and manipulating x,y coordinates. """
@@ -114,7 +114,7 @@ print(q)
print(p is q)
-
This should look familiar — we've used classes before to create
+
The variables p and q are assigned references to two new Point objects.
A function like Turtle or Point that creates a new object instance
is called a constructor. Every class automatically uses the name of the class as the name of the constructor function.
@@ -141,7 +141,7 @@ alex = Turtle()
Check Your Understanding
-
+
What is the the output of the following print code?
To design our class, we simply need to use the analysis above to realize that the state of a fraction object can be
completely described by representing two integers. We can begin by implementing the Fraction class and the __init__
method which will allow the user to provide a numerator and a denominator for the fraction being created.
-
+
class Fraction:
diff --git a/pretext/ClassesDiggingDeeper/ObjectsareMutable.ptx b/pretext/ClassesDiggingDeeper/ObjectsareMutable.ptx
index 21fd86124..7b170476b 100644
--- a/pretext/ClassesDiggingDeeper/ObjectsareMutable.ptx
+++ b/pretext/ClassesDiggingDeeper/ObjectsareMutable.ptx
@@ -12,7 +12,7 @@
representation would be 3/4.
There is a very nice iterative method for computing the greatest common divisor of two integers. Try to run the
function on a number of different examples.
-
+
def gcd(m, n):
while m % n != 0:
@@ -31,7 +31,7 @@ print(gcd(12, 16))
a fraction method called simplify. We will ask the fraction to put itself in lowest terms.
The simplify method will pass the numerator and the denominator to the gcd function to find the
greatest common divisor. It will then modify itself by dividing its num and its den by that value.
-
+
def gcd(m, n):
while m % n != 0:
diff --git a/pretext/ClassesDiggingDeeper/Sameness.ptx b/pretext/ClassesDiggingDeeper/Sameness.ptx
index a6768f6d8..1dd7ac238 100644
--- a/pretext/ClassesDiggingDeeper/Sameness.ptx
+++ b/pretext/ClassesDiggingDeeper/Sameness.ptx
@@ -13,7 +13,7 @@
We've already seen the is operator in the chapter on lists, where we
talked about aliases.
It allows us to find out if two references refer to the same object.
The following program concerns a list of lists of names. In some cases, we may want to take nested list data and "un-nest" it. To do this, we need to
iterate through the outer list, and then construct another loop to iterate through each name in each sublist. In this program's case, we are simply printing each
name as we encounter it.
-
+
names = [["Thomas", "Abraham", "George"], ["Theodore", "Grover", "William"], ["Franklin", "Dwight", "John", "Harry"], ["George", "Bill"]]
for sublist in names:
@@ -17,7 +17,7 @@ for sublist in names:
Nested lists can also be navigated by index rather than by value. This complicates the code somewhat, but gives us more flexibility for what can be done to each item.
In this example program, we visit each name and turn it lowercase.
Note that in the above program it is very important that we use len(names[sublist_index]) in the second range call. Because the nested lists in this example
do not have the same length, we have to check the length of each sublist when setting up our nested for loop bounds. If we do not do this carefully, then we can easily
miss data or get an out of bounds exception. Consider a different, erroneous example:
Nested lists can be used in many different contexts, but one more common use is to model 2D grids of data. Here is one last example that treats nested lists as a 2D coordinate plane
and finds the location of a single value in that plane. Note this example reverses the y axis, so y values increase as you travel downward. This is to match the indexing on the lists,
though we could model this as a more familiar coordinate system with some small changes.
-
+
coord = [['_', '_', '_', '_'],
['_', '_', 'p', '_'],
@@ -53,10 +53,10 @@ for y in range(len(names)):
print(f'p is as coordinates (x={x}, y={y})')
-
A nested list is a list that appears as an element in another list. In this
list, the element with index 3 is a nested list.
@@ -7,7 +7,7 @@
nested list, we can proceed in two steps. First, extract the nested list, then extract the item
of interest. It is also possible to combine those steps using bracket operators that evaluate from
left to right.
diff --git a/pretext/ComplexLogic/ObjectsandReferences.ptx b/pretext/ComplexLogic/ObjectsandReferences.ptx
index bf8bd24d2..d055a62f9 100644
--- a/pretext/ComplexLogic/ObjectsandReferences.ptx
+++ b/pretext/ComplexLogic/ObjectsandReferences.ptx
@@ -1,5 +1,5 @@
-
+Objects and References
If we execute these assignment statements,
@@ -19,7 +19,7 @@ b = "banana"
refer to.
We already know that objects can be identified using their unique identifier. We can also test whether two names refer to the same object using the is
operator. The is operator will return true if the two references are to the same object. In other words, the references are the same. Try our example from above.
-
+
a = "banana"
b = "banana"
@@ -32,7 +32,7 @@ print(a is b)
Since strings are immutable, Python can optimize resources by making two names
that refer to the same string literal value refer to the same object.
This is not the case with lists. Consider the following example. Here, a and b refer to two different lists, each of which happens to have the same element values.
-
+
a = [81, 82, 83]
b = [81, 82, 83]
@@ -48,7 +48,7 @@ print(a == b)
a and b have the same value but do not refer to the same object.
There is one other important thing to notice about this reference diagram. The variable a is a reference to a collection of references. Those references actually refer to the integer values in the list. In other words, a list is a collection of references to objects. Interestingly, even though a and b are two different lists (two different collections of references), the integer object 81 is shared by both. Like strings, integers are also immutable so Python optimizes and lets everyone share the same object for some commonly used small integers.
Here is the example in codelens. Pay particular attention to the id values.
-
+
a = [81, 82, 83]
b = [81, 82, 83]
diff --git a/pretext/ComplexLogic/PureFunctions.ptx b/pretext/ComplexLogic/PureFunctions.ptx
index 453bf9383..f116f181a 100644
--- a/pretext/ComplexLogic/PureFunctions.ptx
+++ b/pretext/ComplexLogic/PureFunctions.ptx
@@ -1,5 +1,5 @@
-
+Pure Functions
A pure function does not produce side effects. It communicates with the
calling program only through parameters (which it does not modify) and a return
@@ -7,7 +7,7 @@
To use the pure function version of double_stuff to modify things,
you would assign the return value back to things.
-
+
def doubleStuff(a_list):
""" Return a new list in which contains doubles of the elements in a_list. """
@@ -24,7 +24,7 @@ print(things)
Once again, codelens helps us to see the actual references and objects as they are passed and returned.
-
+
def doubleStuff(a_list):
""" Return a new list in which contains doubles of the elements in a_list. """
diff --git a/pretext/ComplexLogic/TheAccumulatorPatternwithLists.ptx b/pretext/ComplexLogic/TheAccumulatorPatternwithLists.ptx
index 17462b8a3..b96ff174c 100644
--- a/pretext/ComplexLogic/TheAccumulatorPatternwithLists.ptx
+++ b/pretext/ComplexLogic/TheAccumulatorPatternwithLists.ptx
@@ -1,5 +1,5 @@
-
+The Accumulator Pattern with Lists
Remember the ? Many algorithms involving lists make use of
@@ -7,23 +7,23 @@
explore the use of the accumulator pattern with lists.
Let's take the problem of adding up all of the items in a list. The following program
computes the sum of a list of numbers.
-
+
-sum = 0
+total = 0
for num in [1, 3, 5, 7, 9]:
- sum = sum + num
-print(sum)
+ total = total + num
+print(total)
-
The program begins by defining an accumulator variable, sum, and initializing it to 0 (line 1).
+
The program begins by defining an accumulator variable, total, and initializing it to 0 (line 1).
Next, the program iterates over the list (lines 2-3), and updates the sum on each
- iteration by adding an item from the list (line 3). When the loop is finished, sum
+ iteration by adding an item from the list (line 3). When the loop is finished, total
has accumulated the sum of all of the items in the list.
Take a moment to step through this program using CodeLens to see how it works. It's important to
grasp the basic techniques.
Sometimes when we're accumulating, we don't want to add to our accumulator every time we iterate.
Consider, for example, the following program which counts the number of names with more than 3 letters.
-
+
long_names = 0
for name in ["Joe", "Sally", "Amy", "Brad"]:
@@ -39,7 +39,7 @@ print(long_names)
it.
At the end, we have accumulated the total number of long names.
We can use conditionals to also count if particular items are in a string or list. The following code finds all occurrences of vowels in a string.
-
+
s = "what if we went to the zoo"
num_vowels = 0
@@ -53,13 +53,13 @@ print(num_vowels)
an o. If it is an o then we will update our counter.
-
+ Accumulating the Max Value
We can also use the accumulation pattern with conditionals to find the maximum or minimum value. Instead of
continuing to build up the accumulator value like we have when counting or finding a sum, we can reassign the
accumulator variable to a different value.
The following example shows how we can get the maximum value from a list of integers.
-
+
nums = [9, 3, 8, 11, 5, 29, 2]
best_num = 0
@@ -77,7 +77,7 @@ print(best_num)
happen to our code? What if we were looking for the smallest number but we initialized best_num with
zero? To get around this issue, we can initialize the accumulator variable using one of the numbers in the
list.
-
+
nums = [9, 3, 8, 11, 5, 29, 2]
best_num = nums[0]
@@ -90,11 +90,11 @@ print(best_num)
The only thing we changed was the value of best_num on line 2 so that the value of best_num is the
first element in nums, but the result is still the same!
-
+ Accumulating a String Result
The accumulator pattern can be used to convert a list of items to a string.
Consider the following program:
-
+
scores = [85, 95, 70]
result = ''
@@ -110,13 +110,13 @@ print("The scores are " + result)
The output of the program has some undesirable formatting problems: there is a trailing comma instead
of a period, and there are no spaces between the items. The next activity lets you work to
correct those problems.
-
+
Let's work to improve the formatting of the sentence produced by the program above.
Revise the following code so that it outputs the sentence:
The scores are 85, 95, and 70.
-
+
scores = [85, 95, 70]
result = ''
@@ -145,7 +145,7 @@ myTests().main()
This solution works by iterating over all of the scores in the list
except the last, and dealing with that one separately.
-
+
scores = [85, 95, 70]
result = ''
for score in scores[:-1]:
@@ -166,7 +166,7 @@ print("The scores are " + result)
Check your understanding
-
+
What is printed by the following statements?
@@ -215,7 +215,7 @@ print(x)
-
+
What is printed by the following statements?
@@ -264,11 +264,11 @@ print(min_value)
-
+
Challenge For each word in words, add ‘d' to the end of the word if the word ends in e to make it past tense. Otherwise, add ‘ed' to make it past tense. Save these past tense words to a list called past_tense.
Combining the in operator with string concatenation using + and the accumulator pattern, we can
write a function that removes all the vowels from a string. The idea is to start with a string and iterate over each character, checking to see if the character is a vowel. As we process the characters, we will build up a new string consisting of only the nonvowel characters. To do this, we use the accumulator pattern.
Remember that the accumulator pattern allows us to keep a running total. With strings, we are not accumulating a numeric total. Instead we are accumulating characters onto a string.
-
+
def removeVowels(s):
vowels = "aeiouAEIOU"
@@ -36,7 +36,7 @@ if eachChar != 'a' and eachChar != 'e' and eachChar != 'i' and
Take a close look also at the initialization of sWithoutVowels. We start with an empty string and then begin adding
new characters to the end.
Step through the function using codelens to see the accumulator variable grow.
Functions which take lists as arguments and change them during execution are
called modifiers and the changes they make are called side effects.
@@ -9,7 +9,7 @@
the same list that the argument is referencing.
For example, the function below takes a list as an
argument and multiplies each element in the list by 2:
-
+
def doubleStuff(aList):
""" Overwrite each element in aList with double its value. """
@@ -29,7 +29,7 @@ print(things)
If a function modifies the elements of a list parameter, the caller sees the change since the change
is occurring to the original.
This can be easily seen in codelens. Note that after the call to doubleStuff, the formal parameter aList refers to the same object as the actual parameter things. There is only one copy of the list object itself.
-
+
def doubleStuff(aList):
""" Overwrite each element in aList with double its value. """
diff --git a/pretext/ComplexLogic/toctree.ptx b/pretext/ComplexLogic/toctree.ptx
index 61940cb1b..0a254a223 100644
--- a/pretext/ComplexLogic/toctree.ptx
+++ b/pretext/ComplexLogic/toctree.ptx
@@ -4,12 +4,9 @@
4
4
4
-
4
-
-4
4
-
+4
4
4
4
diff --git a/pretext/Debugging/HowtoAvoidDebugging.ptx b/pretext/Debugging/HowtoAvoidDebugging.ptx
index 3b643b2a7..b88c6b05d 100644
--- a/pretext/Debugging/HowtoAvoidDebugging.ptx
+++ b/pretext/Debugging/HowtoAvoidDebugging.ptx
@@ -43,7 +43,7 @@
Ok, let's look at an example. Let's solve the problem posed in question 3 at the end of the Simple Python Data chapter. Ask the user for the time now (in hours 0 - 23), and ask for the number of hours to wait. Your program should output what the time will be on the clock when the alarm goes off. For example, if current_time is 8 and wait_time is 5, final_time should be 13 (1 pm).
So, where to start? The problem requires two pieces of input from the user, so let's start there and make sure we can get the data we need.
-
+
current_time = input("what is the current time (in hours)?")
wait_time = input("How many hours do you want to wait")
@@ -53,7 +53,7 @@ print(wait_time)
So far so good. Now let's take the next step. We need to figure out what the time will be after waiting wait_time number of hours. A reasonable solution is to simply add wait_time to current_time and print out the result. So lets try that.
-
+
current_time = input("What is the current time (in hours 0 - 23)?")
wait_time = input("How many hours do you want to wait")
@@ -66,7 +66,7 @@ print(final_time)
Hmm, when you run this example you see that something unexpected has happened. You would not realize this was an error unless you first knew what the program was supposed to do.
-
+
Which of the following best describes what is wrong with the previous example?
@@ -99,7 +99,7 @@ print(final_time)
This error was probably pretty simple to spot, because we printed out the value of final_time and it is easy to see that the numbers were just concatenated together rather than added.
So what do we do about the problem? We will need to convert both current_time and wait_time to int. At this stage of your programming development, it can be a good idea to include the type of the variable in the variable name itself. So let's look at another iteration of the program that does that, and the conversion to integer.
-
+
current_time_str = input("What is the current time (in hours 0-23)?")
wait_time_str = input("How many hours do you want to wait")
@@ -114,7 +114,7 @@ print(final_time_int)
Now, that's a lot better, and in fact depending on the hours you chose, it may be exactly right. If you entered 8 for current_time and 5 for wait_time then 13 is correct. But if you entered 17 (5 pm) for current_time and 9 for wait_time then the result of 26 is not correct.
This illustrates an important aspect of testing: it is important to test your code on a range of inputs. It is especially important to test your code on boundary conditions. For this particular problem, you should test your program with current_time of 0, 23, and some values in between. You should test your wait_time for 0, and some larger values. What about negative numbers? Negative numbers don't make sense, and since we don't really have the tools to deal with telling the user when something is wrong we will not worry about that just yet.
So to account for those numbers that are bigger than 23, we need one final step: using the modulus operator.
-
+
current_time_str = input("What is the current time (in hours 0-23)?")
wait_time_str = input("How many hours do you want to wait")
diff --git a/pretext/Debugging/KnowyourerrorMessages.ptx b/pretext/Debugging/KnowyourerrorMessages.ptx
index 9e83f8d55..445215c01 100644
--- a/pretext/Debugging/KnowyourerrorMessages.ptx
+++ b/pretext/Debugging/KnowyourerrorMessages.ptx
@@ -17,7 +17,7 @@ print(final_time_int)
Can you see what is wrong, just by looking at the code? Maybe, maybe not. Our brain tends to see what we think is there, so sometimes it is very hard to find the problem just by looking at the code. Especially when it is our own code and we are sure that we have done everything right!
Let's try the program again, but this time in an activecode:
-
+
current_time_str = input("What is the current time (in hours 0-23)?")
wait_time_str = input("How many hours do you want to wait")
@@ -35,7 +35,7 @@ print(final_time_int)
Python interpreter. The interpreter in activecode is limited in many ways, but it is intended for beginners,
including the wording chosen to describe errors.
-
+
Which of the following explains why wait_time_int = int(wait_time_int) is an error?
TypeErrors occur when you you try to combine two objects that are not compatible. For example you try to add together an integer and a string. Usually type errors can be isolated to lines that are using mathematical operators, and usually the line number given by the error message is an accurate indication of the line.
Here's an example of a type error created by a Polish learner. See if you can find and fix the error.
-
+
a = input('wpisz godzine')
x = input('wpisz liczbe godzin')
@@ -332,7 +332,7 @@ print ('godzina teraz', a)
NameError
Name errors almost always mean that you have used a variable before it has a value. Often NameErrors are simply caused by typos in your code. They can be hard to spot if you don't have a good eye for catching spelling mistakes. Other times you may simply mis-remember the name of a variable or even a function you want to call. You have seen one example of a NameError at the beginning of this section. Here is another one. See if you can get this program to run successfully:
-
+
str_time = input("What time is it now?")
str_wait_time = input("What is the number of nours to wait?")
@@ -361,7 +361,7 @@ print(time_when_alarm_go_off)
Here is another one for you to try:
-
+
n = input("What time is it now (in hours)?")
n = imt(n)
@@ -378,7 +378,7 @@ print("The time is now", q)
And one last bit of code to fix.
-
+
present_time = input("Enter the present timein hours:")
set_alarm = input("Set the hours for alarm:")
@@ -422,7 +422,7 @@ print(alarm_time)
ValueError
Value errors occur when you pass a parameter to a function and the function is expecting a certain limitations on the values, and the value passed is not compatible. We can illustrate that with this particular program in two different ways.
-
+
current_time_str = input("What is the current time (in hours 0-23)?")
current_time_int = int(current_time_str)
diff --git a/pretext/Files/AlternativeFileReadingMethods.ptx b/pretext/Files/AlternativeFileReadingMethods.ptx
index 494965c5c..840c794e4 100644
--- a/pretext/Files/AlternativeFileReadingMethods.ptx
+++ b/pretext/Files/AlternativeFileReadingMethods.ptx
@@ -120,7 +120,7 @@
Now let's look at another method of reading our file using a while loop. This is important because many other programming languages do not support the for loop style for reading files but they do support the pattern we'll show you here.
-
+
infile = open("ccdata.txt", "r")
line = infile.readline()
diff --git a/pretext/Files/Iteratingoverlinesinafile.ptx b/pretext/Files/Iteratingoverlinesinafile.ptx
index da9ccf0f7..c86a48b21 100644
--- a/pretext/Files/Iteratingoverlinesinafile.ptx
+++ b/pretext/Files/Iteratingoverlinesinafile.ptx
@@ -44,7 +44,7 @@
the split method, we can break each line into a list containing all the fields of interest about climate
change. We can then take the values corresponding to year, global average temperature, and global emmisions to
construct a simple sentence.
-
+
ccfile = open("ccdata.txt", "r")
diff --git a/pretext/Files/ReadingCSV.ptx b/pretext/Files/ReadingCSV.ptx
index 3a91fe72a..c12bea915 100644
--- a/pretext/Files/ReadingCSV.ptx
+++ b/pretext/Files/ReadingCSV.ptx
@@ -11,7 +11,7 @@
This section focuses on reading csv, so we should use a reader. The reason we are interested in doing this is because the reader will automatically detect and remove
the commas separating values for us. Essentially, the reader will split the data up into lists for us. This makes it simpler to navigate and interact with the data in the file.
Let's see an example of this working.
-
+
import csv
with open("ccdata.csv", "r") as file:
diff --git a/pretext/Files/WithStatements.ptx b/pretext/Files/WithStatements.ptx
index 0bee04a3e..a067be262 100644
--- a/pretext/Files/WithStatements.ptx
+++ b/pretext/Files/WithStatements.ptx
@@ -10,7 +10,7 @@
When the program exits the with block, the context manager handles the common stuff that normally happens. For example closing a file. A simple example will clear up all of this abstract discussion of contexts.
-
+
with open('mydata.txt') as md:
print(md)
diff --git a/pretext/Files/WritingCSV.ptx b/pretext/Files/WritingCSV.ptx
index ee265ce73..fdd8682d4 100644
--- a/pretext/Files/WritingCSV.ptx
+++ b/pretext/Files/WritingCSV.ptx
@@ -4,7 +4,7 @@
We already introduced the csv module in the previous section. Let's examine some examples using a csv.writer object.
Like the reader object, the csv.writer function takes a opened file object. Once set up, the csv file can be written to with writerow.
Make note that writerow does not need an explicit newline character \n to know when to end a line of text. This sets it apart for the the regular file.write() function.
-
+
import csv
data = [["Column_1_Name","Column_2_Name","Column_3_Name"],
@@ -27,7 +27,7 @@ with open("new_file.csv", "w", newline='') as file:
There is one other writer method you may find useful, which is writerows. This allows you to write multiple rows of data at the same time. When applied to the previous
example, it saves us from having to set up a loop.
To construct this file, we will approach the problem using a similar algorithm as above. After opening the file, we will iterate through the
lines, break each line into its parts, choose the parts that we need, and then output them. Eventually, the output will be written to a file.
The program below solves part of the problem. Notice that it reads the data and creates a string consisting of the year of the climate change followed by the global emission. In this example, we simply print the lines as they are created.
When we run this program, we see the lines of output on the screen. Once we are satisfied that it is creating the appropriate output, the next step is to add the necessary pieces to produce an output file and write the data lines to it. To start, we need to open a new output file by adding another call to the open function, outfile = open("emissiondata.txt",'w'), using the 'w' flag. We can choose any file name we like. If the file does not exist, it will be created. However, if the file does exist, it will be reinitialized as empty and you will lose any previous contents.
Once the file has been created, we just need to call the write method passing the string that we wish to add to the file. In this case, the string is already being printed so we will just change the print into a call to the write method. However, there is one additional part of the data line that we need to include. The newline character needs to be concatenated to the end of the line. The entire line now becomes outfile.write(dataline + '\n'). We also need to close the file when we are done.
We have already seen that boolean values result from the evaluation of boolean expressions. Since the result of any
expression evaluation can be returned by a function (using the return statement),
functions can return boolean values. This turns out to be a very convenient way to hide the details of complicated tests. For example:
-
+
def isDivisible(x, y):
if x % y == 0:
@@ -47,7 +47,7 @@ else:
not isDivisible(x, y)). The following example shows the isDivisible function at work. Notice how
descriptive the code is when we move the testing details into a boolean function. Try it
with a few other actual parameters to see what is printed.
-
+
def isDivisible(x, y):
return x % y == 0
@@ -60,7 +60,7 @@ else:
Here is the same program in codelens. When we evaluate the if statement in the main part of the program, the evaluation of
the boolean expression causes a call to the isDivisible function. This is very easy to see in codelens.
-
+
def isDivisible(x, y):
return x % y == 0
@@ -74,7 +74,7 @@ else:
Check your understanding
-
+
What is a Boolean function?
@@ -105,7 +105,7 @@ else:
-
+
Is the following statement legal in a Python function (assuming x, y and z are defined to be numbers)?
@@ -134,12 +134,12 @@ return x + y < z
-
+ More Unit Testing
When we write unit tests, we should also consider output equivalence classes that result in significantly different results.
The isDivisible function can return either True or False. These two different outputs give us two equivalence classes. We then choose inputs that should give each of the different results. It is important to have at least one test for each output equivalence class.
-
+
def isDivisible(x, y):
'''is x evenly divisible by y?'''
@@ -155,7 +155,7 @@ if __name__ == "__main__":
This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
-
+
diff --git a/pretext/Functions/Composition.ptx b/pretext/Functions/Composition.ptx
index 182f5dfeb..7f5ce7620 100644
--- a/pretext/Functions/Composition.ptx
+++ b/pretext/Functions/Composition.ptx
@@ -24,7 +24,7 @@ return result
Consider the following Python code. Note that line numbers are included on the left.
@@ -91,7 +91,7 @@ print(result)
-
+
Consider the following Python code. Note that line numbers are included on the left.
diff --git a/pretext/Functions/Functionscancallotherfunctions.ptx b/pretext/Functions/Functionscancallotherfunctions.ptx
index 692aee804..c98720523 100644
--- a/pretext/Functions/Functionscancallotherfunctions.ptx
+++ b/pretext/Functions/Functionscancallotherfunctions.ptx
@@ -11,7 +11,7 @@
first function called square simply computes the square of a given number.
The second function called sum_of_squares makes use of square to compute
the sum of three numbers that have been squared.
-
+
def square(x):
y = x * x
diff --git a/pretext/Functions/Functionsthatreturnvalues.ptx b/pretext/Functions/Functionsthatreturnvalues.ptx
index 743ea4faf..f5812b9f8 100644
--- a/pretext/Functions/Functionsthatreturnvalues.ptx
+++ b/pretext/Functions/Functionsthatreturnvalues.ptx
@@ -5,7 +5,7 @@
job. For example, if you want to find the absolute value of a number, you have
to indicate what the number is. Python has a built-in function for computing
the absolute value:
-
+
print(abs(5))
@@ -14,7 +14,7 @@ print(abs(-5))
In this example, the arguments to the abs function are 5 and -5.
Some functions take more than one argument. For example the range function that we saw with for loops.
Another built-in function that takes more than one argument is max.
-
+
print(max(7, 11))
print(max(4, 1, 17, 2, 12))
@@ -55,7 +55,7 @@ print(max(3 * 11, 5 ** 3, 512 - 9, 1024 ** 0))
as a parameter and return the result of squaring that number. Here is the
black-box diagram with the Python code following.
-
+
def square(x):
y = x * x
@@ -93,7 +93,7 @@ print("The result of", toSquare, "squared is", result)
we will see later where it makes sense to have a return statement even when other statements
follow, and the further statements are not executed.
-
+
def square(x):
y = x * x
@@ -130,7 +130,7 @@ print("The result of", toSquare, "squared is", squareResult)
programmers. As you step through this example, pay very close attention to the return
value in the local variables listing. Then look at what is printed when the
function returns.
-
+
def square(x):
y = x * x
@@ -148,7 +148,7 @@ print("The result of", toSquare, "squared is", squareResult)
Check your understanding
-
+
What is wrong with the following function definition:
@@ -194,7 +194,7 @@ def addEm(x, y, z):
-
+
What will the following function return?
diff --git a/pretext/Functions/ProgramDevelopment.ptx b/pretext/Functions/ProgramDevelopment.ptx
index d86150a1f..c2cbbf371 100644
--- a/pretext/Functions/ProgramDevelopment.ptx
+++ b/pretext/Functions/ProgramDevelopment.ptx
@@ -29,7 +29,7 @@ def distance(x1, y1, x2, y2):
returns zero. But it is syntactically correct, and it will run, which means
that we can test it before we make it more complicated.
We import the test module to enable us to write a unit test for the function.
-
+
import test
def distance(x1, y1, x2, y2):
@@ -83,7 +83,7 @@ def distance(x1, y1, x2, y2):
should be 25).
Finally, using the fractional exponent 0.5 to find the square root,
we compute and return the result.
Here is the program in activecode. Note that the heading of the function definition is the same as it was before. All that has changed
is the details of how the squaring is done. This is a great example of black box design. We can change out the details inside of the box and still use the function exactly as we did before.
-
+
def square(x):
runningtotal = 0
@@ -47,7 +47,7 @@ print("The result of", toSquare, "squared is", squareResult)
the for statement? Not sure? Try it and find out.
Here is the same program in codelens. Step through the function and watch the running total accumulate the result.
This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
-
+
@@ -85,7 +85,7 @@ repeat:
Check your understanding
-
+
Consider the following code:
@@ -162,7 +162,7 @@ def square(x):
A Variation on the Accumulator Pattern
-
+
def square(x):
'''raise x to the second power'''
diff --git a/pretext/Functions/UnitTesting.ptx b/pretext/Functions/UnitTesting.ptx
index 5d995f943..7c17cda8f 100644
--- a/pretext/Functions/UnitTesting.ptx
+++ b/pretext/Functions/UnitTesting.ptx
@@ -39,7 +39,7 @@
Take a look at the way assert is used in the following code.
-
+
assert type(9//5) == int
assert type(9.0//5) == int
@@ -55,7 +55,7 @@ assert type(9.0//5) == int
Check your understanding
-
+
When assert x==y is executed and x and y have the same values, what will happen?
@@ -118,7 +118,7 @@ assert type(9.0//5) == int
In the code below, lst is bound to a list object. In python, not all the elements of a list have to be of the
same type. We can check that they all have the same type and get an error if they are not. Notice that with lst2,
one of the assertions fails.
-
+
lst = ['a', 'b', 'c']
first_type = type(lst[0])
@@ -137,7 +137,7 @@ for item in lst2:
Testing whether a function returns the correct value is the easiest test case to define. You simply check whether the
result of invoking the function on a particular input produces the particular output that you expect. Take a look at
the following code.
-
+
def square(x):
#raise x to the second power
@@ -150,7 +150,7 @@ assert square(3) == 9
principle, a function might work properly on all the inputs that are tested in the test cases, but still not work
properly on some other inputs. That's where the art of defining test cases comes in: you try to find specific inputs that
are representative of all the important kinds of inputs that might ever be passed to the function.
-
+
For the hangman game, this ‘blanked' function takes a word and some letters that have been guessed, and returns a version
of the word with _ for all the letters that haven't been guessed. Which of the following is the correct way to write
diff --git a/pretext/Functions/Variablesandparametersarelocal.ptx b/pretext/Functions/Variablesandparametersarelocal.ptx
index 3451b4f86..f0c8e2a0c 100644
--- a/pretext/Functions/Variablesandparametersarelocal.ptx
+++ b/pretext/Functions/Variablesandparametersarelocal.ptx
@@ -5,7 +5,7 @@
variable on the left hand side of the assignment operator. It is called local because this variable only
exists inside the function and you cannot use it outside. For example,
consider again the square function:
-
+
def square(x):
y = x * x
@@ -39,7 +39,7 @@
On the other hand, it is legal for a function to access a global variable. However, this is considered
bad form by nearly all programmers and should be avoided. Look at the following,
nonsensical variation of the square function.
-
+
def badsquare(x):
y = x ** power
@@ -62,7 +62,7 @@ print(result)
There is another variation on this theme of local versus global variables. Assignment statements in the local function cannot
change variables defined outside the function, without further (discouraged) special syntax. Consider the following
codelens example:
-
+
def powerof(x, p):
power = p # Another dumb mistake
@@ -96,7 +96,7 @@ print(result)
formal parameter will cause a change to the value of the variable that was
used as the actual parameter, especially when the two share the same name.
But this example demonstrates that that is clearly not how Python operates.
-
+
def square(x):
y = x * x
@@ -111,7 +111,7 @@ print(result)
Check your understanding
-
+
What is a variable's scope?
@@ -142,7 +142,7 @@ print(result)
-
+
What is a local variable?
@@ -173,7 +173,7 @@ print(result)
-
+
Can you use the same name for a local variable as a global variable?
diff --git a/pretext/Functions/functions.ptx b/pretext/Functions/functions.ptx
index 2309236e7..bd3b5a301 100644
--- a/pretext/Functions/functions.ptx
+++ b/pretext/Functions/functions.ptx
@@ -49,7 +49,7 @@ def name( parameters ):
It would make sense if we did not have to duplicate all the steps each time we want to find the size of the range. "printRange" can be thought of as an
abstraction of a number of smaller steps. We will need to provide one piece of information for the function to do its work: the list we need the range of.
Here is a program containing a function to capture this idea. Give it a try.
-
+
def printRange(lst):
"""Prints the size of the range of lst."""
@@ -88,7 +88,7 @@ def name( parameters ):
Once we've defined a function, we can call it as often as we like and its
statements will be executed each time we call it. In this case, we could use it to get
the size of the range of multiple lists. Make sure you can identify all three invocations of the printRange function.
-
+
def printRange(lst):
"""Prints the size of the range of lst."""
@@ -113,7 +113,7 @@ printRange([5, 10, 1000, 2])
This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
What are the parameters of the following function?
@@ -334,7 +334,7 @@ def printSquare(size):
-
+
Considering the function below, which of the following statements correctly invokes, or calls, this function (i.e., causes it to run)? Assume we already have a variable named my_size.
@@ -389,7 +389,7 @@ def printSquare(size):
-
+
True or false: A function can be called several times by placing a function call in the body of a loop.
The following activecode shows this idea. In line 11 we have defined a new function called main that doesn't need any parameters. The five lines of main processing are now placed inside this function. Finally, in order to execute that main processing code, we need to invoke the main function (line 20). When you push run, you will see that the program works the same as it did before.
-
+
def square(x):
y = x * x
@@ -56,7 +56,7 @@ main() # Invoke the main function
Before the Python interpreter executes your program, it defines a few special variables. One of those variables is called __name__ and it is automatically set to the string value "__main__" when the program is being executed by itself in a standalone fashion. On the other hand, if the program is being imported by another program, then the __name__ variable is set to the name of that module. This means that we can know whether the program is being run by itself or whether it is being used by another program and based on that observation, we may or may not choose to execute some of the code that we have written.
For example, assume that we have written a collection of functions to do some simple math. We can include a main function to invoke these math functions. It is much more likely, however, that these functions will be imported by another program for some other purpose. In that case, we would not want to execute our main function.
The activecode below defines two simple functions and a main.
-
+
def squareit(n):
return n * n
diff --git a/pretext/GeneralIntro/ATypicalFirstProgram.ptx b/pretext/GeneralIntro/ATypicalFirstProgram.ptx
index 4bb8512e0..5c72c40a5 100644
--- a/pretext/GeneralIntro/ATypicalFirstProgram.ptx
+++ b/pretext/GeneralIntro/ATypicalFirstProgram.ptx
@@ -13,7 +13,7 @@ print("Hello, World!")
print anything on paper. It displays a value on the screen. In this case, the result is the phrase:
What is the most important skill for a computer scientist?
@@ -49,7 +49,7 @@
-
+
An algorithm is:
diff --git a/pretext/GeneralIntro/Comments.ptx b/pretext/GeneralIntro/Comments.ptx
index 8c3159fd1..c9fe4a8ef 100644
--- a/pretext/GeneralIntro/Comments.ptx
+++ b/pretext/GeneralIntro/Comments.ptx
@@ -10,7 +10,7 @@
reader - it is completely ignored by the interpreter.
In Python, the # token starts a comment. The rest of the line is ignored.
Here is a new version of Hello, World!.
-
+
#---------------------------------------------------
# This demo program shows off how elegant Python is!
@@ -28,7 +28,7 @@ print("Hello, World!") # Isn't this easy!
First, you can write, modify, and execute programs using a unique activecode interpreter that allows you to execute Python code right
in the text itself (right from the web browser). Although this is certainly not the way real programs are written, it provides an excellent
environment for learning a programming language like Python since you can experiment with the language as you are reading.
-
+
print("My first program adds two numbers, 2 and 3:")
print(2 + 3)
@@ -53,7 +53,7 @@ print(2 + 3)
In codelens you can see and control the step by step progress.
Note that the red arrow always points to the next line of code that is going to be executed.
The light green arrow points to the line that was just executed.
-
+
print("My first program adds two numbers, 2 and 3:")
print(2 + 3)
@@ -65,7 +65,7 @@ print(2 + 3)
Check your understanding
-
+
The activecode interpreter allows you to (select all that apply):
diff --git a/pretext/GeneralIntro/ThePythonProgrammingLanguage.ptx b/pretext/GeneralIntro/ThePythonProgrammingLanguage.ptx
index ff6c7ed7a..33491dac4 100644
--- a/pretext/GeneralIntro/ThePythonProgrammingLanguage.ptx
+++ b/pretext/GeneralIntro/ThePythonProgrammingLanguage.ptx
@@ -74,7 +74,7 @@ My first program adds two numbers, 2 and 3:
Check your understanding
-
+
Source code is another name for:
@@ -113,7 +113,7 @@ My first program adds two numbers, 2 and 3:
-
+
What is the difference between a high-level programming language and a low-level programming language?
@@ -154,7 +154,7 @@ My first program adds two numbers, 2 and 3:
-
+
Pick the best replacements for 1 and 2 in the following sentence: When comparing compilers and interpreters, a compiler is like 1 while an interpreter is like 2.
diff --git a/pretext/IntroRecursion/CalculatingtheSumofaListofNumbers.ptx b/pretext/IntroRecursion/CalculatingtheSumofaListofNumbers.ptx
index a5ceb8a32..a3e867a89 100644
--- a/pretext/IntroRecursion/CalculatingtheSumofaListofNumbers.ptx
+++ b/pretext/IntroRecursion/CalculatingtheSumofaListofNumbers.ptx
@@ -8,7 +8,7 @@
is shown below. The function uses an accumulator variable
(theSum) to compute a running total of all the numbers in the list
by starting with and adding each number in the list.
-
+
def listsum(numList):
theSum = 0
@@ -51,7 +51,7 @@ total = \ 25
In this equation returns the first element of
the list and returns a list of everything but
the first element. This is easily expressed in Python.
Write a function that takes a string as a parameter and returns a new string that is the reverse of the old string.
-
+
from test import testEqual
def reverse(s):
@@ -134,7 +134,7 @@ testEqual(reverse(""),"")
-
+
from test import testEqual
def removeWhite(s):
diff --git a/pretext/IntroRecursion/TheThreeLawsofRecursion.ptx b/pretext/IntroRecursion/TheThreeLawsofRecursion.ptx
index 9d4bddde1..0c086c4d3 100644
--- a/pretext/IntroRecursion/TheThreeLawsofRecursion.ptx
+++ b/pretext/IntroRecursion/TheThreeLawsofRecursion.ptx
@@ -46,7 +46,7 @@
problem by using the three laws of recursion.
Self Check
-
+
How many recursive calls are made when computing the sum of the list [2,4,6,8,10]?
@@ -85,7 +85,7 @@
-
+
Suppose you are going to write a recusive function to calculate the factorial of a number. fact(n) returns n * n-1 * n-2 * … * 1, and the factorial of zero is definded to be 1. What would be the most appropriate base case?
diff --git a/pretext/Iteration/BreakAndContinue.ptx b/pretext/Iteration/BreakAndContinue.ptx
index 8f13f7198..6c7af97be 100644
--- a/pretext/Iteration/BreakAndContinue.ptx
+++ b/pretext/Iteration/BreakAndContinue.ptx
@@ -1,5 +1,5 @@
-
+break and continue
In loops, we sometimes want to traverse until we reach a certain value.
@@ -9,7 +9,7 @@
When a break statement is reached, the loop immediately ends and proceeds with the code after the loop.
break is only a valid statement inside of loops, such as the following:
-
+
i = 0
while i < 10:
@@ -24,7 +24,7 @@ while i < 10:
When a continue statement is reached, the current iteration is stopped (similar to break),
however, the loop will continue running for all iterations after the current one.
-
+
i = 0
while i < 10:
diff --git a/pretext/Iteration/FlowofExecutionofthewhileLoop.ptx b/pretext/Iteration/FlowofExecutionofthewhileLoop.ptx
index 674266a21..cdc423eca 100644
--- a/pretext/Iteration/FlowofExecutionofthewhileLoop.ptx
+++ b/pretext/Iteration/FlowofExecutionofthewhileLoop.ptx
@@ -1,5 +1,5 @@
-
+Flow of Execution of the while Loop
As before with if, loops allow us as programmers to manipulate the control flow of a Python program.
We can now possibly skip a portion of code, or choose to repeat it an indefinite number of times.
@@ -8,7 +8,7 @@
A codelens demonstration is a good way to help you visualize exactly how the flow of control
works with the while loop. Try stepping forward and backward through the program by pressing
the buttons. You can see the value of count change as the loop iterates through the values from 10 to 0.
A special character that causes the cursor to move to the next tab stop
on the current line.
+
+
+ traverse
+
To iterate through the elements of a collection, performing a similar
+ operation on each.
diff --git a/pretext/Iteration/Listsandforloops.ptx b/pretext/Iteration/Listsandforloops.ptx
index 872c053ab..b3d7b04b2 100644
--- a/pretext/Iteration/Listsandforloops.ptx
+++ b/pretext/Iteration/Listsandforloops.ptx
@@ -1,8 +1,8 @@
-
+Traversing lists with the for loop
-
It is also possible to perform list traversal using iteration by item as well as iteration by index.
-
+
It is possible to perform list traversal using iteration by item as well as iteration by index.
+
fruits = ["apple", "orange", "banana", "cherry"]
@@ -13,7 +13,7 @@ for afruit in fruits: # by item
It almost reads like natural language: For (every) fruit in (the list of) fruits,
print (the name of the) fruit.
We can also use the indices to access the items in an iterative fashion.
-
+
fruits = ["apple", "orange", "banana", "cherry"]
@@ -25,7 +25,7 @@ for position in range(len(fruits)): # by index
list, printing the position-eth element. Note that we used len as the upper bound on the range
so that we can iterate correctly no matter how many items are in the list.
Any sequence expression can be used in a for loop. For example, the range function returns a sequence of integers.
-
+
for number in range(20):
if number % 3 == 0:
@@ -36,7 +36,7 @@ for number in range(20):
Since lists are mutable, it is often desirable to traverse a list, modifying
each of its elements as you go. The following code squares all the numbers from 1 to
5 using iteration by position.
diff --git a/pretext/Iteration/SentinelValuesAndValidation.ptx b/pretext/Iteration/SentinelValuesAndValidation.ptx
index cbc33af57..0e5321576 100644
--- a/pretext/Iteration/SentinelValuesAndValidation.ptx
+++ b/pretext/Iteration/SentinelValuesAndValidation.ptx
@@ -1,7 +1,7 @@
-
+Other uses of while
-
+ Sentinel Values
The indefinite loops provided by the while statement are common in the real world.
@@ -53,7 +53,7 @@
We don't have a little plastic bar data type in Python, so we'll do the next best thing: we
will use a price of zero to mean this is my last item. In this program,
zero is a sentinel value, a value used to signal the end of the loop. Here's the code:
-
+
total = 0
count = 0
@@ -91,7 +91,7 @@
Check your understanding
-
+
True or False: A while loop will continue to iterate forever unless it meets a condition to stop.
@@ -118,7 +118,7 @@
-
+ Validating Input
You can also use a while loop when you want to validate input; when you want to make
sure the user has entered valid input for a prompt. Let's say you want a function
@@ -128,7 +128,7 @@
Note that it uses
the upper() method which is described in to convert a string to upper case.
When you run the following code, try typing something other than Y or N to see how the code reacts:
-
+
valid_input = False
response = input('Do you like lima beans? Y)es or N)o: ')
diff --git a/pretext/Iteration/The3n1Sequence.ptx b/pretext/Iteration/The3n1Sequence.ptx
index 40e4c4150..53cb7d31c 100644
--- a/pretext/Iteration/The3n1Sequence.ptx
+++ b/pretext/Iteration/The3n1Sequence.ptx
@@ -1,5 +1,5 @@
-
+The 3n + 1 Sequence
As another example of iteration with while, let's look at a sequence that has fascinated mathematicians for many years.
The rule for creating the sequence is to start from
@@ -8,7 +8,7 @@
whenever n is even, or else by multiplying it by three and adding 1 when it is odd. The sequence
terminates when n reaches 1.
This Python code captures that algorithm. Try running this program several times supplying different values for n.
-
+
n = 3
@@ -63,10 +63,10 @@
-
+
Check your understanding
-
+
Consider the code that prints the 3n+1 sequence in ActiveCode box 6. Will the while loop in this code always terminate for any positive integer value of n?
diff --git a/pretext/Iteration/TheforLoop.ptx b/pretext/Iteration/TheforLoop.ptx
index 3b4d6bc78..8efd54db4 100644
--- a/pretext/Iteration/TheforLoop.ptx
+++ b/pretext/Iteration/TheforLoop.ptx
@@ -1,5 +1,5 @@
-
+The for loop
The while statement is a general-purpose tool for iteration, and is necessary for any instance of iteration where we don't know how many repetitions will be needed.
However, if we do know how many are needed, there is a more efficient approach: the for statement.
@@ -7,7 +7,7 @@ However, if we do know how many are needed, there is a more efficient approach:
we'd like to send them each an email inviting them to our party. We
don't quite know how to send email yet, so for the moment we'll just print a
message for each friend.
-
+
for name in ["Joe", "Amy", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]:
print(f"Hi {name}! Please come to my party on Saturday!")
@@ -61,7 +61,7 @@ terminates.
Check your understanding
-
+
True or False: You can rewrite any for-loop as a while-loop.
diff --git a/pretext/Iteration/TherangeFunction.ptx b/pretext/Iteration/TherangeFunction.ptx
index a3bd46c3b..a3940ade1 100644
--- a/pretext/Iteration/TherangeFunction.ptx
+++ b/pretext/Iteration/TherangeFunction.ptx
@@ -1,5 +1,5 @@
-
+The range Function
In our first example of a while loop, we counted down from 10 to 0. If we were to consider doing this with a for loop, we would need to construct our own series of numbers
@@ -57,7 +57,7 @@ for x in range(10):
Here are two examples for you to run. Try them and then add another line below to create a sequence starting
at 10 and going up to 20 (including 20).
Codelens will help us to further understand the way range works. In this case, the variable i will take on values
produced by the range function.
-
+
for i in range(10):
print(i)
@@ -78,7 +78,7 @@ print(list(range(1, 5)))
range(0,19,2). The most general form of the range is
range(start, beyondLast, step). You can also create a sequence of numbers that
starts big and gets smaller by using a negative value for the step parameter.
-
+
print(list(range(0, 19, 2)))
print(list(range(0, 20, 2)))
@@ -86,7 +86,7 @@ print(list(range(10, 0, -1)))
Try it in codelens. Do you see why the first two statements produce the same result?
-
+
for i in range(0, 20, 2):
print(i)
@@ -95,7 +95,7 @@ for i in range(0, 20, 2):
Check your understanding
-
+
In the command range(3, 10, 2), what does the second argument (10) specify?
@@ -134,7 +134,7 @@ for i in range(0, 20, 2):
-
+
What command correctly generates the sequence 2, 5, 8?
@@ -173,7 +173,7 @@ for i in range(0, 20, 2):
-
+
What happens if you give range only one argument? For example: range(4)
@@ -212,7 +212,7 @@ for i in range(0, 20, 2):
-
+
Which range function call will produce the sequence 20, 15, 10, 5?
@@ -251,7 +251,7 @@ for i in range(0, 20, 2):
-
+
What could the second parameter (12) in range(2, 12, 4) be replaced with and generate exactly the same sequence?
diff --git a/pretext/Iteration/ThewhileStatement.ptx b/pretext/Iteration/ThewhileStatement.ptx
index 07e20b14d..4a1eca840 100644
--- a/pretext/Iteration/ThewhileStatement.ptx
+++ b/pretext/Iteration/ThewhileStatement.ptx
@@ -1,5 +1,5 @@
-
+The while Statement
Let's look at our first Python statement that can be used to build an iteration. It is called the while statement. When used with other code it can be used to
@@ -7,7 +7,7 @@
a boolean expression to control the flow of execution. The body of while (code indented one space in) will be repeated as long as the controlling boolean
expression evaluates to True.
Here is a simple example that counts down from 10 to 0.
-
+
count = 10
while count > 0:
@@ -71,7 +71,7 @@
Here is the summation program that uses a while statement.
-
+
""" Return the sum of 1+2+3 ... n """
aBound = int(input("Please give a number n: "))
@@ -90,7 +90,7 @@
The same program in codelens will allow you to observe the flow of execution.
-
+
""" Return the sum of 1+2+3 ... n """
aBound = int(input("Please give a number n: "))
@@ -110,7 +110,7 @@
This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
-
+
@@ -120,7 +120,7 @@
Check your understanding
-
+
True or False: You can rewrite any for-loop as a while-loop.
@@ -143,7 +143,7 @@
-
+
The following code contains an infinite loop. Which is the best explanation for why the loop does not terminate?
@@ -192,7 +192,7 @@ print(answer)
-
+
What is printed by this code?
diff --git a/pretext/Iteration/TraversalandtheforLoopByIndex.ptx b/pretext/Iteration/TraversalandtheforLoopByIndex.ptx
index 9850cc364..6dec6e390 100644
--- a/pretext/Iteration/TraversalandtheforLoopByIndex.ptx
+++ b/pretext/Iteration/TraversalandtheforLoopByIndex.ptx
@@ -1,11 +1,11 @@
-
+Traversing strings with the for Loop: By Index
It is also possible to use the range function to systematically generate the indices of the characters. The for loop can then be used to iterate over these positions.
These positions can be used together with the indexing operator to access the individual
characters in the string.
Consider the following codelens example.
-
+
fruit = "apple"
for idx in range(5):
@@ -17,7 +17,7 @@ for idx in range(5):
of the characters.
In order to make the iteration more general, we can use the len function to provide the bound for range. This is a very common pattern for traversing any sequence by position. Make sure you understand why the range function behaves
correctly when using len of the string as its parameter value.
-
+
fruit = "apple"
for idx in range(len(fruit)):
@@ -27,7 +27,7 @@ for idx in range(len(fruit)):
You may also note that iteration by position allows the programmer to control the direction of the
traversal by changing the sequence of index values. Recall that we can create ranges that count down as
well as up so the following code will print the characters from right to left.
-
+
fruit = "apple"
for idx in range(len(fruit)-1, -1, -1):
@@ -38,7 +38,7 @@ for idx in range(len(fruit)):
Check your understanding
-
+
How many times is the letter o printed by the following statements?
diff --git a/pretext/Iteration/TraversalandtheforLoopByItem.ptx b/pretext/Iteration/TraversalandtheforLoopByItem.ptx
index b92453001..b46bd2125 100644
--- a/pretext/Iteration/TraversalandtheforLoopByItem.ptx
+++ b/pretext/Iteration/TraversalandtheforLoopByItem.ptx
@@ -1,5 +1,5 @@
-
+Traversing strings with the for Loop: By Item
A lot of computations involve processing a collection one item at a time. For strings this means
that we would like to process one character at a time.
@@ -7,7 +7,7 @@
to it, and continue until the end. This pattern of processing is called a
traversal.
We have previously seen that the for statement can iterate over the items of a sequence (a list of names in the case below).
-
+
for aname in ["Joe", "Amy", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]:
invitation = "Hi " + aname + ". Please come to my party on Saturday!"
@@ -15,14 +15,14 @@ for aname in ["Joe", "Amy", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]:
Recall that the loop variable takes on each value in the sequence of names. The body is performed once for each name. The same was true for the sequence of integers created by the range function.
-
+
for avalue in range(10):
print(avalue)
Since a string is simply a sequence of characters, the for loop iterates over each character automatically.
-
+
for achar in "Go Spot Go":
print(achar)
@@ -34,7 +34,7 @@ for achar in "Go Spot Go":
Check your understanding
-
+
How many times is the word HELLO printed by the following statements?
@@ -80,7 +80,7 @@ for ch in s:
-
+
How many times is the word HELLO printed by the following statements?
diff --git a/pretext/Iteration/TraversalandthewhileLoop.ptx b/pretext/Iteration/TraversalandthewhileLoop.ptx
index 166c22bba..536875f57 100644
--- a/pretext/Iteration/TraversalandthewhileLoop.ptx
+++ b/pretext/Iteration/TraversalandthewhileLoop.ptx
@@ -1,11 +1,11 @@
-
+Traversal and the while Loop
The while loop can also control the
generation of index values used to navigate strings or lists. The programmer is responsible for setting up the initial
condition, making sure that the condition is correct, and making sure that something changes inside the
body to guarantee that the condition will eventually fail.
-
+
fruit = "apple"
@@ -20,7 +20,7 @@ while position < len(fruit):
executed. The last character accessed is the one with the index
len(fruit)-1, which is the last character in the string.
Here is the same example in codelens so that you can trace the values of the variables.
-
+
fruit = "apple"
@@ -33,7 +33,7 @@ while position < len(fruit):
Check your understanding
-
+
How many times is the letter o printed by the following statements?
@@ -75,7 +75,7 @@ while idx < len(s):
This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
Computers are often used to automate repetitive tasks. Repeating identical or
+
Computers are often used to automate repetitive tasks. Repeating identical or
similar tasks without making errors is something that computers do well and
people do poorly.
Repeated execution of a sequence of statements is called iteration. Because
diff --git a/pretext/Lists/AccessingElements.ptx b/pretext/Lists/AccessingElements.ptx
index d9cae3bd3..9d950f42e 100644
--- a/pretext/Lists/AccessingElements.ptx
+++ b/pretext/Lists/AccessingElements.ptx
@@ -7,7 +7,7 @@
the index. Remember that the indices start at 0. Any integer expression can be used
as an index and as with strings, negative index values will locate items from the right instead
of from the left.
diff --git a/pretext/Lists/AppendversusConcatenate.ptx b/pretext/Lists/AppendversusConcatenate.ptx
index 85d82a24c..e2c457658 100644
--- a/pretext/Lists/AppendversusConcatenate.ptx
+++ b/pretext/Lists/AppendversusConcatenate.ptx
@@ -3,7 +3,7 @@
Append versus Concatenate
The append method adds a new item to the end of a list. It is also possible to add a new item to the end of a list by using the concatenation operator. However, you need to be careful.
Consider the following example. The original list has 3 integers. We want to add the word cat to the end of the list.
Here we have used append which simply modifies the list. In order to use concatenation, we need to write an assignment statement that uses the accumulator pattern:
origlist = origlist + ["cat"]
Note that the word cat needs to be placed in a list since the concatenation operator needs two lists to do its work.
-
+
origlist = [45, 32, 88]
@@ -24,7 +24,7 @@ origlist = origlist + ["cat"]
On the other hand, with concatenation, an entirely new list is created. This can be seen in the following codelens example where
newlist refers to a list which is a copy of the original list, origlist, with the new item cat added to the end. origlist still contains the three values it did before the concatenation. This is why the assignment operation is necessary as part of the
accumulator pattern.
-
+
origlist = [45, 32, 88]
@@ -34,7 +34,7 @@ origlist = origlist + ["cat"]
It is important to see that these operators create new lists from the elements of the operand lists. If you concatenate a list with 2 items and a list with 4 items, you will get a new list with 6 items (not a list with two sublists). Similarly, repetition of a list of 2 items 4 times will give a list with 8 items.
One way for us to make this more clear is to run a part of this example in codelens. As you step through the code, you will see the variables being created and the lists that they refer to. Pay particular attention to the fact that when newlist is created by the statement newlist = fruit + numlist, it refers to a completely new list formed by making copies of the items from fruit and numlist. You can see this very clearly in the codelens object diagram. The objects are different.
Using slices to delete list elements can be awkward and therefore error-prone.
Python provides an alternative that is more readable.
The del statement removes an element from a list by using its position.
-
+
a = ['one', 'two', 'three']
del a[1]
@@ -22,7 +22,7 @@ print(alist)
index, but do not cause runtime errors if the index limits go too far.
This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
-
+
diff --git a/pretext/Lists/ListLength.ptx b/pretext/Lists/ListLength.ptx
index c7e1ca7fb..a16bd17a6 100644
--- a/pretext/Lists/ListLength.ptx
+++ b/pretext/Lists/ListLength.ptx
@@ -5,7 +5,7 @@
of items in the list). However, since lists can have items which are themselves lists, it important to note
that len only returns the top-most length. In other words, sublists are considered to be a single
item when counting the length of the list.
-
+
alist = ["hello", 2.0, 5, [10, 20]]
print(len(alist))
@@ -15,7 +15,7 @@ print(len(['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]))
Check your understanding
-
+
What is printed by the following statements?
@@ -44,7 +44,7 @@ print(len(alist))
-
+
What is printed by the following statements?
diff --git a/pretext/Lists/ListMethods.ptx b/pretext/Lists/ListMethods.ptx
index 263c05652..7fb739c5e 100644
--- a/pretext/Lists/ListMethods.ptx
+++ b/pretext/Lists/ListMethods.ptx
@@ -5,7 +5,7 @@
append is a list method which adds the argument passed to it to the end of
the list. Continuing with this example, we show several other list methods. Many of them are
easy to understand.
-
+
mylist = []
mylist.append(5)
@@ -192,7 +192,7 @@ print(mylist)
can be found in the Python Documentation.
It is important to remember that methods like append, sort,
and reverse all return None. This means that re-assigning mylist to the result of sorting mylist will result in losing the entire list. Calls like these will likely never appear as part of an assignment statement (see line 8 below).
This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
-
+
diff --git a/pretext/Lists/ListSlices.ptx b/pretext/Lists/ListSlices.ptx
index 4bdf72da5..6909e2054 100644
--- a/pretext/Lists/ListSlices.ptx
+++ b/pretext/Lists/ListSlices.ptx
@@ -5,7 +5,7 @@
that if you omit the first index (before the colon), the slice starts at the
beginning of the sequence. If you omit the second index, the slice goes to the
end of the sequence.
-
+
a_list = ['a', 'b', 'c', 'd', 'e', 'f']
print(a_list[1:3])
@@ -17,7 +17,7 @@ print(a_list[:])
Check your understanding
-
+
What is printed by the following statements?
@@ -62,7 +62,7 @@ print(alist[4:])
or the rate at which it decrements (if the step size is negative).
It is also possible to specify -1 as the step term to slice with the values in reverse.
-
+
What is printed by the following statements?
@@ -100,7 +100,7 @@ print(alist[1:5:2])
-
+
What is printed by the following statements?
diff --git a/pretext/Lists/ListValues.ptx b/pretext/Lists/ListValues.ptx
index b30b2b489..3acfed0ce 100644
--- a/pretext/Lists/ListValues.ptx
+++ b/pretext/Lists/ListValues.ptx
@@ -22,7 +22,7 @@
Finally, there is a special list that contains no elements. It is called the
empty list and is denoted [].
As you would expect, we can also assign list values to variables and pass lists as parameters to functions.
Unlike strings, lists are mutable. This means we can change an item in a list by accessing
it directly as part of the assignment statement. Using the indexing operator (square brackets) on the left side of an assignment, we can
update one of the list items.
-
+
fruit = ["banana", "apple", "cherry"]
print(fruit)
@@ -18,7 +18,7 @@ print(fruit)
assignment to an element of a list is called item assignment. Item
assignment does not work for strings. Recall that strings are immutable.
Here is the same example in codelens so that you can step through the statements and see the changes to the list elements.