diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..f9957a5 Binary files /dev/null and b/.DS_Store differ diff --git a/_sources/.DS_Store b/_sources/.DS_Store new file mode 100644 index 0000000..d5830f9 Binary files /dev/null and b/_sources/.DS_Store differ diff --git a/_sources/Assessments/.DS_Store b/_sources/Assessments/.DS_Store new file mode 100644 index 0000000..bace131 Binary files /dev/null and b/_sources/Assessments/.DS_Store differ diff --git a/_sources/Assessments/Figures/.DS_Store b/_sources/Assessments/Figures/.DS_Store new file mode 100644 index 0000000..eb179c6 Binary files /dev/null and b/_sources/Assessments/Figures/.DS_Store differ diff --git a/_sources/Assessments/Figures/week3a1_1.png b/_sources/Assessments/Figures/week3a1_1.png new file mode 100644 index 0000000..b56c2c0 Binary files /dev/null and b/_sources/Assessments/Figures/week3a1_1.png differ diff --git a/_sources/Assessments/Figures/week3a1_2.png b/_sources/Assessments/Figures/week3a1_2.png new file mode 100644 index 0000000..af01e3d Binary files /dev/null and b/_sources/Assessments/Figures/week3a1_2.png differ diff --git a/_sources/Assessments/Figures/week3a2_1.png b/_sources/Assessments/Figures/week3a2_1.png new file mode 100644 index 0000000..a6d88c1 Binary files /dev/null and b/_sources/Assessments/Figures/week3a2_1.png differ diff --git a/_sources/Assessments/Figures/week3a2_2.png b/_sources/Assessments/Figures/week3a2_2.png new file mode 100644 index 0000000..8d97cd4 Binary files /dev/null and b/_sources/Assessments/Figures/week3a2_2.png differ diff --git a/_sources/Assessments/Figures/week3a2_3.png b/_sources/Assessments/Figures/week3a2_3.png new file mode 100644 index 0000000..b0787c6 Binary files /dev/null and b/_sources/Assessments/Figures/week3a2_3.png differ diff --git a/_sources/Assessments/Figures/week3a2_4.png b/_sources/Assessments/Figures/week3a2_4.png new file mode 100644 index 0000000..f1dac0b Binary files /dev/null and b/_sources/Assessments/Figures/week3a2_4.png differ diff --git a/_sources/Assessments/Figures/week3a3_1.png b/_sources/Assessments/Figures/week3a3_1.png new file mode 100644 index 0000000..f6584b1 Binary files /dev/null and b/_sources/Assessments/Figures/week3a3_1.png differ diff --git a/_sources/Assessments/Figures/week3a3_2.png b/_sources/Assessments/Figures/week3a3_2.png new file mode 100644 index 0000000..8b440bb Binary files /dev/null and b/_sources/Assessments/Figures/week3a3_2.png differ diff --git a/_sources/Assessments/Figures/week3a3_3.png b/_sources/Assessments/Figures/week3a3_3.png new file mode 100644 index 0000000..45f40c5 Binary files /dev/null and b/_sources/Assessments/Figures/week3a3_3.png differ diff --git a/_sources/Assessments/Figures/week3a3_4.png b/_sources/Assessments/Figures/week3a3_4.png new file mode 100644 index 0000000..dc9605a Binary files /dev/null and b/_sources/Assessments/Figures/week3a3_4.png differ diff --git a/_sources/Assessments/assigmentcourseone.rst b/_sources/Assessments/assigmentcourseone.rst new file mode 100644 index 0000000..4af36ad --- /dev/null +++ b/_sources/Assessments/assigmentcourseone.rst @@ -0,0 +1,118 @@ +.. 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". + +Assignment +---------- + +.. activecode:: asign_c01_01 + :language: python + :autograde: unittest + :practice: T + :topics: + + **1.** Write code to determine how many vowels are in the text assigned to ``story``. Assign this number to the variable ``num_vowels``. Note that in this problem, only 'a', 'e', 'i', 'o', and 'u' count as vowels. + ~~~~ + story = """The quick brown fox jumped over the lazy dog. + By the end of the day, the fox had travelled far from home + and the dog had only made it down the street. This was not + an advantage for the dog though, because it still took both + animals the same amount of time to arrive at home.""" + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def testOne(self): + og_story = """The quick brown fox jumped over the lazy dog. + By the end of the day, the fox had travelled far from home + and the dog had only made it down the street. This was not + an advantage for the dog though, because it still took both + animals the same amount of time to arrive at home.""" + self.assertEqual(num_vowels, 80, "Testing that num_vowels is a number that contains the correct elements.") + self.assertEqual(story, og_story, "Testing that story is still the original string assigned.") + self.assertIn('for', self.getEditorText(), "Testing your code (Don't worry about actual and expected values.)") + + myTests().main() + +.. activecode:: asign_c01_02 + :language: python + :autograde: unittest + :practice: T + :topics: + + **2.** Write code that uses the string stored in ``org`` and creates an acronym which is assigned to the variable ``acro``. Only the first letter of each word should be used, each letter in the acronym should be a captial letter, and there should be nothing to separate the letters of the acronym. Words that should not be included in the acronym are stored in the list ``stopwords``. For example, if ``org`` was assigned the string "hello to world" then the resulting acronym should be "HW". + ~~~~ + stopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 'so', 'it', 'and'] + org = "The organization for health, saftey, and education" + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def testOne(self): + self.assertEqual(acro, 'OHSE', 'Checking that acro has been set correctly.') + self.assertTrue(type(acro) == type("string"), "Checking that acro is a string.") + self.assertIn('for', self.getEditorText(), "Testing your code (Don't worry about actual and expected values).") + + myTests().main() + +.. activecode:: asign_c01_03 + :language: python + :autograde: unittest + :practice: T + :topics: + + **3.** Write code that uses the string stored in ``sent`` and creates an acronym which is assigned to the variable ``acro``. The first two letters of each word should be used, each letter in the acronym should be a captial letter, and each element of the acronym should be separated by a ". ". Words that should not be included in the acronym are stored in the list ``stopwords``. For example, if ``sent`` was assigned the string "height and ewok wonder" then the resulting acronym should be "HE. EW. WO". + ~~~~ + stopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 'so', 'it', 'and'] + sent = "The water, earth, and air are vital." + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def testOne(self): + self.assertEqual(acro, 'WA. EA. AI. AR. VI', 'Checking that acro has been set correctly.') + self.assertTrue(type(acro) == type("string"), "Checking that acro is a string.") + self.assertIn('for', self.getEditorText(), "Testing your code (Don't worry about actual and expected values).") + + myTests().main() + +.. activecode:: asign_c01_04 + :language: python + :autograde: unittest + :practice: T + :topics: + + **3.** Write code that checks if ``p_phrase`` is a palindrome. A palindrome is a phrase that, if reversed, would read the exact same. Assign the reversed version of ``p_phrase`` to the variable ``r_phrase``. + ~~~~ + p_phrase = "was it a car or a cat I saw" + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def testOne(self): + self.assertEqual(r_phrase, "was I tac a ro rac a ti saw", "checking that r_phrase is set correctly") + stripped_phrase = p_phrase.replace(" ", "").lower() + stripped_r_phrase = r_phrase.replace(" ", "").lower() + self.assertEqual(stripped_phrase, stripped_r_phrase, "checking that r_phrase and p_phrase are equivalent if the spaces are placed in the correct locations.") + self.assertIsNot(p_phrase, r_phrase, "checking that r_phrase and p_phrase are not the same object.") + + myTests().main() + + diff --git a/_sources/Assessments/week1a1.rst b/_sources/Assessments/week1a1.rst new file mode 100644 index 0000000..7548ba8 --- /dev/null +++ b/_sources/Assessments/week1a1.rst @@ -0,0 +1,88 @@ +.. 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". + +Week 1 Assessment 1 +------------------- + +**Check your understanding** + +.. mchoice:: question1_1_1 + :answer_a: A solution to a problem that can be solved by a computer. + :answer_b: A step by step list of instructions that if followed exactly will solve the problem under consideration. + :answer_c: A series of instructions implemented in a programming language. + :answer_d: A special kind of notation used by programmers. + :feedback_a: While it is true that algorithms often do solve problems, this is not the best answer. An algorithm is more than just the solution to the problem for a computer. An algorithm can be used to solve all sorts of problems, including those that have nothing to do with computers. + :feedback_b: Algorithms are like recipes: they must be followed exactly, they must be clear and unambiguous, and they must end. + :feedback_c: Programming languages are used to express algorithms, but an algorithm does not have to be expressed in terms of a programming language. + :feedback_d: Programmers sometimes use a special notation to illustrate or document an algorithm, but this is not the definition of an algorithm. + :correct: b + :practice: T + :topics: GeneralIntro/Algorithms + + An algorithm is: + +.. mchoice:: question1_1_2 + :answer_a: Because computers are better at solving problems. + :answer_b: So that you don't have to solve the problem yourself. + :answer_c: So that you have a general solution to a problem. + :answer_d: Because you need a set of instructions to follow. + :feedback_a: Computers aren't necessarily better at solving problems, though often they can be quicker than humans. Additionally, algorithms can be used to solve non-computer related problems. + :feedback_b: While it is beneficial to have a set of instructions that others can follow, this isn't the best answer. By creating the algorithm, you solve a problem for yourself and others. + :feedback_c: Yes, by creating a general solution you can then express it as a program if you choose, and then use a computer to automate the execution. + :feedback_d: While it is beneficial to have a set of instructions as that is what an algorithm **is**, it is not **why** we would want to create one. + :correct: c + :practice: T + :topics: GeneralIntro/Algorithms + + Why create an algorithm? + + +.. mchoice:: question1_1_3 + :answer_a: natural languages can be parsed while formal languages cannot. + :answer_b: ambiguity, redundancy, and literalness. + :answer_c: there are no differences between natural and formal languages. + :answer_d: tokens, structure, syntax, and semantics. + :feedback_a: Actually both languages can be parsed (determining the structure of the sentence), but formal languages can be parsed more easily in software. + :feedback_b: All of these can be present in natural languages, but cannot exist in formal languages. + :feedback_c: There are several differences between the two but they are also similar. + :feedback_d: These are the similarities between the two. + :correct: b + :practice: T + :topics: GeneralIntro/FormalandNaturalLanguages + + The differences between natural and formal languages include: + +.. mchoice:: question1_1_4 + :answer_a: True + :answer_b: False + :feedback_a: It usually takes longer to read a program because the structure is as important as the content and must be interpreted in smaller pieces for understanding. + :feedback_b: It usually takes longer to read a program because the structure is as important as the content and must be interpreted in smaller pieces for understanding. + :correct: b + :practice: T + :topics: GeneralIntro/FormalandNaturalLanguages + + True or False: Reading a program is like reading other kinds of text. + +.. activecode:: question1_1_5 + :language: python + :autograde: unittest + + 1 Write code to print out the phrase "Hello World". + ~~~~ + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def testOne(self): + self.assertIn("Hello World", self.getOutput(), "Testing output (Don't worry about actual and expected values).") + + myTests().main() diff --git a/_sources/Assessments/week1a2.rst b/_sources/Assessments/week1a2.rst new file mode 100644 index 0000000..492f63c --- /dev/null +++ b/_sources/Assessments/week1a2.rst @@ -0,0 +1,102 @@ +.. 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". + +Week 1 Assessment 2 +------------------- + +**Check your understanding** + +.. activecode:: ps_01_02 + :include: addl_functions + :language: python + :autograde: unittest + :topics: SimplePythonData/FunctionCalls + + **1.** There is a function we are providing in for you in this problem called ``square``. It takes one integer and returns the square of that integer value. Write code to assign a variable called ``xyz`` the value ``5*5`` (five squared). Use the square function, rather than just multiplying with ``*``. + ~~~~ + xyz = "" + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def testOne(self): + self.assertEqual(type(xyz), type(3), "Checking type of xyz") + self.assertEqual(xyz, 25, "Checking if xyz is 25") + self.assertIn('square', self.getEditorText(), "Testing that 'square' is in your code. (Don't worry about Actual and Expected Values.)") + + myTests().main() + +.. activecode:: ps_01_01 + :language: python + :autograde: unittest + :practice: T + :topics: Sequences/SplitandJoin + + **2.** Write code to assign the number of *characters* in the string ``rv`` to a variable ``num_chars``. + ~~~~ + rv = """Once upon a midnight dreary, while I pondered, weak and weary, + Over many a quaint and curious volume of forgotten lore, + While I nodded, nearly napping, suddenly there came a tapping, + As of some one gently rapping, rapping at my chamber door. + 'Tis some visitor, I muttered, tapping at my chamber door; + Only this and nothing more.""" + + # Write your code here! + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def testOne(self): + self.assertEqual(num_chars, len(rv), "Testing that num_chars has been set to the length of rv") + + myTests().main() + + +.. mchoice:: question1_1_1_3 + :multiple_answers: + :answer_a: a = len("hello worldwelcome!") + :answer_b: a = 11 + 8 + :answer_c: a = len(z) + len(y) + :answer_d: a = len("hello world") + len("welcome!") + :answer_e: none of the above are hardcoding. + :feedback_a: Though we are using the len function here, we are hardcoding what len should return the length of. We are not referencing z or y. + :feedback_b: This is hardcoding, we are writing in the value without referencing z or y. + :feedback_c: This is not considered hard coding. We are using the function len to determine the length of what is stored in z and y, which is a correct way to approach this problem. + :feedback_d: Though we are using the len function here, we are hardcoding what len should return the length of each time we call len. We are not referencing z or y. + :feedback_e: At least one of these solutions is considered hardcoding. Take another look. + :correct: a,b,d + :practice: T + :topics: + + The code below initializes two variables, ``z`` and ``y``. We want assign the total number of characters in ``z`` and in ``y`` to the variable ``a``. Which of the following solutions, if any, would be considered hard coding? + + .. sourcecode:: python + + z = "hello world" + y = "welcome!" + + +.. activecode:: addl_functions + :language: python + :nopre: + :hidecode: + + (This is not an assessment question) The code below defines functions used by one of the questions above. Do not modify the code, but feel free to take a look. + + ~~~~ + + def square(num): + return num**2 + diff --git a/_sources/Assessments/week1a3.rst b/_sources/Assessments/week1a3.rst new file mode 100644 index 0000000..c18aa23 --- /dev/null +++ b/_sources/Assessments/week1a3.rst @@ -0,0 +1,157 @@ +.. 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". + +Week 1 Assessment 3 +------------------- + +**Check your understanding** + +.. mchoice:: question1_3_1_1_1 + :multiple_answers: + :answer_a: Tex.forward(20) + :answer_b: forward() + 20 + :answer_c: forward(20) + :answer_d: forward(20).Tex + :answer_e: Tex.forward(10 + 10) + :feedback_a: This is a correct way to move a turtle forward. + :feedback_b: This does not use the turtle method necessary to move a turtle forward. Additionally, how would the program know what turtle should be moving? + :feedback_c: This does not use the turtle method necessary to move a turtle forward. Additionally, how would the program know what turtle should be moving? + :feedback_d: This is not the correct structure to execute the task. + :feedback_e: You are allowed to write expressions inside of methods, so this is correctly written. + :correct: a,e + :practice: T + :topics: PythonTurtle/InstancesAHeardofTurtles + + What are correct ways to tell a turtle named Tex to move forward 20 pixels? Select as many as apply. + +.. mchoice:: question1_3_1_1_2 + :answer_a: turtle(Turtle) + :answer_b: turtle.Turtle() + :answer_c: Turtle.turtle() + :answer_d: Turtle(turtle) + :feedback_a: When making a new instace of the turtle class, you need to use dot notation. + :feedback_b: Yes, this is the correct way. + :feedback_c: turtle represents the class and should be first. + :feedback_d: When making a new instace of the turtle class, you need to use dot notation. + :correct: b + :practice: T + :topics: + + Which is the correct way to make a new instance of the Turtle class? + +.. mchoice:: question1_3_1_1_3 + :answer_a: The turtle class. + :answer_b: The same turtle that is used in each drawing your programs make. + :answer_c: A unique 'turtle' that you can use to draw. + :feedback_a: Though each instance does use the turtle class, this is not the best answer. + :feedback_b: Each instance that is made using the turtle class is unique. Remember how you can have multiple 'turtles' in a single drawing? Each of those are different turtles but they are all instances of the turtle class. + :feedback_c: Yes, an instance of the turtle class represents a unique turtle. The turtle class is like a stencil or mold that can be used to make as many turtles as you would like. + :correct: c + :practice: T + :topics: + + What does each instance of the Turtle class represent? + +.. mchoice:: question1_3_1_1_4 + :answer_a: True + :answer_b: False + :feedback_a: Just like the variables you've learned about so far, you can assign values to an attribute and look up the values that are assigned to the attribute. + :feedback_b: The only difference is the structure that is used to refer to it. + :correct: a + :practice: T + :topics: + + True or False, attributes/instance variables are just like other variables in Python? + +.. mchoice:: question1_3_1_1_5 + :multiple_answers: + :answer_a: Change the value of an attribute. + :answer_b: Return values. + :answer_c: Create new attributes and set their value. + :answer_d: Delete instances of a class. + :answer_e: None of the above. + :feedback_a: Methods can change the value that is associated with an attribute. + :feedback_b: Methods can return values. + :feedback_c: Methods can create new attributes and then set that attribute's value. + :feedback_d: Methods cannot delete instances of a class. + :feedback_e: Methods can do at least one of the above. Take another look. + :correct: a,b,c + :practice: T + :topics: + + Select all of the following things that methods can do: + + +.. mchoice:: question1_3_1_1_6 + :answer_a: student.title() + :answer_b: title.student() + :answer_c: title.student + :answer_d: student(title) + :answer_e: student.title + :correct: e + :feedback_a: This is not the structure used to refer to an attribute. + :feedback_b: This is not the structure or order used to refer to an attribute. + :feedback_c: This is not the order used to refer to an attribute. + :feedback_d: This would be the syntax for a function named student being called on a variable named title. + :feedback_e: Yes, this is the correct structure to use. + :practice: T + :topics: + + For an instance of a class that is assigned to the variable ``student``, what is the propper way to refer to the ``title`` attribute/instance variable? + +.. fillintheblank:: question1_3_1_1_7 + + What is the name of the attribute in the following code? + + .. sourcecode:: python + + import turtle + + jane = turtle.Turtle() + jane.forward(20) + print(jane.x) + + The attribute is + + - :x: Good work! + :jane: jane is an instance, not an attribute. + :forward: forward is a method, not an attribute. + :turtle: turtle is the class, not an attribute. + :Turtle: Turtle is a method, not an attribute + :.*: Incorrect, try again. + +.. fillintheblank:: question1_3_1_1_8 + + What is the name of the instances in the following code? Please put one instance per blank space and enter them in the order that the computer would read them. + + .. sourcecode:: python + + import turtle + wn = turtle.Screen() + + jazz = turtle.Turtle() + jazz.forward(50) + jazz.right(90) + pop = turtle.Turtle() + pop.left(180) + pop.forward(76) + + + - :wn: Good work! + :jazz: Try a different location + :pop: Try a different location + :.*: Incorrect, try again. + - :jazz: Good work! + :wn: Try a different location + :pop: Try a different location + :.*: Incorrect, try again. + - :pop: Good work! + :wn: Try a different location + :jazz: Try a different location + :.*: Incorrect, try again. diff --git a/_sources/Assessments/week1a4.rst b/_sources/Assessments/week1a4.rst new file mode 100644 index 0000000..2057d3b --- /dev/null +++ b/_sources/Assessments/week1a4.rst @@ -0,0 +1,22 @@ +.. 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". + +Week 1 Assessment 4 +------------------- + +**Check your understanding** + +.. activecode:: ps_01_09 + :language: python + :topics: PythonTurtle/OurFirstTurtleProgram + + **9.** Write a program that uses the turtle module to draw something. It doesn't have to be complicated, but draw something different than we have done in the past. (Hint: if you are drawing something complicated, it could get tedious to watch it draw over and over. Try setting ``.speed(10)`` for the turtle to draw fast, or ``.speed(0)`` for it to draw super fast with no animation.) + ~~~~ + import turtle + diff --git a/_sources/Assessments/week2a1.rst b/_sources/Assessments/week2a1.rst new file mode 100644 index 0000000..05360c0 --- /dev/null +++ b/_sources/Assessments/week2a1.rst @@ -0,0 +1,195 @@ +.. 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". + +Week 2 Assessment 1 +------------------- + +**Check your understanding** + + +.. activecode:: ps_02_01 + :language: python + :autograde: unittest + :practice: T + :topics: Iteration/Stringsandforloops + + **1.** Write one for loop to print out each character of the string ``my_str`` on a separate line. + ~~~~ + my_str = "MICHIGAN" + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def test_output(self): + self.assertIn('for', self.getEditorText(), "Testing your code (Don't worry about actual and expected values).") + self.assertIn("M\nI\nC\nH\nI\nG\nA\nN", self.getOutput(), "Testing output (Don't worry about actual and expected values).") + + myTests().main() + + +.. activecode:: ps_02_02 + :language: python + :autograde: unittest + :practice: T + :topics: Iteration/Listsandforloops + + **2.** Write one for loop to print out each element of the list ``several_things``. Then, write *another* for loop to print out the TYPE of each element of the list ``several_things``. To complete this problem you should have written two different for loops, each of which iterates over the list ``several_things``, but each of those 2 for loops should have a different result. + ~~~~ + several_things = ["hello", 2, 4, 6.0, 7.5, 234352354, "the end", "", 99] + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def test_output(self): + self.assertIn('for', self.getEditorText(), "Testing your code (Don't worry about actual and expected values).") + str1 = "hello\n2\n4\n6.0\n7.5\n234352354\nthe end\n\n99\n\n\n\n\n\n\n\n\n" + str2 = "hello\n2\n4\n6.0\n7.5\n234352354\nthe end\n\n99\n\n\n\n\n\n\n\n\n" + self.assertTrue(str1 in self.getOutput() or str2 in self.getOutput(), "Testing output (Don't worry about actual and expected values).") + + myTests().main() + + +.. activecode:: ps_02_03 + :language: python + :autograde: unittest + :practice: T + :topics: Iteration/Listsandforloops + + **3.** Write code that uses iteration to print out **the length** of each element of the list stored in ``str_list``. + ~~~~ + str_list = ["hello", "", "goodbye", "wonderful", "I love Python"] + + # Write your code here. + ===== + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + def test_output(self): + self.assertIn("for", self.getEditorText(), "Testing whether you used a for loop (Don't worry about actual and expected values).") + self.assertIn("5\n0\n7\n9\n13", self.getOutput(), "Testing output (Don't worry about actual and expected values).") + + myTests().main() + + +.. activecode:: ps_02_04 + :language: python + :autograde: unittest + :topics: Iteration/Listsandforloops + + **4.** Write a program that uses the turtle module **and** a for loop to draw something. It doesn't have to be complicated, but draw something different than we have done in the past. (Hint: if you are drawing something complicated, it could get tedious to watch it draw over and over. Try setting ``.speed(10)`` for the turtle to draw fast, or ``.speed(0)`` for it to draw super fast with no animation.) + ~~~~ + import turtle + + +.. activecode:: ps_02_05 + :language: python + :autograde: unittest + :practice: T + :topics: Iteration/TheAccumulatorPatternwithStrings + + **5.** Write code to count the number of characters in ``original_str`` using the accumulation pattern and assign the answer to a variable ``num_chars``. Do NOT use the ``len`` function to solve the problem (if you use it while you are working on this problem, comment it out afterward!) + ~~~~ + original_str = "The quick brown rhino jumped over the extremely lazy fox." + + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def testOne(self): + self.assertEqual(num_chars, len(original_str), "Testing whether num_chars_sent has the correct value") + self.assertNotIn('len', self.getEditorText(), "Testing that you are not including the len function in your code. (Don't worry about Actual and Expected Values.)") + + myTests().main() + + +.. activecode:: ps_02_06 + :language: python + :autograde: unittest + :practice: T + :topics: Iteration/TheAccumulatorPatternwithLists + + **6.** Write code to create a **list of word lengths** for the words in ``original_str`` using the accumulation pattern and assign the answer to a variable ``num_words_list``. (You should use the ``len`` function). + + ~~~~ + original_str = "The quick brown rhino jumped over the extremely lazy fox." + + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def testOne(self): + self.assertEqual(num_words_list, map(len, original_str.split()), "Testing whether num_words_list has the correct value") + self.assertIn('for', self.getEditorText(), "Testing that you are using a for loop in your code. (Don't worry about Actual and Expected Values.)") + + myTests().main() + + +.. activecode:: ps_02_07 + :language: python + :autograde: unittest + :practice: T + :topics: Iteration/TheAccumulatorPatternwithLists + + **7.** ``addition_str`` is a string with a list of numbers separated by the ``+`` sign. Write code that uses the accumulation pattern to take the sum of all of the numbers and assigns it to ``sum_val`` (an integer). (You should use the ``.split("+")`` function to split by ``"+"`` and ``int()`` to cast to an integer). + + ~~~~ + addition_str = "2+5+10+20" + + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def testOne(self): + self.assertEqual(sum_val, 37, "Testing whether sum_val has the correct value") + self.assertIn('split', self.getEditorText(), "Testing your code (Don't worry about actual and expected values).") + self.assertIn('int', self.getEditorText(), "Testing your code (Don't worry about actual and expected values).") + + myTests().main() + + +.. activecode:: ps_02_08 + :language: python + :autograde: unittest + :practice: T + :topics: Iteration/TheAccumulatorPatternwithLists + + **8.** ``week_temps_f`` is a string with a list of fahrenheit temperatures separated by the ``,`` sign. Write code that uses the accumulation pattern to compute the **average** (sum divided by number of items) and assigns it to ``avg_temp``. Do not hard code your answer (i.e., make your code compute both the sum or the number of items in ``week_temps_f``) (You should use the ``.split(",")`` function to split by ``","`` and ``float()`` to cast to a float). + + ~~~~ + week_temps_f = "75.1,77.7,83.2,82.5,81.0,79.5,85.7" + + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def testOne(self): + self.assertAlmostEqual(avg_temp, 80.67142857142858, 7, "Testing that avg_temp has the correct value") + self.assertIn('split', self.getEditorText(), "Testing your code (Don't worry about actual and expected values).") + self.assertIn('float', self.getEditorText(), "Testing your code (Don't worry about actual and expected values).") + + myTests().main() + diff --git a/_sources/Assessments/week3a1.rst b/_sources/Assessments/week3a1.rst new file mode 100644 index 0000000..b7a7805 --- /dev/null +++ b/_sources/Assessments/week3a1.rst @@ -0,0 +1,139 @@ +.. 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". + +Week 3 Assessment 1 +------------------- + +**Check your understanding** + +.. mchoice:: question3_1_1_1 + :answer_a: I. + :answer_b: II. + :answer_c: Neither is the correct reference diagram. + :feedback_a: Yes, when we are using the remove method, we are just editing the existing list, not making a new copy. + :feedback_b: When we use the remove method, we just edit the existing list. We do not make a new copy that does not include the removed object. + :feedback_c: One of the diagrams is correct - look again at what is happening to lst. + :correct: a + :practice: T + :topics: + + Which of these is a correct reference diagram following the execution of the following code? + + .. sourcecode:: python + + lst = ['mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune', 'pluto'] + lst.remove('pluto') + first_three = lst[:2] + + I. + + .. image:: Figures/week3a1_1.png + :alt: First Potential Solution + + II. + + .. image:: Figures/week3a1_2.png + :alt: Second Potential Solution + +.. mchoice:: question3_1_1_2 + :answer_a: ['travel', 'lights', 'moon'] + :answer_b: ['world', 'travel', 'lights'] + :answer_c: ['travel', 'lights'] + :answer_d: ['world', 'travel'] + :feedback_a: When we take a slice of something, it is inclusive of the first number and exclusive of the second. + :feedback_b: When we take a slice of something, it is inclusive of the first number and exclusive of the second. Additionally, Python is a zero-index based language. + :feedback_c: Yes, python is a zero-index based language and slices are inclusive of the first number and exclusive of the second. + :feedback_d: Python is a zero-index based language. + :correct: c + :practice: T + :topics: + + What will the output be for the following code? + + .. sourcecode:: python + + ls = ['run', 'world', 'travel', 'lights', 'moon', 'baseball', 'sea'] + new = ls[2:4] + print(new) + +.. mchoice:: question3_1_1_3 + :answer_a: zpzpzpzpzp + :answer_b: zzzzzppppp + :answer_c: pzpzpzpzpz + :answer_d: pppppzzzzz + :answer_e: None of the above, an error will occur. + :feedback_a: The order of concatenation matters. + :feedback_b: Think about the order that the program is executed in, what occurs first? + :feedback_c: Yes, because let_two was put before let, c has "pz" and then that is repeated five times. + :feedback_d: Think about the order that the program is executed in, what occurs first? + :feedback_e: This is correct syntax and no errors will occur. + :correct: c + :practice: T + :topics: + + What will the output be for the following code? + + .. sourcecode:: python + + let = "z" + let_two = "p" + c = let_two + let + m = c*5 + print(m) + +.. activecode:: a_03_01_01 + :language: python + :topics: Sequences/ListSlices + + **4.** Write a program that extracts the last three items in the list ``sports`` and assigns it to the variable ``last``. Make sure to write your code so that it works no matter how many items are in the list. + ~~~~ + sports = ['cricket', 'football', 'volleyball', 'baseball', 'softball', 'track and field', 'curling', 'ping pong', 'hockey'] + + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def test_output(self): + self.assertEqual(last, ['curling', 'ping pong', 'hockey'], "Testing that the value of last is the last three items in sports.") + self.assertNotIn("[6:]", self.getEditorText(), "Testing that your code would work no matter how many items. (Don't worry about actual and expected values).") + + + myTests().main() + +.. activecode:: a_03_01_02 + :language: python + :topics: + + **5.** Write code that combines the following variables so that the sentence "You are doing a great job, keep it up!" is assigned to the variable ``message``. Do not edit the values assigned to ``by``, ``az``, ``io``, or ``qy``. + ~~~~ + by = "You are" + az = "doing a great " + io = "job" + qy = "keep it up!" + + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def test_output(self): + self.assertEqual(by, 'You are', "Testing original variables.") + self.assertEqual(az, 'doing a great ', "Testing original variables.") + self.assertEqual(io, 'job', "Testing original variables.") + self.assertEqual(qy, 'keep it up!', "Testing original variables.") + self.assertEqual(message, 'You are doing a great job, keep it up!', "Testing that the value of message is what was expected.") + self.assertNotIn("You are doing a great job, keep it up!", self.getEditorText(), "Testing for hardcoding (Don't worry about actual and expected values).") + + + myTests().main() \ No newline at end of file diff --git a/_sources/Assessments/week3a2.rst b/_sources/Assessments/week3a2.rst new file mode 100644 index 0000000..61d4e7a --- /dev/null +++ b/_sources/Assessments/week3a2.rst @@ -0,0 +1,335 @@ +.. 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". + +Week 3 Assessment 2 +------------------- + +**Check your understanding** + +.. mchoice:: question3_2_1_1_1 + :answer_a: string + :answer_b: integer + :answer_c: float + :answer_d: list + :feedback_a: Not quite, is it slicing or accessing an element? + :feedback_b: What is happening in the assigment statement for m? + :feedback_c: What is happening in the assigment statement for m? + :feedback_d: Yes, a slice returns a list no matter how large the slice. + :correct: d + :practice: T + :topics: + + What is the type of ``m``? + + .. sourcecode:: python + + l = ['w', '7', 0, 9] + m = l[1:2] + +.. mchoice:: question3_2_1_1_2 + :answer_a: string + :answer_b: integer + :answer_c: float + :answer_d: list + :feedback_a: Yes, the quotes around the number mean that this is a string. + :feedback_b: Not quite, look again at what is being extracted. + :feedback_c: Not quite, look again at what is being extracted. + :feedback_d: Not quite, is it slicing or accessing an element? + :correct: a + :practice: T + :topics: + + What is the type of ``m``? + + .. sourcecode:: python + + l = ['w', '7', 0, 9] + m = l[1] + +.. mchoice:: question3_2_1_1_3 + :answer_a: string + :answer_b: integer + :answer_c: float + :answer_d: list + :feedback_a: Not quite, think about what the result of .split() is. + :feedback_b: Not quite, look again at what types are present and what the result of .split() is. + :feedback_c: Not quite, look again at what types are present and what the result of .split() is. + :feedback_d: Yes, the .split() method returns a list. + :correct: d + :practice: T + :topics: + + What is the type of ``x``? + + .. sourcecode:: python + + b = "My, what a lovely day" + x = b.split(',') + +.. mchoice:: question3_2_1_1_4 + :answer_a: string + :answer_b: integer + :answer_c: float + :answer_d: list + :feedback_a: Yes, the string is split into a list, then joined back into a string, then split again, and finally joined back into a string. + :feedback_b: Not quite, look again at what types are present and what the result of .split() is. + :feedback_c: Not quite, look again at what types are present and what the result of .split() is. + :feedback_d: Not quite, think about what .split() and .join() return. + :correct: a + :practice: T + :topics: + + What is the type of ``a``? + + .. sourcecode:: python + + b = "My, what a lovely day" + x = b.split(',') + z = "".join(x) + y = z.split() + a = "".join(y) + + +.. mchoice:: question3_2_1_1_5 + :answer_a: I. + :answer_b: II. + :answer_c: III. + :answer_d: IV. + :feedback_a: Yes, when we make our own diagrams we want to keep the old information because sometimes other variables depend on them. It can get cluttered though if there is a lot of information. + :feedback_b: Not quite, we want to keep track of old information because sometimes other variables depend on them. + :feedback_c: Look again at what is happening when join is executed. + :feedback_d: What happens to the spaces in a string when it is split by whitespace? + :correct: a + :practice: T + :topics: + + Which of these is a correct reference diagram following the execution of the following code? + + .. sourcecode:: python + + sent = "The mall has excellent sales right now." + wrds = sent.split() + wrds[1] = 'store' + new_sent = " ".join(wrds) + + I. + + .. image:: Figures/week3a2_1.png + :alt: First Potential Solution + + II. + + .. image:: Figures/week3a2_2.png + :alt: Second Potential Solution + + III. + + .. image:: Figures/week3a2_3.png + :alt: Third Potential Solution + + IV. + + .. image:: Figures/week3a2_4.png + :alt: Fourth Potential Solution + + +.. mchoice:: question3_2_1_1_6 + :answer_a: .pop() + :answer_b: .insert() + :answer_c: .count() + :answer_d: .index() + :feedback_a: pop removes and returns items (default is to remove and return the last item in the list) + :feedback_b: insert will add an item at whatever position is specified. + :feedback_c: count returns the number of times something occurs in a list + :feedback_d: Yes, index will return the position of the first occurance of an item. + :correct: d + :practice: T + :topics: + + Which method would you use to figure out the position of an item in a list? + +.. mchoice:: question3_2_1_1_7 + :answer_a: .insert() + :answer_b: .pop() + :answer_c: .append() + :answer_d: .remove() + :feedback_a: While you can use insert, it is not the best method to use because you need to specify that you want to stick the new item at the end. + :feedback_b: pop removes an item from a list + :feedback_c: Yes, though you can use insert to do the same thing, you don't need to provide the position. + :feedback_d: remove gets rid of the first occurance of any item that it is told. It does not add an item. + :correct: c + :practice: T + :topics: + + Which method best to use when adding an item to the end of a list? + +.. activecode:: a_03_02_01 + :language: python + :topics: Sequences/ListSlices + + **8.** Write code to add 'horseback riding' to the third position (english third) in the list ``sports``. + ~~~~ + sports = ['cricket', 'football', 'volleyball', 'baseball', 'softball', 'track and field', 'curling', 'ping pong', 'hockey'] + + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def test_output(self): + self.assertEqual(sports, ['cricket', 'football', 'horseback riding', 'volleyball', 'baseball', 'softball', 'track and field', 'curling', 'ping pong', 'hockey'], "Testing that sports is set correctly (Don't worry about actual and expected values).") + + myTests().main() + +.. activecode:: a_03_02_02 + :language: python + :topics: Sequences/ListSlices + + **9.** Write code to take 'London' out of the list ``trav_dest``. + ~~~~ + trav_dest = ['Beirut', 'Milan', 'Pittsburgh', 'Buenos Aires', 'Nairobi', 'Kathmandu', 'Osaka', 'London', 'Melbourne'] + + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def test_output(self): + self.assertEqual(trav_dest, ['Beirut', 'Milan', 'Pittsburgh', 'Buenos Aires', 'Nairobi', 'Kathmandu', 'Osaka', 'Melbourne'], "Testing that trav_dest is set correctly (Don't worry about actual and expected values).") + + myTests().main() + + +.. activecode:: a_03_02_03 + :language: python + :topics: Sequences/ListSlices + + **10.** Write code to add 'Guadalajara' to the end of the list ``trav_dest`` using a list method. + ~~~~ + trav_dest = ['Beirut', 'Milan', 'Pittsburgh', 'Buenos Aires', 'Nairobi', 'Kathmandu', 'Osaka', 'Melbourne'] + + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def test_output(self): + self.assertEqual(trav_dest, ['Beirut', 'Milan', 'Pittsburgh', 'Buenos Aires', 'Nairobi', 'Kathmandu', 'Osaka', 'Melbourne', 'Guadalajara'], "Testing that trav_dest is set correctly (Don't worry about actual and expected values).") + self.assertNotIn('+', self.getEditorText(), "Testing your code (Don't worry about actual and expected values).") + self.assertIn('.', self.getEditorText(), "Testing that a method was used in your code (Don't worry about actual and expected values).") + + myTests().main() + +.. activecode:: a_03_02_04 + :language: python + :topics: Sequences/ListSlices + + **11.** Write code to find the postion of the string "Tony" in the list ``awards`` and save that information in the variable ``pos``. + ~~~~ + awards = ['Emmy', 'Tony', 'Academy', 'Grammy'] + + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def test_output(self): + self.assertEqual(pos, 1, "Testing that pos is set correctly (Don't worry about actual and expected values).") + + myTests().main() + +.. activecode:: a_03_02_05 + :language: python + :topics: Sequences/ListSlices + + **12.** Write code to rearrage the strings in the list ``winners`` so that they are in alphabetical order from A to Z. + ~~~~ + winners = ['Kazuo Ishiguro', 'Rainer Weiss', 'Youyou Tu', 'Malala Yousafzai', 'Alice Munro', 'Alvin E. Roth'] + + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def test_output(self): + self.assertEqual(winners, ['Alice Munro', 'Alvin E. Roth', 'Kazuo Ishiguro', 'Malala Yousafzai', 'Rainer Weiss', 'Youyou Tu'], "Testing that winners is set correctly (Don't worry about actual and expected values).") + + myTests().main() + +.. activecode:: a_03_02_06 + :language: python + :topics: Sequences/ListSlices + + **13.** Write code to switch the order of the ``winners`` list so that it is now Z to A. Assign this list to the variable ``z_winners``. + ~~~~ + winners = ['Alice Munro', 'Alvin E. Roth', 'Kazuo Ishiguro', 'Malala Yousafzai', 'Rainer Weiss', 'Youyou Tu'] + + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def test_output(self): + self.assertEqual(z_winners, ['Youyou Tu','Rainer Weiss', 'Malala Yousafzai','Kazuo Ishiguro', 'Alvin E. Roth', 'Alice Munro'], "Testing that z_winners is set correctly (Don't worry about actual and expected values).") + + myTests().main() + +.. activecode:: a_03_02_07 + :language: python + :topics: Sequences/ListSlices + + **14.** Write code to determine how many 9's are in the list ``nums`` and assign that value to the variable ``how_many``. Do not use a for loop to do this. + ~~~~ + nums = [4, 2, 23.4, 9, 545, 9, 1, 234.001, 5, 49, 8, 9 , 34, 52, 1, -2, 9.1, 4] + + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def test_output(self): + self.assertEqual(how_many, 3, "Testing that how_many is set correctly (Don't worry about actual and expected values).") + self.assertNotIn('for', self.getEditorText(), "Testing your code (Don't worry about actual and expected values).") + + myTests().main() + + +.. activecode:: a_03_02_08 + :language: python + :topics: Sequences/ListSlices + + **14.** Write code to get rid of the the second 8 so that here are only two 8's in the list nums. + ~~~~ + nums = [4, 2, 8, 23.4, 8, 9, 545, 9, 1, 234.001, 5, 49, 8, 9 , 34, 52, 1, -2, 9.1, 4] + + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def test_output(self): + self.assertEqual(nums, [4, 2, 8, 23.4, 9, 545, 9, 1, 234.001, 5, 49, 8, 9 , 34, 52, 1, -2, 9.1, 4], "Testing that nums is set correctly (Don't worry about actual and expected values).") + + myTests().main() \ No newline at end of file diff --git a/_sources/Assessments/week3a3.rst b/_sources/Assessments/week3a3.rst new file mode 100644 index 0000000..11615ad --- /dev/null +++ b/_sources/Assessments/week3a3.rst @@ -0,0 +1,129 @@ +.. 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". + +Week 3 Assessment 3 +------------------- + +**Check your understanding** + +.. fillintheblank:: question3_3_1_1 + + What will be the value of ``a`` after the following code has executed? + + .. sourcecode:: python + + a = ["holiday", "celebrate!"] + quiet = a + quiet.append("company") + + + The value of ``a`` will be + + - :\[["']holiday["'], ["']celebrate!["'], ["']company["']\]: Good work! + :\[["']holiday["'], ["']celebrate!["']\]: This is the old value of a - a has changed. + :.*: Incorrect, try again. + +.. mchoice:: question3_3_1_2 + :answer_a: yes + :answer_b: no + :feedback_a: Yes, the intent by the programmer was not executed properly if they wanted to print the list ['q', 'u'] because of aliasing. + :feedback_b: If the intent was to print the list ['q', 'u'] then aliasing would cause a problem because z also replaces the 'u' with an 'i'. + :correct: a + :practice: T + :topics: + + Could aliasing cause potential confusion in this problem? + + .. sourcecode:: python + + b = ['q', 'u', 'i'] + z = b + b[1] = 'i' + z.remove('i') + print(z) + +.. mchoice:: question3_3_1_3 + :answer_a: yes + :answer_b: no + :feedback_a: Though both lists have changed, it is not as likely to cause confusion. + :feedback_b: These operations on the lists are not likely to cause confusion. + :correct: b + :practice: T + :topics: + + Could aliasing cause potential confusion in this problem? + + .. sourcecode:: python + + b = ['q', 'u', 'i'] + z = b + b[1] = 'i' + for elem in b: + print(elem) + for item in z: + print(item) + +.. mchoice:: question3_3_1_4 + :answer_a: yes + :answer_b: no + :feedback_a: Since a string is immutable, aliasing won't be as confusing. Beware of using something like item = item + new_item with mutable objects though because it creates a new object. However, when we use += then that doesn't happen. + :feedback_b: Since a string is immutable, aliasing won't be as confusing. Beware of using something like item = item + new_item with mutable objects though because it creates a new object. However, when we use += then that doesn't happen. + :correct: b + :practice: T + :topics: + + Could aliasing cause potential confusion in this problem? + + .. sourcecode:: python + + sent = "Holidays can be a fun time when you have good company!" + phrase = sent + phrase = phrase + " Holidays can also be fun on your own!" + +.. mchoice:: question3_3_1_5 + :answer_a: I. + :answer_b: II. + :answer_c: III. + :answer_d: IV. + :feedback_a: When an object is concatinated with another using +=, a new copy is made. If this is done in the longer form (item = item + object) then it edits the original object. + :feedback_b: When an object is concatinated with another using +=, a new copy is made. If this is done in the longer form (item = item + object) then it edits the original object. + :feedback_c: When an object is concatinated with another using +=, a new copy is made. If this is done in the longer form (item = item + object) then it edits the original object. + :feedback_d: Yes, the behavior of item = item + object_two is different than item += object_two where the first version makes a new object entirely and the second version changes the original object so that object_two is added to the first. + :correct: d + :practice: T + :topics: + + Which of these is a correct reference diagram following the execution of the following code? + + .. sourcecode:: python + + x = ["dogs", "cats", "birds", "reptiles"] + y = x + x += ['fish', 'horses'] + y = y + ['sheep'] + + I. + + .. image:: Figures/week3a3_1.png + :alt: First Potential Solution + + II. + + .. image:: Figures/week3a3_2.png + :alt: Second Potential Solution + + III. + + .. image:: Figures/week3a3_3.png + :alt: Third Potential Solution + + IV. + + .. image:: Figures/week3a3_4.png + :alt: Fourth Potential Solution diff --git a/_sources/Assessments/week4a1.rst b/_sources/Assessments/week4a1.rst new file mode 100644 index 0000000..f768a84 --- /dev/null +++ b/_sources/Assessments/week4a1.rst @@ -0,0 +1,150 @@ +.. 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". + +Week 4 Assignment +----------------- + +**Check your understanding** + +.. activecode:: ps_03_01 + :language: python + :autograde: unittest + :practice: T + :topics: Iteration/TheAccumulatorPattern + + **1.** ``rainfall_mi`` is a string that contains the average number of inches of rainfall in Michigan for every month (in inches) with every month separated by a comma. + Write code to compute the number of months that have more than 3 inches of rainfall. Store the result in the variable ``num_rainy_months``. + In other words, count the number of items with values ``> 3.0``. + + + Hard-coded answers will receive no credit. + ~~~~ + rainfall_mi = "1.65, 1.46, 2.05, 3.03, 3.35, 3.46, 2.83, 3.23, 3.5, 2.52, 2.8, 1.85" + ===== + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + def testOne(self): + self.assertIn('for', self.getEditorText(), "Testing that your code has a for loop (Don't worry about actual and expected values).") + self.assertEqual(num_rainy_months, 5, "Testing that num_rainy_months has the right value") + + myTests().main() + +.. activecode:: ps_03_02 + :language: python + :autograde: unittest + :practice: T + :topics: Iteration/TheAccumulatorPattern + + **2.** The variable ``sentence`` stores a string. Write code to determine how many words in ``sentence`` start and end with the same letter, including one-letter words. + Store the result in the variable ``same_letter_count``. + + + Hard-coded answers will receive no credit. + ~~~~ + sentence = "students flock to the arb for a variety of outdoor activities such as jogging and picnicking" + + # Write your code here. + + + ==== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + def testOne(self): + self.assertEqual(same_letter_count, 2, "Checking that same_letter_count has the correct value") + + myTests().main() + +.. activecode:: ps_03_03 + :language: python + :autograde: unittest + :practice: T + :topics: Iteration/TheAccumulatorPattern + + **3.** Write code to count the number of strings in list ``items`` that have the character ``w`` in it. Assign that number to the variable ``acc_num``. + + HINT 1: Use the accumulation pattern! + + HINT 2: the ``in`` operator checks whether a substring is present in a string. + + + Hard-coded answers will receive no credit. + ~~~~ + items = ["whirring", "wow!", "calendar", "wry", "glass", "", "llama","tumultuous","owing"] + + + ===== + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + def testOne(self): + self.assertIn(' in ', self.getEditorText(), "Testing your code (Don't worry about actual and expected values).") + self.assertEqual(acc_num, 4, "Testing that acc_num has been set to the number of strings that have 'w' in them.") + + myTests().main() + +.. activecode:: ps_03_04 + :language: python + :autograde: unittest + :practice: T + :topics: Iteration/TheAccumulatorPattern + + **4.** Write code that counts the number of words in ``sentence`` that contain *either* an "a" or an "e". Store the result in the variable ``num_a_or_e``. + + Note 1: be sure to not double-count words that contain both an a and an e. + + HINT 1: Use the ``in`` operator. + + HINT 2: You can either use ``or`` or ``elif``. + + + Hard-coded answers will receive no credit. + ~~~~ + sentence = "python is a high level general purpose programming language that can be applied to many different classes of problems." + + + ===== + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + def testOne(self): + self.assertIn(' in ', self.getEditorText(), "Testing your code (Don't worry about actual and expected values).") + self.assertEqual(num_a_or_e, 14, "Testing that num_a_or_e has been set to the correct number.") + + myTests().main() + +.. activecode:: ps_04_03 + :language: python + :autograde: unittest + :practice: T + :topics: Iteration/TheAccumulatorPattern + + **3.** Write code that will count the number of vowels in the sentence ``s`` and assign the result to the variable ``num_vowels``. For this problem, vowels are only a, e, i, o, and u. Hint: use the ``in`` operator with ``vowels``. + ~~~~ + s = "singing in the rain and playing in the rain are two entirely different situations but both can be fun" + vowels = ['a','e','i','o','u'] + + # Write your code here. + + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def testOne(self): + self.assertEqual(num_vowels, 32, "testing whether num_vowels is set correctly") + + def testOneA(self): + self.assertIn('for', self.getEditorText(), "Testing your code (Don't worry about actual and expected values).") + + myTests().main() diff --git a/_sources/Assessments/week5a1.rst b/_sources/Assessments/week5a1.rst new file mode 100644 index 0000000..5453bb8 --- /dev/null +++ b/_sources/Assessments/week5a1.rst @@ -0,0 +1,122 @@ +.. 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". + +Week 5 Assessment 1 +------------------- + +**Check your understanding** + +.. mchoice:: question5_1_1_1 + :answer_a: byzo + :answer_b: x + :answer_c: z + :answer_d: c + :feedback_a: This is the variable with our string, but it does not accumulate anything. + :feedback_b: This is the iterator variable. It changes each time but does not accumulate. + :feedback_c: This is a variable inside the for loop. It changes each time but does not accumulate or retain the old expressions that were assigned to it. + :feedback_d: Yes, this is the accumulator variable. By the end of the program, it will have a full count of how many items are in byzo. + :correct: d + :practice: T + :topics: + + Which of these is the accumulator variable? + + .. sourcecode:: python + + byzo = 'hello world!' + c = 0 + for x in byzo: + z = x + "!" + print(z) + c = c + 1 + +.. mchoice:: question5_1_1_2 + :answer_a: cawdra + :answer_b: elem + :answer_c: t + :feedback_a: Yes, this is the sequence that we iterate over. + :feedback_b: This is the iterator variable. It changes each time but is not the whole sequence itself. + :feedback_c: This is the accumulator variable. By the end of the program, it will have a full count of how many items are in cawdra. + :correct: a + :practice: T + :topics: + + Which of these is the sequence? + + .. sourcecode:: python + + cawdra = ['candy', 'daisy', 'pear', 'peach', 'gem', 'crown'] + t = 0 + for elem in cawdra: + t = t + len(elem) + +.. mchoice:: question5_1_1_3 + :answer_a: item + :answer_b: lst + :answer_c: num + :feedback_a: Yes, this is the iterator variable. It changes each time but is not the whole sequence itself. + :feedback_b: This is the sequence that we iterate over. + :feedback_c: This is the accumulator variable. By the end of the program, it will have the total value of the integers that are in lst. + :correct: a + :practice: T + :topics: + + Which of these is the iterator variable? + + .. sourcecode:: python + + lst = [5, 10, 3, 8, 94, 2, 4, 9] + num = 0 + for item in lst: + num += item + +.. fillintheblank:: question5_1_1_4 + + What is the iterator variable in the following? + + .. sourcecode:: python + + rest = ["sleep", 'dormir', 'dormire', "slaap", 'sen', 'yuxu', 'yanam'] + let = '' + for phrase in rest: + let += phrase[0] + + The iterator variable is + + - :phrase: Good work! + :rest: rest is the sequence, not the iterator variable. + :let: let is the accumulator variable, not the iterator variable. + :.*: Incorrect, try again. + + + +.. activecode:: assess_week5_01 + :language: python + :autograde: unittest + :practice: T + :topics: Iteration/TheAccumulatorPatternwithStrings + + 2. Currently there is a string called ``str1``. Write code to create a list called ``chars`` which should contain the characters from ``str1``. Each character in ``str1`` should be its own element in the list ``chars``. + ~~~~ + str1 = "I love python" + # HINT: what's the accumulator? That should go here. + + ===== + + from unittest.gui import TestCaseGui + + class myTests(TestCaseGui): + + def testOne(self): + self.assertEqual(chars, ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'p', 'y', 't', 'h', 'o', 'n'], "Testing that chars is assigned to correct values.") + + myTests().main() + + + diff --git a/_sources/Assessments/week5a2.rst b/_sources/Assessments/week5a2.rst new file mode 100644 index 0000000..232f514 --- /dev/null +++ b/_sources/Assessments/week5a2.rst @@ -0,0 +1,183 @@ +.. 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". + +Week 5 Assessment 2 +------------------- + +**Check your understanding** + +.. mchoice:: question5_2_1_1 + :answer_a: I. + :answer_b: II. + :answer_c: III. + :answer_d: none of the above would be appropriate for the problem. + :feedback_a: This pattern will only count how many items are in the list, not provide the total accumulated value. + :feedback_b: This would reset the value of s each time the for loop iterated, and so by the end s would be assigned the value of the last item in the list plus the last item in the list. + :feedback_c: Yes, this will solve the problem. + :feedback_d: One of the patterns above is a correct way to solve the problem. + :correct: c + :practice: T + :topics: + + Given that we want to accumulate the total sum of a list of numbers, which of the following accumulator patterns would be appropriate? + + I. + + .. sourcecode:: python + + nums = [4, 5, 2, 93, 3, 5] + s = 0 + for n in nums: + s = s + 1 + + II. + + .. sourcecode:: python + + nums = [4, 5, 2, 93, 3, 5] + s = 0 + for n in nums: + s = n + n + + III. + + .. sourcecode:: python + + nums = [4, 5, 2, 93, 3, 5] + s = 0 + for n in nums: + s = s + n + + +.. mchoice:: question5_2_1_2 + :answer_a: I. + :answer_b: II. + :answer_c: III. + :answer_d: IV. + :answer_e: none of the above would be appropriate for the problem. + :feedback_a: How does this solution know that the element of lst is a string and that s should be updated? + :feedback_b: What happens to s each time the for loop iterates? + :feedback_c: Reread the prompt again, what do we want to accumulate? + :feedback_d: Yes, this will solve the problem. + :feedback_e: One of the patterns above is a correct way to solve the problem. + :correct: d + :practice: T + :topics: + + Given that we want to accumulate the total number of strings in the list, which of the following accumulator patterns would be appropriate? + + I. + + .. sourcecode:: python + + lst = ['plan', 'answer', 5, 9.29, 'order, items', [4]] + s = 0 + for n in nums: + s = s + n + + II. + + .. sourcecode:: python + + lst = ['plan', 'answer', 5, 9.29, 'order, items', [4]] + for n in nums: + s = 0 + if type(n) == type("string"): + s = s + 1 + + III. + + .. sourcecode:: python + + lst = ['plan', 'answer', 5, 9.29, 'order, items', [4]] + s = "" + for n in nums: + s = s + n + + IV. + + .. sourcecode:: python + + lst = ['plan', 'answer', 5, 9.29, 'order, items', [4]] + s = 0 + for n in nums: + if type(n) == type("string"): + s = s + 1 + +.. mchoice:: question5_2_1_3 + :multiple_answers: + :answer_a: sum + :answer_b: x + :answer_c: total + :answer_d: accum + :answer_e: none of the above + :feedback_a: No, though sum might be clear, it is also the name of a commonly used function in Python, and so there can be issues if sum is used as an accumulator variable. + :feedback_b: No, x is not a clear enough name to be used for an accumulator variable. + :feedback_c: Yes, total is a good name for accumulating numbers. + :feedback_d: Yes, accum is a good name. It's both short and easy to remember. + :feedback_e: At least one of the answers above is a good name for an accumulator variable. + :correct: c,d + :practice: T + :topics: + + Which of these are good names for an accumulator variable? Select as many as apply. + +.. mchoice:: question5_2_1_4 + :multiple_answers: + :answer_a: item + :answer_b: y + :answer_c: elem + :answer_d: char + :answer_e: none of the above + :feedback_a: Yes, item can be a good name to use as an iterator variable. + :feedback_b: No, y is not likely to be a clear name for the iterator variable. + :feedback_c: Yes, elem can be a good name to use as an iterator variable, especially when iterating over lists. + :feedback_d: Yes, char can be a good name to use when iterating over a string, because the iterator variable would be assigned a character each time. + :feedback_e: At least one of the answers above is a good name for an iterator variable. + :correct: a,c,d + :practice: T + :topics: + + Which of these are good names for an iterator variable? Select as many as apply. + +.. mchoice:: question5_2_1_5 + :multiple_answers: + :answer_a: num_lst + :answer_b: p + :answer_c: sentence + :answer_d: names + :answer_e: none of the above + :feedback_a: Yes, num_lst is good for a sequence variable if the value is actually a list of numbers. + :feedback_b: No, p is not likely to be a clear name for the iterator variable. + :feedback_c: Yes, this is good to use if the for loop is iterating through a string. + :feedback_d: Yes, names is good, assuming that the for loop is iterating through actual names and not something unrelated to names. + :feedback_e: At least one of the answers above is a good name for a sequence variable + :correct: a,c,d + :practice: T + :topics: + + Which of these are good names for a sequence variable? Select as many as apply. + +.. mchoice:: question5_2_1_6 + :answer_a: accumulator variable: x | iterator variable: s | sequence variable: lst + :answer_b: accumulator variable: total | iterator variable: s | sequence variable: lst + :answer_c: accumulator variable: x | iterator variable: sentences | sequence variable: word_lst + :answer_d: accumulator variable: total | iterator variable: sentences |sequence variable: word_lst + :answer_e: none of the above + :feedback_a: Though lst may be a good name, x and s are not clear names for accumulator and iterator variables. + :feedback_b: Though total, and lst may be good names, there is a more clear option since s is not very clear. + :feedback_c: Though sentences and word_lst are good names, x is not the best name for an accumulator variable. + :feedback_d: Yes, this combination of variable names is the most clear. + :feedback_e: One of the options above has good names for the scenario. + :correct: d + :practice: T + :topics: + + Given the following scenario, what are good names for the accumulator variable, iterator variable, and sequence variable? You are writing code that uses a list of sentences and accumulates the total number of sentences that have the word 'happy' in them. + diff --git a/_sources/Classes/AddingOtherMethodstoourClass.rst b/_sources/Classes/AddingOtherMethodstoourClass.rst index 7b931c7..dd72628 100644 --- a/_sources/Classes/AddingOtherMethodstoourClass.rst +++ b/_sources/Classes/AddingOtherMethodstoourClass.rst @@ -10,22 +10,40 @@ Adding Other Methods to a Class ------------------------------- -The key advantage of using a class like ``Point`` rather than something like a simple -tuple ``(7, 6)`` now becomes apparent. We can add methods to -the ``Point`` class that are sensible operations for points. Had we chosen to use a -tuple to represent the point, we would not have this capability. -Creating a class like ``Point`` brings an exceptional -amount of "organizational power" to our programs, and to our thinking. -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 list bound to variable L, ``L.append(7)`` calls the function append, with the list itself as the first parameter and 7 as the second parameter. Methods are accessed using dot notation. This is why ``L.append(7)`` has 2 parameters even though you may think it only has one: the list stored in the variable ``L`` is the first parameter value and 7 is the second. +The key advantage of using a class like ``Point`` rather than something like a simple tuple ``(7, 6)`` now becomes +apparent. We can add methods to the ``Point`` class that are sensible operations for points. Had we chosen to use +a tuple to represent the point, we would not have this capability. Creating a class like ``Point`` brings an +exceptional amount of "organizational power" to our programs, and to our thinking. 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 list bound to +variable L, ``L.append(7)`` calls the function append, with the list itself as the first parameter and 7 as the +second parameter. Methods are accessed using dot notation. This is why ``L.append(7)`` has 2 parameters even +though you may think it only has one: the list stored in the variable ``L`` is the first parameter value and 7 is +the second. + +We can visualize a method (called doThing for this example) in the following way. The shapes on top will allow for +two parameters/arguments and the shape on the bottom will allow for one return value. + +.. image:: Figures/method.png + :alt: a square with two outcroppings on the top, which represent parameters, and one outcroping on the bottom, which represents the return value. + +When the method is inside the class then, we can take some of our instance variables, or even new arguments in this +case, and do some action. Here, when doThing is called we will provide a number as an argument (as demonstrated by +the blue and yellow piece.doThing(5) image above the factory). This means that for the blue/yellow piece, we will +do something with the number to result in a return value. A more indepth explanation will be provided later on. -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. +.. image:: Figures/class_with_method_example.png + :alt: the method doThing is now in the class, and takes one of the instance variables and a new number in order to put out a return value. -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 a reference to the object itself which in turn gives access to the state data inside the object. +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 a reference +to the object itself which in turn gives access to the state data inside the object. .. activecode:: chp13_classes4 @@ -48,11 +66,13 @@ to write functions that return values. One thing to notice is that even though print(p.getX()) print(p.getY()) -Note that the ``getX`` method simply returns the value of the instance variable x from the object self. In other words, the implementation of the method is to go to the state of the object itself and get the value of ``x``. Likewise, the ``getY`` method looks almost the same. +Note that the ``getX`` method simply returns the value of the instance variable x from the object self. In other +words, the implementation of the method is to go to the state of the object itself and get the value of ``x``. +Likewise, the ``getY`` method looks almost the same. -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, beyond the data stored in the instance variables. -It will perform a more complex task. +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, beyond the data stored in the instance variables. It will perform a more +complex task. .. activecode:: chp13_classes5 @@ -77,9 +97,6 @@ It will perform a more complex task. p = Point(7,6) print(p.distanceFromOrigin()) - -Notice that the call of ``distanceFromOrigin`` does not *explicitly* -supply an argument to match the ``self`` parameter. This is true of all method calls. The definition will always seem to -have one additional parameter as compared to the invocation. - - +Notice that the call of ``distanceFromOrigin`` does not *explicitly* supply an argument to match the ``self`` +parameter. This is true of all method calls. The definition will always seem to have one additional parameter as +compared to the invocation. diff --git a/_sources/Classes/Figures/.DS_Store b/_sources/Classes/Figures/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/_sources/Classes/Figures/.DS_Store differ diff --git a/_sources/Classes/Figures/class_example.png b/_sources/Classes/Figures/class_example.png new file mode 100644 index 0000000..60e5159 Binary files /dev/null and b/_sources/Classes/Figures/class_example.png differ diff --git a/_sources/Classes/Figures/class_instance_representation.png b/_sources/Classes/Figures/class_instance_representation.png new file mode 100644 index 0000000..ea6dada Binary files /dev/null and b/_sources/Classes/Figures/class_instance_representation.png differ diff --git a/_sources/Classes/Figures/class_with_method_example.png b/_sources/Classes/Figures/class_with_method_example.png new file mode 100644 index 0000000..d0cfd38 Binary files /dev/null and b/_sources/Classes/Figures/class_with_method_example.png differ diff --git a/_sources/Classes/Figures/creating_instance.gif b/_sources/Classes/Figures/creating_instance.gif new file mode 100644 index 0000000..31b18e9 Binary files /dev/null and b/_sources/Classes/Figures/creating_instance.gif differ diff --git a/_sources/Classes/Figures/method.png b/_sources/Classes/Figures/method.png new file mode 100644 index 0000000..9a95849 Binary files /dev/null and b/_sources/Classes/Figures/method.png differ diff --git a/_sources/Classes/ImprovingourConstructor.rst b/_sources/Classes/ImprovingourConstructor.rst index 2eed1c7..9afc421 100644 --- a/_sources/Classes/ImprovingourConstructor.rst +++ b/_sources/Classes/ImprovingourConstructor.rst @@ -11,11 +11,13 @@ Adding Parameters to the Constructor ------------------------------------- -Our constructor so far can only create points at location ``(0,0)``. To create a point at position (7, 6) requires that we -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. +Our constructor so far can only create points at location ``(0,0)``. To create a point at position (7, 6) requires +that we 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 generally usable by putting extra parameters into -the ``__init__`` method, as shown in this example. +We can make our class constructor more generally usable by putting extra parameters into the ``__init__`` method, +as shown in this example. .. sourcecode:: python @@ -31,9 +33,20 @@ the ``__init__`` method, as shown in this example. Now when we create new points, we supply the x and y coordinates as parameters. When the point is created, the values of ``initX`` and ``initY`` are assigned to the state of the object, in the **instance variables** x and y. -This is a common thing to do in the ``__init__`` method for a class: take in some parameters and save them as instance variables. Why is this useful? Keep in mind that the parameter variables will go away when the method is finished executing. The instance variables, however, will still be accessible anywhere that you have a handle on the object instance. This is a way of saving those initial values that are provided when the class constructor is invoked. +This process is animated below: - Later on, you will see classes where the ``__init__`` method does more than just save parameters as instance variables. For example, it might parse the contents of those variables and do some computation on them, storing the results in instance variables. It might even make an Internet connection, download some content, and store that in instance variables. +.. image:: Figures/creating_instance.gif + :alt: the steps a computer takes to create a new instance of a class that takes two arguments and makes three instance variables. + +This is a common thing to do in the ``__init__`` method for a class: take in some parameters and save them as +instance variables. Why is this useful? Keep in mind that the parameter variables will go away when the method is +finished executing. The instance variables, however, will still be accessible anywhere that you have a handle on the +object instance. This is a way of saving those initial values that are provided when the class constructor is invoked. + + Later on, you will see classes where the ``__init__`` method does more than just save parameters as instance + variables. For example, it might parse the contents of those variables and do some computation on them, storing the + results in instance variables. It might even make an Internet connection, download some content, and store that in + instance variables. .. image:: Figures/objectpic5.png :alt: Simple object has state and methods diff --git a/_sources/Classes/UserDefinedClasses.rst b/_sources/Classes/UserDefinedClasses.rst index 7cb4d14..3e3195f 100644 --- a/_sources/Classes/UserDefinedClasses.rst +++ b/_sources/Classes/UserDefinedClasses.rst @@ -14,16 +14,14 @@ User Defined Classes -------------------- -We've already seen classes like ``str``, ``int``, ``float`` and ``list``. These were defined by Python and +We've already seen classes like ``str``, ``int``, ``float`` and ``list``. 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. +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 -numbers (coordinates) that are treated collectively as a single object. -Points are often written in parentheses with a comma -separating the coordinates. For example, ``(0, 0)`` represents the origin, and -``(x, y)`` represents the point ``x`` units to the right and ``y`` units up -from the origin. This ``(x,y)`` is the state of the point. +As an example, consider the concept of a mathematical point. In two dimensions, a point is two numbers +(coordinates) that are treated collectively as a single object. Points are often written in parentheses with a +comma separating the coordinates. For example, ``(0, 0)`` represents the origin, and ``(x, y)`` represents the +point ``x`` units to the right and ``y`` units up from the origin. This ``(x,y)`` is the state of the point. Thinking about our diagram above, we could draw a ``point`` object as shown here. @@ -31,20 +29,18 @@ Thinking about our diagram above, we could draw a ``point`` object as shown here :alt: A point has an x and a y -Some of the typical operations that one associates with points might be to ask -the point for its x coordinate, ``getX``, or to ask for its y coordinate, ``getY``. You would want these types of functions available to prevent accidental changes to these instance variables since doing so would allow you to view the values without accessing them directly. You may also -wish to calculate the distance of a point from the origin, or the distance of a point from another point, -or find the midpoint between two points, or answer the question as to whether a point falls within a -given rectangle or circle. We'll shortly see how we can organize these -together with the data. +Some of the typical operations that one associates with points might be to ask the point for its x coordinate, +``getX``, or to ask for its y coordinate, ``getY``. You would want these types of functions available to prevent +accidental changes to these instance variables since doing so would allow you to view the values without accessing +them directly. You may also wish to calculate the distance of a point from the origin, or the distance of a point +from another point, or find the midpoint between two points, or answer the question as to whether a point falls +within a given rectangle or circle. We'll shortly see how we can organize these together with the data. .. image:: Figures/objectpic3.png :alt: A point also has methods - Now that we understand what a ``point`` object might look like, we can define a new **class**. -We'll want our points to each have an ``x`` and a ``y`` attribute, -so our first class definition looks like this. +We'll want our points to each have an ``x`` and a ``y`` attribute, so our first class definition looks like this. .. sourcecode:: python :linenos: @@ -57,25 +53,26 @@ so our first class definition looks like this. self.x = 0 self.y = 0 -Class definitions can appear anywhere in a program, but they are usually near -the beginning (after the ``import`` statements). The syntax rules for a class -definition are the same as for other compound statements. There is a header -which begins with the keyword, ``class``, followed by the name of the class, -and ending with a colon. +Class definitions can appear anywhere in a program, but they are usually near the beginning (after the +``import`` statements). The syntax rules for a class definition are the same as for other compound +statements. There is a header which begins with the keyword, ``class``, followed by the name of the class, and +ending with a colon. + +If the first line after the class header is a string, it becomes the docstring of the class, and will be recognized +by various tools. (This is also the way docstrings work in functions.) -If the first line after the class header is a string, it becomes -the docstring of the class, and will be recognized by various tools. (This -is also the way docstrings work in functions.) +Every class should have a method with the special name ``__init__``. This **initializer method**, often referred to +as the **constructor**, is automatically called whenever a new instance of ``Point`` is created. It gives the +programmer the opportunity to set up the attributes required within the new instance by giving them their initial +state values. The ``self`` parameter (you could choose any other name, but nobody ever does!) is automatically set +to reference the newly created object that needs to be initialized. -Every class should have a method with the special name ``__init__``. -This **initializer method**, often referred to as the **constructor**, is automatically called whenever a new -instance of ``Point`` is created. It gives the programmer the opportunity -to set up the attributes required within the new instance by giving them -their initial state values. The ``self`` parameter (you could choose any -other name, but nobody ever does!) is automatically set to reference -the newly created object that needs to be initialized. +You can think of a class as a factory, which can produce instances. -So let's use our new Point class now. This next part should look a little familiar, if you remember some of the syntax for how we created instances of the Turtle class, in the :ref:`chapter on Turtle graphics `. +.. image:: Figures/class_instance_representation.png + +So let's use our new Point class now. This next part should look a little familiar, if you remember some of the +syntax for how we created instances of the Turtle class, in the :ref:`chapter on Turtle graphics `. .. activecode:: chp13_classes1 @@ -92,20 +89,22 @@ So let's use our new Point class now. This next part should look a little famili print("Nothing seems to have happened with the points") - -During the initialization of the objects, we created two -attributes called ``x`` and ``y`` for each object, and gave them both the value 0. You will note that when you run the -program, nothing happens. It turns out that this is not quite the case. In fact, two ``Points`` have been created, each -having an x and y coordinate with value 0. However, because we have not asked the program to do anything with the points, we don't see any other result. - +During the initialization of the objects, we created two attributes called ``x`` and ``y`` for each object, and +gave them both the value 0. You will note that when you run the program, nothing happens. It turns out that this +is not quite the case. In fact, two ``Points`` have been created, each having an x and y coordinate with value 0. +However, because we have not asked the program to do anything with the points, we don't see any other result. .. image:: Figures/objectpic4.png :alt: Simple object has state and methods +Below is a more detailed look at the class that's constructed as a factory which was mentioned earlier. Inside the +class are some methods - the __init__, met_1, and met_2 - as well as some attributes - var1 and var2. +.. image:: Figures/class_example.png -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 section). +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 section). .. activecode:: chp13_classes2 @@ -126,20 +125,17 @@ However, notice that the ``is`` operator returns ``False`` meaning that they are print(p is q) -A function like ``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. -The definition of the constructor function is done -when you write the ``__init__`` function (method) inside the class definition. +A function like ``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. The definition of the constructor function is +done when you write the ``__init__`` function (method) inside the class definition. -It may be helpful to think of a class as a factory for making objects. -The class itself isn't an instance of a point, but it contains the machinery -to make point instances. Every time you call the constructor, you're asking -the factory to make you a new object. As the object comes off the -production line, its initialization method is executed to -get the object properly set up with it's factory default settings. +It may be helpful to think of a class as a factory for making objects. The class itself isn't an instance of a +point, but it contains the machinery to make point instances. Every time you call the constructor, you're asking +the factory to make you a new object. As the object comes off the production line, its initialization method is +executed to get the object properly set up with it's factory default settings. -The combined process of "make me a new object" and "get its settings initialized -to the factory default settings" is called **instantiation**. +The combined process of "make me a new object" and "get its settings initialized to the factory default settings" +is called **instantiation**. To get a clearer understanding of what happens when instantiating a new instance, examine the previous code using CodeLens. @@ -162,8 +158,13 @@ To get a clearer understanding of what happens when instantiating a new instance print(p is q) -At Step 6 in the CodeLens execution, you can see that Point has been bound to an object representing the point class, but there are not yet any instances. The execution of line 9, ``p = Point()``, occurs at steps 7-9. First, at step 7, you can see that a blank instance of the class has been created, and is passed as the first (and only parameter) to the ``__init__`` method. That method's code is executed, with the variable self bound to that instance. At steps 8 and 9, two instance variables are filled in: x and y are both set to 0. Nothing is returned from the ``__init__`` method, but the point object itself is returned from the call to ``Point()``. Thus, at step 10, p is bound to the new point that was created and initialized. - -Skipping ahead, by the time we get to Step 16, p and q are each bound to different points. Even though both have x and y instance variables set to 0, they are *different objects*. Thus ``p is q`` evaluates to False. - - +At Step 6 in the CodeLens execution, you can see that Point has been bound to an object representing the point +class, but there are not yet any instances. The execution of line 9, ``p = Point()``, occurs at steps 7-9. First, +at step 7, you can see that a blank instance of the class has been created, and is passed as the first (and only +parameter) to the ``__init__`` method. That method's code is executed, with the variable self bound to that +instance. At steps 8 and 9, two instance variables are filled in: x and y are both set to 0. Nothing is returned +from the ``__init__`` method, but the point object itself is returned from the call to ``Point()``. Thus, at step +10, p is bound to the new point that was created and initialized. + +Skipping ahead, by the time we get to Step 16, p and q are each bound to different points. Even though both have x +and y instance variables set to 0, they are *different objects*. Thus ``p is q`` evaluates to False. diff --git a/_sources/Exceptions/.DS_Store b/_sources/Exceptions/.DS_Store new file mode 100644 index 0000000..8b65e7f Binary files /dev/null and b/_sources/Exceptions/.DS_Store differ diff --git a/_sources/Exceptions/Figures/exception_types.png b/_sources/Exceptions/Figures/exception_types.png new file mode 100644 index 0000000..ab44ee8 Binary files /dev/null and b/_sources/Exceptions/Figures/exception_types.png differ diff --git a/_sources/Exceptions/Figures/try_except.png b/_sources/Exceptions/Figures/try_except.png new file mode 100644 index 0000000..db8aae5 Binary files /dev/null and b/_sources/Exceptions/Figures/try_except.png differ diff --git a/_sources/Exceptions/intro-exceptions.rst b/_sources/Exceptions/intro-exceptions.rst index 96a8957..940b239 100644 --- a/_sources/Exceptions/intro-exceptions.rst +++ b/_sources/Exceptions/intro-exceptions.rst @@ -17,7 +17,12 @@ Raising and Catching Errors .. index:: try, except, Exception -The try/except control structure provides a way to process a run-time error and continue on with program execution. Until now, any run-time error, such asking for the 8th item in a list with only 3 items, or dividing by 0, has caused the program execution to stop. In the browser ActiveCode windows, you get an error message in a box below. When you are executing python programs from the command-line, you also get an error message saying something about what went wrong and what line it occurred on. After the run-time error is encountered, the python interpreter does not try to execute the rest of the code. You have to make some change in your code and rerun the whole program. +The try/except control structure provides a way to process a run-time error and continue on with program execution. +Until now, any run-time error, such asking for the 8th item in a list with only 3 items, or dividing by 0, has +caused the program execution to stop. In the browser ActiveCode windows, you get an error message in a box below. +When you are executing python programs from the command-line, you also get an error message saying something about +what went wrong and what line it occurred on. After the run-time error is encountered, the python interpreter does +not try to execute the rest of the code. You have to make some change in your code and rerun the whole program. With try/except, you tell the python interpreter: @@ -29,6 +34,9 @@ With try/except, you tell the python interpreter: * execute a block of code in the "except" clause * then carry on with the rest of the program after the try/except statement +.. image:: Figures/try_except.png + :alt: shows the two scenarios, either the try is executed successfully or the except is executed. + .. sourcecode:: python try: @@ -36,7 +44,14 @@ With try/except, you tell the python interpreter: except : -The syntax is fairly straightforward. The only tricky part is that after the word except, there can optionally be a specification of the kinds of errors that will be handled. The catchall is the class Exception. If you write ``except Exception:`` all runtime errors will be handled. If you specify a more restricted class of errors, only those errors will be handled; any other kind of error will still cause the program to stop running and an error message to be printed. +The syntax is fairly straightforward. The only tricky part is that after the word except, there can optionally be a +specification of the kinds of errors that will be handled. The catchall is the class Exception. If you write +``except Exception:`` all runtime errors will be handled. If you specify a more restricted class of errors, only +those errors will be handled; any other kind of error will still cause the program to stop running and an error +message to be printed. + +.. image:: Figures/exception_types.png + :alt: shows three error types, KeyError, FileNotFoundError, and ZeroDivisionError. The code below causes an error of type IndexError, by trying to access the third element of a two-element list. @@ -46,7 +61,6 @@ The code below causes an error of type IndexError, by trying to access the third items = ['a', 'b'] third = items[2] - The code below causes an error of type ZeroDivisionError, or less specifically ArithmeticError. .. activecode:: exceptions_2 @@ -55,7 +69,10 @@ The code below causes an error of type ZeroDivisionError, or less specifically A x = 5 y = x/0 -Let's see what happens if we wrap some of this problematic code in a try/except statement. Note that ``this won't print`` doesn't print: when the error is encountered, the rest of the try block is skipped and the exception block is executed. When the except block is done, it continues on with the nex line of code that's outdented to the same level as the try: ``continuing`` is printed. +Let's see what happens if we wrap some of this problematic code in a try/except statement. Note that ``this won't +print`` doesn't print: when the error is encountered, the rest of the try block is skipped and the exception block +is executed. When the except block is done, it continues on with the nex line of code that's outdented to the same +level as the try: ``continuing`` is printed. .. activecode:: exceptions_3 :nocanvas: @@ -95,7 +112,11 @@ If we catch only IndexEror, and we actually have a divide by zero error, the pro print("continuing again") -There's one other useful feature. The exception code can access a variable that contains information about exactly what the error was. Thus, for example, in the except clause you could print out the information that would normally be printed as an error message but continue on with execution of the rest of the program. To do that, you specify a variable name after the exception class that's being handled. The exception clause code can refer to that variable name. +There's one other useful feature. The exception code can access a variable that contains information about exactly +what the error was. Thus, for example, in the except clause you could print out the information that would normally +be printed as an error message but continue on with execution of the rest of the program. To do that, you specify a +variable name after the exception class that's being handled. The exception clause code can refer to that variable +name. .. activecode:: exceptions_5 :nocanvas: @@ -148,7 +169,6 @@ There's one other useful feature. The exception code can access a variable that After a run-time exception is handled by an except clause, the rest of the code in the try clause will be executed. - .. mchoice:: exceptions_mc4 :practice: T :topics: Exceptions/intro-exceptions @@ -173,5 +193,3 @@ There's one other useful feature. The exception code can access a variable that print(1.0 / (3-i)) except Exception as error_inst: print("Got an error", error_inst) - - diff --git a/_sources/Functions/Figures/.DS_Store b/_sources/Functions/Figures/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/_sources/Functions/Figures/.DS_Store differ diff --git a/_sources/GeneralIntro/ATypicalFirstProgram.rst b/_sources/GeneralIntro/ATypicalFirstProgram.rst index 787889d..8ab583a 100644 --- a/_sources/GeneralIntro/ATypicalFirstProgram.rst +++ b/_sources/GeneralIntro/ATypicalFirstProgram.rst @@ -25,7 +25,7 @@ print anything on paper. It displays a value on the screen. In this case, the re Hello, World! -Here is the example in activecode. Give it a try! +Here is the example in activecode. Activecode windows allow you to execute python code while inside the textbook. When you click **Run** you will execute whatever code has been written in the window. Each time you hit **Run** a new version of the code will be saved in that activecode window's history. If you have already run code in the activecode window before and would like to revert your code to a prior save, click **Load History** and a bar will appear. Your most recent code will be on the right side of the bar, and the first time you clicked **Run** will be on the left side. Regardless of whether you've run the window in the past though, once you start to execute code the **Load History** button will change to the history bar. If you would like to see how python processes your code step-by-step then click on **Show CodeLens**. If you have already opened CodeLens and would like to step through different code then you'll need to refresh the page. Give it a try! .. activecode:: ch01_2 diff --git a/_sources/GeneralIntro/FormalandNaturalLanguages.rst b/_sources/GeneralIntro/FormalandNaturalLanguages.rst index 746c04b..1a50ade 100644 --- a/_sources/GeneralIntro/FormalandNaturalLanguages.rst +++ b/_sources/GeneralIntro/FormalandNaturalLanguages.rst @@ -126,7 +126,7 @@ natural languages, can make a big difference in a formal language. The differences between natural and formal languages include: .. mchoice:: question1_10_2 - :answer_a: True + :answer_a: True :answer_b: False :feedback_a: It usually takes longer to read a program because the structure is as important as the content and must be interpreted in smaller pieces for understanding. :feedback_b: It usually takes longer to read a program because the structure is as important as the content and must be interpreted in smaller pieces for understanding. diff --git a/_sources/GeneralIntro/MoreAboutPrograms.rst b/_sources/GeneralIntro/MoreAboutPrograms.rst index 9001a3d..f00ecac 100644 --- a/_sources/GeneralIntro/MoreAboutPrograms.rst +++ b/_sources/GeneralIntro/MoreAboutPrograms.rst @@ -46,6 +46,49 @@ instructions. .. That may be a little vague, but we will come back to this topic later when we .. talk about **algorithms**. +Preview of Control Structures +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +We won't get too much into python control structures yet, but it is good to mention them early to give you a taste for what you can do with the language! +If these make sense to you now, that's great! +However, we don't expect you to understand these yet - understanding will come later. + +First we have structures that allow us to iterate over something. +We can look at strings character-by-character or lists item-by-item until we've reached the end of them by using something called a ``for`` loop. + +.. activecode:: chap01_program_01 + + for character in "Cool string": + print(character) + +We can also iterate without a definite stopping point with ``while`` loops. +You might use this if you want to receive input from the user of your program but you don't know how long it'll take for them to be done with your code. + +.. activecode:: chap01_program_02 + + grocery_item = "" + while grocery_item != "done": + grocery_item = input("Please write down an item to add to your grocery list. When you are done writing the list then simply type: done") + print(grocery_item) + +Other structures will allow us to only run parts of our programs or only do some task if a certain set of conditions are found. +Conditionals, as they're called, allow us to do that. +Check out how adding conditionals to our code can change what we can write about regarding grocery shopping. + +.. activecode:: chap01_program_03 + + grocery_item = "" + grocery_list = [] + while grocery_item != "done": + grocery_item = input("Please write down an item to add to your grocery list. When you are done writing the list then simply type: done") + if grocery_item == 'done': + continue + else: + print("adding the item to the list") + grocery_list.append(grocery_item) + print("Here is our grocery list:") + print(grocery_list) + **Check your understanding** .. mchoice:: question1_4_1 diff --git a/_sources/GeneralIntro/Syntaxerrors.rst b/_sources/GeneralIntro/Syntaxerrors.rst index 9ae1dcf..8e96558 100644 --- a/_sources/GeneralIntro/Syntaxerrors.rst +++ b/_sources/GeneralIntro/Syntaxerrors.rst @@ -20,10 +20,15 @@ For most readers, a few syntax errors are not a significant problem, which is why we can read the poetry of e. e. cummings without problems. Python is not so forgiving. If there is a single syntax error anywhere in your program, Python will display an error message and quit. You will not be able -to complete the execution your program. During the first few weeks of your programming career, you +to complete the execution of your program. During the first few weeks of your programming career, you will probably spend a lot of time tracking down syntax errors. However, as you gain experience, you will make fewer errors and you will also be able to find your errors faster. +Can you spot the syntax error in the code below? + +.. activecode:: ch_01_syntax_01 + + print("Hello World!" **Check your understanding** diff --git a/_sources/IndefiniteIteration/Figures/.DS_Store b/_sources/IndefiniteIteration/Figures/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/_sources/IndefiniteIteration/Figures/.DS_Store differ diff --git a/_sources/IndefiniteIteration/ThewhileStatement.rst b/_sources/IndefiniteIteration/ThewhileStatement.rst index 4a16a8e..374aee1 100644 --- a/_sources/IndefiniteIteration/ThewhileStatement.rst +++ b/_sources/IndefiniteIteration/ThewhileStatement.rst @@ -17,19 +17,23 @@ The ``while`` Statement http://media.interactivepython.org/thinkcsVideos/whileloop.mov http://media.interactivepython.org/thinkcsVideos/whileloop.webm -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``. +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``. 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. - - +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. @@ -49,11 +53,11 @@ Here is a new version of the summation program that uses a while statement. 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. +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. @@ -72,8 +76,6 @@ The same program in codelens will allow you to observe the flow of execution. print(sumTo(4)) - - .. note:: The names of the variables have been chosen to help readability. More formally, here is the flow of execution for a ``while`` statement: @@ -84,39 +86,38 @@ More formally, here is the flow of execution for a ``while`` 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. +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. +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. -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. +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. -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. +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:: - 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. That also makes a while loop harder to read and understand than the equivalent for loop. So, while you *can* implement definite iteration with a while loop, it's not a good idea to do that. Use a for loop whenever it will be known at the beginning of the iteration process how many times the block of code needs to be executed. - + 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. That +also makes a while loop harder to read and understand than the equivalent for loop. So, while you *can* implement +definite iteration with a while loop, it's not a good idea to do that. Use a for loop whenever it will be known at +the beginning of the iteration process how many times the block of code needs to be executed. **Check your understanding** diff --git a/_sources/Inheritance/.DS_Store b/_sources/Inheritance/.DS_Store new file mode 100644 index 0000000..aa232a8 Binary files /dev/null and b/_sources/Inheritance/.DS_Store differ diff --git a/_sources/Inheritance/Figures/class_inheritance.png b/_sources/Inheritance/Figures/class_inheritance.png new file mode 100644 index 0000000..6f25645 Binary files /dev/null and b/_sources/Inheritance/Figures/class_inheritance.png differ diff --git a/_sources/Inheritance/inheritVarsAndMethods.rst b/_sources/Inheritance/inheritVarsAndMethods.rst index 7924351..d9ed454 100644 --- a/_sources/Inheritance/inheritVarsAndMethods.rst +++ b/_sources/Inheritance/inheritVarsAndMethods.rst @@ -15,13 +15,33 @@ Inheriting Variables and Methods Mechanics of Defining a Subclass -------------------------------- -We said that inheritance provides us a more elegant way of, for example, creating ``Dog`` and ``Cat`` types, rather than making a very complex ``Pet`` class. In the abstract, this is pretty intuitive: all pets have certain things, but dogs are different from cats, which are different from birds. Going a step further, a Collie dog is different from a Labrador dog, for example. Inheritance provides us with an easy and elegant way to represent these differences. - -Basically, it works by defining a new class, and using a special syntax to show what the new sub-class *inherits from* a super-class. So if you wanted to define a ``Dog`` class as a special kind of ``Pet``, you would say that the ``Dog`` type inherits from the ``Pet`` type. In the definition of the inherited class, you only need to specify the methods and instance variables that are different from the parent class (the **parent class**, or the **superclass**, is what we may call the class that is *inherited from*. In the example we're discussing, ``Pet`` would be the superclass of ``Dog`` or ``Cat``). - -Here is an example. Say we want to define a class ``Cat`` that inherits from ``Pet``. Assume we have the ``Pet`` class that we defined earlier. - -We want the ``Cat`` type to be exactly the same as ``Pet``, *except* we want the sound cats to start out knowing "meow" instead of "mrrp", and we want the ``Cat`` class to have its own special method called ``chasing_rats``, which only ``Cat`` s have. +We said that inheritance provides us a more elegant way of, for example, creating ``Dog`` and ``Cat`` types, +rather than making a very complex ``Pet`` class. In the abstract, this is pretty intuitive: all pets have certain +things, but dogs are different from cats, which are different from birds. Going a step further, a Collie dog is +different from a Labrador dog, for example. Inheritance provides us with an easy and elegant way to represent these +differences. + +Basically, it works by defining a new class, and using a special syntax to show what the new sub-class +*inherits from* a super-class. So if you wanted to define a ``Dog`` class as a special kind of ``Pet``, you would +say that the ``Dog`` type inherits from the ``Pet`` type. In the definition of the inherited class, you only need +to specify the methods and instance variables that are different from the parent class (the **parent class**, or +the **superclass**, is what we may call the class that is *inherited from*. In the example we're discussing, +``Pet`` would be the superclass of ``Dog`` or ``Cat``). + +Here is an example. Say we want to define a class ``Cat`` that inherits from ``Pet``. Assume we have the ``Pet`` +class that we defined earlier. + +We want the ``Cat`` type to be exactly the same as ``Pet``, *except* we want the sound cats to start out knowing +"meow" instead of "mrrp", and we want the ``Cat`` class to have its own special method called ``chasing_rats``, +which only ``Cat`` s have. + +To map this example onto the image, below, the smallest, yellow piece is an instance of the method ``Cat``. The +yellow piece can then attach to the slightly larger, blue factory piece which represents the ``Cat`` class. The +blue factory piece then attaches to the largest, red factory piece, which represents the ``Pet`` class. If we +wanted to represent the ``Dog`` class, that might be a green factory, which looks similar to the blue factory +piece, but will not fit the yellow piece since that not an instance of the ``Cat`` class. + +.. image:: Figures/class_inheritance.png For reference, here's the original Tamagotchi code diff --git a/_sources/Inheritance/intro.rst b/_sources/Inheritance/intro.rst index be78ea9..095ba1f 100644 --- a/_sources/Inheritance/intro.rst +++ b/_sources/Inheritance/intro.rst @@ -11,11 +11,19 @@ Introduction: Class Inheritance =============================== -Classes can "inherit" methods and class variables from other classes. We'll see the mechanics of how this works in subsequent sections. First, however, let's motivate why this might be valuable. It turns out that inheritance doesn't let you do anything that you couldn't do without it, but it makes some things a lot more elegant. You will also find it's useful when someone else has defined a class in a module or library, and you just want to override a few things without having to reimplement everything they've done. +Classes can "inherit" methods and class variables from other classes. We'll see the mechanics of how this works in +subsequent sections. First, however, let's motivate why this might be valuable. It turns out that inheritance doesn't +let you do anything that you couldn't do without it, but it makes some things a lot more elegant. You will also find +it's useful when someone else has defined a class in a module or library, and you just want to override a few things +without having to reimplement everything they've done. -Consider our Tamagotchi game. Suppose we wanted to make some different kinds of pets that have the same structure as other pets, but have some different attributes or behave a little differently. For example, suppose that dog pets should show their emotional state a little differently than cats or act differently when they are hungry or when they are asked to fetch something. +Consider our Tamagotchi game. Suppose we wanted to make some different kinds of pets that have the same structure as +other pets, but have some different attributes or behave a little differently. For example, suppose that dog pets +should show their emotional state a little differently than cats or act differently when they are hungry or when they +are asked to fetch something. -You could implement this by making instance variable for the pet type and dispatching on that instance variable in various methods. +You could implement this by making instance variable for the pet type and dispatching on that instance variable in +various methods. .. code:: python @@ -83,6 +91,11 @@ That code is exactly the same as the code defining the ``Pet`` class that you sa * A new input to the constructor -- the ``pet_type`` input parameter, which defaults to ``"dog"``, and the ``self.pet_type`` instance variable. * if..elif..else in the ``self.mood()`` method, such that different types of pets (a dog, a cat, or any other type of animal) express their moods and their hunger in slightly different ways. -But that's not an elegant way to do it. It obscures the parts of being a pet that are common to all pets and it buries the unique stuff about being a dog or a cat in the middle of the mood method. What if you also wanted a dog to reduce boredom at a different rate than a cat, and you wanted a bird pet to be different still? Here, we've only implemented **dogs**, **cats**, and **other** -- but you can imagine the possibilities. +But that's not an elegant way to do it. It obscures the parts of being a pet that are common to all pets and it +buries the unique stuff about being a dog or a cat in the middle of the mood method. What if you also wanted a dog to +reduce boredom at a different rate than a cat, and you wanted a bird pet to be different still? Here, we've only +implemented **dogs**, **cats**, and **other** -- but you can imagine the possibilities. -If there were lots of different types of pets, those methods would start to have long and complex **if..elif..elif** code clauses, which can be confusing. And you'd need that in every method where the behavior was different for different types of pets. Class inheritance will give us a more elegant way to do it. +If there were lots of different types of pets, those methods would start to have long and complex **if..elif..elif** +code clauses, which can be confusing. And you'd need that in every method where the behavior was different for +different types of pets. Class inheritance will give us a more elegant way to do it. diff --git a/_sources/Iteration/.DS_Store b/_sources/Iteration/.DS_Store new file mode 100644 index 0000000..8f0c2d8 Binary files /dev/null and b/_sources/Iteration/.DS_Store differ diff --git a/_sources/Iteration/AccumulatorPatternStrategies.rst b/_sources/Iteration/AccumulatorPatternStrategies.rst new file mode 100644 index 0000000..251ea23 --- /dev/null +++ b/_sources/Iteration/AccumulatorPatternStrategies.rst @@ -0,0 +1,34 @@ +.. Copyright (C) Paul Resnick. 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". + +Accumulator Pattern Strategies +============================== + +When you first start learning accumulation patterns it's sometimes difficult to determine what pattern, if any, is best for the problem you're trying to solve. +Depending on what information you're given and what result you want, using accumulation may or may not be necessary. +If the problem is simple, such as determining how many e's are in a string, then you may be better off using existing methods, such as the ``count`` method. +If it's more complicated, such as counting the number of occurrances of multiple things in a string or list, then accumulation may be appropriate. + +Certain actions are likely to involve accumulation patterns. +This includes counting the frequency of something, determining a total, and creating a string or list from another string or list. +Though this is not a complete list of cases where accumulation may be necessary, keeping this in mind can help when creating solutions to prompts and problems. + +One aspect of writing an accumulation pattern is determining the type of the accumulator variable. +In this textbook a prompt will specify what the returned value should be (like asking for the 'biggest number' or 'a list of first words in sentences'). +However, not every problem will be clearly defined. +Regardless, as a programmer you're tasked with coming up with a solution. +When it comes to deciding the type the accumulator variable should be, this may be dictated by the problem you're solving but it can also depend on how *you* want to solve something. + +For example, say you want to extract different parts of a string and then recombine those parts into a new string. +Think about what type your accumulator variable could be. So far you know of two options that might make sense. +A string is the most obvious choice as that's what you want the end result to be. However, this task could also be accomplished with an accumulator variable that is a list. +The solution could then use the ``join`` method or even another accumulation pattern to get the desired final outcome. +Using either the string or the list is fine, but one of them might make your job easier so it's important to think about how the type would affect your actions. + + + diff --git a/_sources/Iteration/Figures/.DS_Store b/_sources/Iteration/Figures/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/_sources/Iteration/Figures/.DS_Store differ diff --git a/_sources/Iteration/Figures/accum_o.gif b/_sources/Iteration/Figures/accum_o.gif new file mode 100644 index 0000000..5f1d450 Binary files /dev/null and b/_sources/Iteration/Figures/accum_o.gif differ diff --git a/_sources/Iteration/Figures/iteration_vs_hardcoding.png b/_sources/Iteration/Figures/iteration_vs_hardcoding.png new file mode 100644 index 0000000..773855f Binary files /dev/null and b/_sources/Iteration/Figures/iteration_vs_hardcoding.png differ diff --git a/_sources/Iteration/FlowofExecutionoftheforLoop.rst b/_sources/Iteration/FlowofExecutionoftheforLoop.rst index 5bd4dc4..63c94e2 100644 --- a/_sources/Iteration/FlowofExecutionoftheforLoop.rst +++ b/_sources/Iteration/FlowofExecutionoftheforLoop.rst @@ -10,21 +10,17 @@ Flow of Execution of the for 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**. -Sequential flow of control is always assumed to be the default behavior for a computer program. +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**. Sequential flow of control is always assumed to be the default behavior for a computer program. The ``for`` statement changes this. 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 ``for`` statement executes. - .. image:: Figures/new_flowchart_for.png :width: 300px @@ -43,5 +39,9 @@ the buttons. You can see the value of ``name`` change as the loop iterates thru for name in ["Joe", "Amy", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]: print("Hi ", name, " Please come to my party on Saturday!") +While this may not seem to be necessary when you're iterating over a few items, it is extremely helpful when +iterating over lots of items. Imagine if you needed to change what happened in the code block. On the left, when you use iteration, this is easy. On the right, when you have hard coded the process, this is more difficult. +.. image:: Figures/iteration_vs_hardcoding.png + :alt: Demonstration of using iteration over hard coding the iteration. diff --git a/_sources/Iteration/Stringsandforloops.rst b/_sources/Iteration/Stringsandforloops.rst index e2e39b0..db1f3fd 100644 --- a/_sources/Iteration/Stringsandforloops.rst +++ b/_sources/Iteration/Stringsandforloops.rst @@ -12,7 +12,7 @@ Strings and ``for`` loops Since a string is simply a sequence of characters, the ``for`` loop iterates over each character automatically. (As always, try -to predict what the output will be from this code before your run it. +to predict what the output will be from this code before your run it.) .. activecode:: ch08_6 :nocanvas: diff --git a/_sources/Iteration/TheAccumulatorPattern.rst b/_sources/Iteration/TheAccumulatorPattern.rst index 5d62b45..3f05db3 100644 --- a/_sources/Iteration/TheAccumulatorPattern.rst +++ b/_sources/Iteration/TheAccumulatorPattern.rst @@ -27,11 +27,10 @@ Next, the iteration is performed 10 times. Inside the for loop, the update occu ``w`` has the value of current item (1 the first time, then 2, then 3, etc.). ``accum`` is reassigned a new value which is the old value plus the current value of ``w``. -This pattern of iterating the updating of a variable is commonly -referred to as the **accumulator pattern**. We refer to the variable as the **accumulator**. This pattern will come up over and over again. Remember that the key -to making it work successfully is to be sure to initialize the variable before you start the iteration. -Once inside the iteration, it is required that you update the accumulator. - +This pattern of iterating the updating of a variable is commonly referred to as the **accumulator pattern**. +We refer to the variable as the **accumulator**. This pattern will come up over and over again. Remember that the key +to making it work successfully is to be sure to initialize the variable before you start the iteration. Once inside +the iteration, it is required that you update the accumulator. Here is the same program in codelens. Step thru the function and watch the "running total" accumulate the result. @@ -49,6 +48,21 @@ Here is the same program in codelens. Step thru the function and watch the "run What would happen if we indented the print accum statement? Not sure? Make a prediction, then try it and find out. +We can use the accumulation pattern is count the number of something or to sum up a total. The above examples only +covered how to get the sum for a list, but we can also count how many items are in it if we wanted to. + +.. activecode:: iter_accum3 + + nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + count = 0 + for w in nums: + count = count + 1 + print(count) + +In this example we don't make use of ``w`` even though the iterator variable is a necessary part of constructing a for +loop. Instead of adding the value of ``w`` to ``count`` we add a 1 to it, because we're incrementing the value of +count when we iterate each time through the loop. Though in this scenario we could have used the ``len`` function, +there are other cases later on where len won't be useful but we still need to count. **Check your understanding** diff --git a/_sources/Iteration/TheAccumulatorPatternwithConditionals.rst b/_sources/Iteration/TheAccumulatorPatternwithConditionals.rst new file mode 100644 index 0000000..c554a63 --- /dev/null +++ b/_sources/Iteration/TheAccumulatorPatternwithConditionals.rst @@ -0,0 +1,119 @@ +.. Copyright (C) Paul Resnick. 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". + +The Accumulator Pattern with Conditionals +----------------------------------------- + +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 letters in a phrase. + +.. activecode:: iter_accumcondition1 + + phrase = "What a wonderful day to program" + tot = 0 + for char in phrase: + if char != " ": + tot = tot + 1 + print(tot) + +Here, we **initialize** the accumulator variable to be zero on line two. + +We **iterate** through the sequence (line 3). + +The **update** step happens in two parts. First, we check to see if the value of ``char`` is not a space. If it is not a space, then we update the value of our accumulator variable ``tot`` (on line 6) by adding one to it. If that conditional proves to be False, which means that char *is* a space, then we don't update tot and continue the for loop. We could have written tot = tot + 1 or tot += 1, either is fine. + +At the end, we have accumulated a the total number of letters in the phrase. Without using the conditional, we would have only been able to count how many characters there are in the string and not been able to differentiate between spaces and non-spaces. + +We can also use ``==`` to execute a similar operation. Here, we'll check to see if the character we are iterating over is an "o". If it is an "o" then we will update our counter. + +.. image:: Figures/accum_o.gif + :alt: a gif that shows code to check that "o" is in the phrase "onomatopoeia". + +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. + +.. activecode:: iter_accumcondition2 + + nums = [9, 3, 8, 11, 5, 29, 2] + best_num = 0 + for n in nums: + if n > best_num: + best_num = n + print(best_num) + +Here, we initalize best_num to zero, assuming that there are no negative numbers in the list. + +In the for loop, we check to see if the current value of n is greater than the current value of ``best_num``. If it is, then we want to **update** ``best_num`` so that it now is assigned the higher number. Otherwise, we do nothing and continue the for loop. + +You may notice that the current structure could be a problem. If the numbers were all negative what would 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. + +.. activecode:: iter_accumcondition3 + + nums = [9, 3, 8, 11, 5, 29, 2] + best_num = nums[0] + for n in nums: + if n > best_num: + best_num = n + 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! + +**Check your understanding** + +.. mchoice:: test_question_iter_condition_1 + :answer_a: 2 + :answer_b: 5 + :answer_c: 0 + :answer_d: There is an error in the code so it cannot run. + :feedback_a: Though only two of the letters in the list are found, we count them each time they appear. + :feedback_b: Yes, we add to x each time we come across a letter in the list. + :feedback_c: Check again what the conditional is evaluating. The value of i will be a character in the string s, so what will happen in the if statement? + :feedback_d: There are no errors in this code. + :correct: b + :practice: T + :topics: Iteration/TheAccumulatorPatternwithConditionals + + What is printed by the following statements? + + .. code-block:: python + + s = "we are learning!" + x = 0 + for i in s: + if i in ['a', 'b', 'c', 'd', 'e']: + x += 1 + print(x) + + +.. mchoice:: test_question_iter_condition_2 + :answer_a: 10 + :answer_b: 1 + :answer_c: 0 + :answer_d: There is an error in the code so it cannot run. + :feedback_a: Not quite. What is the conditional checking? + :feedback_b: min_value was set to a number that was smaller than any of the numbers in the list, so it was never updated in the for loop. + :feedback_c: Yes, min_value was set to a number that was smaller than any of the numbers in the list, so it was never updated in the for loop. + :feedback_d: The code does not have an error that would prevent it from running. + :correct: c + :practice: T + :topics: Iteration/TheAccumulatorPatternwithLists + + What is printed by the following statements? + + .. code-block:: python + + list= [5, 2, 1, 4, 9, 10] + min_value = 0 + for item in list: + if item < min_value: + min_value = item + print(min_value) diff --git a/_sources/Iteration/TheRangeFunction.rst b/_sources/Iteration/TheRangeFunction.rst new file mode 100644 index 0000000..5b5c891 --- /dev/null +++ b/_sources/Iteration/TheRangeFunction.rst @@ -0,0 +1,54 @@ +.. 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". + +The Range Function +================== + +Sometimes we want to iterate for a certain number of times, not just to iterate through a string. +For example, say that you want to print out "Hello, friend!" eight different times. +Sure, you can write ``print("Hello, friend!")`` on eight different lines, but that's tedious. +Imagine you had to do that for each of your friends. +Maybe you don't find it a bother because it's for your friends, but that might end up being a lot of work. +Thankfully, there's a handy function in python to solve this kind of problem. + +The ``range`` function is a built-in python function, much like ``print``. The ``range`` function takes at least one input - which should be an integer - and returns a list as long as your input. +While you can provide two inputs, we will focus on using range with just one input. With one input, range will start at zero and go up to - but not include - the input. + +One important thing to know about the range function in python3 is that if we want to use it outside of iteration, we have to cast it as a list using ``list()``. Inside the textbook you'll notice that ``range`` works with or without casting it as a list but it is best for you to try and get into the habit of casting it as a list. + +Below we can see how ``range`` is used in different circumstances. +The safest way to use the range function is to always cast it as a list, though it is not necessary in every case. +Try changing the code to see what it's like to use range! + + +.. activecode:: chap_09_range_01 + + z = range(3) + print(list(z)) + + for n in z: + print(n) + # this is what happens when we don't cast the range function as a list. + print(z) + + +Now with the range function we can greet our eight friends! + +.. activecode:: chap_09_range_02 + + for _ in range(8): + print("Hello, friend!") + + + + + + + + diff --git a/_sources/PythonTurtle/SummaryOfTurtleMethods.rst b/_sources/PythonTurtle/SummaryOfTurtleMethods.rst index 4e7c3d8..cd4602c 100644 --- a/_sources/PythonTurtle/SummaryOfTurtleMethods.rst +++ b/_sources/PythonTurtle/SummaryOfTurtleMethods.rst @@ -7,8 +7,6 @@ the license is included in the section entitled "GNU Free Documentation License". -.. _turtle_methods: - Summary of Turtle Methods ------------------------- diff --git a/_sources/RESTAPIs/.DS_Store b/_sources/RESTAPIs/.DS_Store new file mode 100644 index 0000000..b939bc9 Binary files /dev/null and b/_sources/RESTAPIs/.DS_Store differ diff --git a/_sources/RESTAPIs/Figures/parameterformat.png b/_sources/RESTAPIs/Figures/parameterformat.png new file mode 100644 index 0000000..d5de995 Binary files /dev/null and b/_sources/RESTAPIs/Figures/parameterformat.png differ diff --git a/_sources/RESTAPIs/Figures/urlexamples.png b/_sources/RESTAPIs/Figures/urlexamples.png new file mode 100644 index 0000000..1e38baf Binary files /dev/null and b/_sources/RESTAPIs/Figures/urlexamples.png differ diff --git a/_sources/RESTAPIs/Figures/urlstructure.png b/_sources/RESTAPIs/Figures/urlstructure.png new file mode 100644 index 0000000..7310868 Binary files /dev/null and b/_sources/RESTAPIs/Figures/urlstructure.png differ diff --git a/_sources/RESTAPIs/RequestURLs.rst b/_sources/RESTAPIs/RequestURLs.rst index 4b27df3..c472f18 100644 --- a/_sources/RESTAPIs/RequestURLs.rst +++ b/_sources/RESTAPIs/RequestURLs.rst @@ -6,11 +6,14 @@ the license is included in the section entitled "GNU Free Documentation License". - Generating Request URLs ======================= -In a REST API, the client or application program-- the kind of program you will be writing-- makes an HTTP request that includes information about what kind of request it is making. Web sites are free to define whatever format they want for how the request should be formatted. This chapter covers a particularly common and particularly simple format, where the request information is encoded right in the URL. This is convenient, because if something goes wrong, we can debug by copying the URL into a browser and see what happens when it tries to visit that URL. +In a REST API, the client or application program-- the kind of program you will be writing-- makes an HTTP request +that includes information about what kind of request it is making. Web sites are free to define whatever format +they want for how the request should be formatted. This chapter covers a particularly common and particularly +simple format, where the request information is encoded right in the URL. This is convenient, because if something +goes wrong, we can debug by copying the URL into a browser and see what happens when it tries to visit that URL. In this format, the URL has a standard structure: @@ -18,7 +21,9 @@ In this format, the URL has a standard structure: * a ``?`` character * one or more key-value pairs, formatted as ``key=value`` pairs and separated by the ``&`` character. -For example, consider the URL ``https://itunes.apple.com/search?term=Ann+Arbor&entity=podcast``. Try copying that URL into a browser. It data about podcasts posted from Ann Arbor, MI. Depending on your browser, it may put the contents into a file attachment that you have to open up to see the contents. +For example, consider the URL ``https://itunes.apple.com/search?term=Ann+Arbor&entity=podcast``. +Try copying that URL into a browser. It data about podcasts posted from Ann Arbor, MI. Depending on your browser, +it may put the contents into a file attachment that you have to open up to see the contents. Let's pull apart that URL. In this case, the FAA uses a slight variation on the basic structure described above. @@ -26,14 +31,20 @@ Let's pull apart that URL. In this case, the FAA uses a slight variation on the * a ``?`` character * key=value pairs. In this case, there are two pairs. The keys are ``term`` and ``entity``. +.. image:: Figures/parameterformat.png + All those parts are concatenated together to form the full URL. +.. image:: Figures/urlstructure.png + Note that in the search term Ann Arbor, the space had to be "encoded" as ``+``. More on that below. Encoding URL Parameters ----------------------- -Here's another URL that has a similar format. ``https://www.google.com/search?q=%22violins+and+guitars%22&tbm=isch``. It's a search on Google for images that match the string "violins and guitars". It's not actually based on a REST API, because the contents that come back are meant to be displayed in a browser. But the URL has the same structure we have been exploring above and introduces the idea of "encoding" URL parameters. +Here's another URL that has a similar format. ``https://www.google.com/search?q=%22violins+and+guitars%22&tbm=isch``. It's a search on Google for images that match the string "violins and guitars". It's not actually based on a REST +API, because the contents that come back are meant to be displayed in a browser. But the URL has the same structure +we have been exploring above and introduces the idea of "encoding" URL parameters. * The base URL is ``https://www.google.com/search`` * ``?`` @@ -41,16 +52,28 @@ Here's another URL that has a similar format. ``https://www.google.com/search?q= * ``q=%22violins+and+guitars%22`` says that the query to search for is "violins and guitars". * ``tbm=isch`` says to go to the tab for image search -Now why is ``"violins and guitars"`` represented in the URL as ``%22violins+and+guitars%22``? The answer is that some characters are not safe to include, as is, in URLs. For example, a URL path is not allowed to include the double-quote character. It also can't include a : or / or a space. Whenever we want to include one of those characters in a URL, we have to *encode* them with other characters. A space is encoded as ``+``. ``"`` is encoded as ``%22``. ``:`` would be encoded as ``%3A``. And so on. +Now why is ``"violins and guitars"`` represented in the URL as ``%22violins+and+guitars%22``? The answer is that +some characters are not safe to include, as is, in URLs. For example, a URL path is not allowed to include the double +-quote character. It also can't include a : or / or a space. Whenever we want to include one of those characters in +a URL, we have to *encode* them with other characters. A space is encoded as ``+``. ``"`` is encoded as ``%22``. +``:`` would be encoded as ``%3A``. And so on. Using requests.get to encode URL parameters ------------------------------------------- -Fortunately, when you want to pass information as a URL parameter value, you don't have to remember all the substitutions that are required to encode special characters. Instead, that capability is built into the requests module. +Fortunately, when you want to pass information as a URL parameter value, you don't have to remember all the +substitutions that are required to encode special characters. Instead, that capability is built into the requests +module. -The get function in the requests module takes an optional parameter called ``params``. If a value is specified for that parameter, it should be a dictionary. The keys and values in that dictionary are used to append something to the URL that is requested from the remote site. +The get function in the requests module takes an optional parameter called ``params``. If a value is specified for +that parameter, it should be a dictionary. The keys and values in that dictionary are used to append something to +the URL that is requested from the remote site. -For example, in the following, the base url is https://google.com/search. A dictionary with two parameters is passed. Thus, the whole url is that base url, plus a question mark, "?", plus a "q=..." and a "tbm=..." separated by an "&". In other words, the final url that is visited is ``https://www.google.com/search?q=%22violins+and+guitars%22&tbm=isch``. Actually, because dictionary keys are unordered in python, the final url might sometimes have the encoded key-value pairs in the other order: ``https://www.google.com/search?tbm=isch&q=%22violins+and+guitars%22``. Fortunately, most websites that accept URL parameters in this form will accept the key-value pairs in any order. +For example, in the following, the base url is https://google.com/search. A dictionary with two parameters is +passed. Thus, the whole url is that base url, plus a question mark, "?", plus a "q=..." and a "tbm=..." separated +by an "&". In other words, the final url that is visited is ``https://www.google.com/search?q=%22violins+and+guitars%22&tbm=isch``. Actually, because dictionary keys are unordered in python, the +final url might sometimes have the encoded key-value pairs in the other order: ``https://www.google.com/search?tbm=isch&q=%22violins+and+guitars%22``. Fortunately, most websites that accept URL parameters in this +form will accept the key-value pairs in any order. .. sourcecode:: python @@ -58,7 +81,13 @@ For example, in the following, the base url is https://google.com/search. A dict results = requests.get("https://google.com/search", params=d) print(results.url) -.. note: +Below are more examples of urls, outlining the base part of the url - which would be the first argument when +calling ``request.get()`` - and the parameters - which would be written as a dictionary and passed into the params +argument when calling ``request.get()``. + +.. image:: Figures/urlexamples.png + +.. note:: If you're ever unsure exactly what url has been produced when calling requests.get and passing a value for params, you can access the .url attribute of the object that is returned. This will be a helpful debugging strategy. You can take that url and plug it into a browser and see what results come back! We will talk about this more in the next section, on debugging calls to ``requests.get()`` when they don't do exactly what you expect. @@ -78,7 +107,3 @@ For example, in the following, the base url is https://google.com/search. A dict :correct: d How would you request the URL ``http://bar.com/goodstuff?greet=hi+there&frosted=no`` using the requests module? - - - - diff --git a/_sources/Requests/.DS_Store b/_sources/Requests/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/_sources/Requests/.DS_Store differ diff --git a/_sources/Requests/Figures/.DS_Store b/_sources/Requests/Figures/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/_sources/Requests/Figures/.DS_Store differ diff --git a/_sources/Requests/Figures/Internet.png b/_sources/Requests/Figures/Internet.png deleted file mode 100755 index 360bd3e..0000000 Binary files a/_sources/Requests/Figures/Internet.png and /dev/null differ diff --git a/_sources/Requests/Figures/argumentstoserver.png b/_sources/Requests/Figures/argumentstoserver.png new file mode 100644 index 0000000..3de5c65 Binary files /dev/null and b/_sources/Requests/Figures/argumentstoserver.png differ diff --git a/_sources/Requests/Figures/internet_requests.png b/_sources/Requests/Figures/internet_requests.png new file mode 100644 index 0000000..1099de3 Binary files /dev/null and b/_sources/Requests/Figures/internet_requests.png differ diff --git a/_sources/Requests/Figures/routers.png b/_sources/Requests/Figures/routers.png new file mode 100644 index 0000000..aad361d Binary files /dev/null and b/_sources/Requests/Figures/routers.png differ diff --git a/_sources/Requests/Figures/serverresponse.png b/_sources/Requests/Figures/serverresponse.png new file mode 100644 index 0000000..d21982b Binary files /dev/null and b/_sources/Requests/Figures/serverresponse.png differ diff --git a/_sources/Requests/how_the_Internet_works.rst b/_sources/Requests/how_the_Internet_works.rst index da194fd..1eb6ee1 100644 --- a/_sources/Requests/how_the_Internet_works.rst +++ b/_sources/Requests/how_the_Internet_works.rst @@ -6,8 +6,6 @@ the license is included in the section entitled "GNU Free Documentation License". - - The Internet: Behind the Scenes =============================== @@ -25,8 +23,4 @@ The Internet is a transport mechanism that lets any connected device communicate * At the destination, the packets are reassembled into the original data message. -.. Figure:: Figures/Internet.png - - The interconnected devices in the middle are the routers. - - +.. Figure:: Figures/routers.png diff --git a/_sources/Requests/http.rst b/_sources/Requests/http.rst index e7e0fb7..55e3756 100644 --- a/_sources/Requests/http.rst +++ b/_sources/Requests/http.rst @@ -6,14 +6,14 @@ the license is included in the section entitled "GNU Free Documentation License". - - The HTTP protocol ================= -A protocol specifies the order in which parties will speak and the format of what they say and the content of appropriate responses. +A protocol specifies the order in which parties will speak and the format of what they say and the content of +appropriate responses. -HTTP is the protocol that specifies how web browsers or other programs communicate with web servers. One version of the formal specific, before it was later split into multiple documents, was IETF `RFC 2616 `_. It is 176 pages long! Fortunately, the basics are pretty easy to understand. +HTTP is the protocol that specifies how web browsers or other programs communicate with web servers. One version of +the formal specific, before it was later split into multiple documents, was IETF `RFC 2616 `_. It is 176 pages long! Fortunately, the basics are pretty easy to understand. * Step 1: the client makes a request to the server. * If the request only involves fetching data, the client sends a message of the form ``GET ``, where is the path part of the URL @@ -23,9 +23,13 @@ HTTP is the protocol that specifies how web browsers or other programs communica * Any cookies that the server previously asked the client to hold onto. This allows the server to continue previous interactions, rather than treating every request as stand-alone. It also allows ad networks to place personalized ads. * After the HTTP headers, for a POST type communication, there is some data (the body of the request). +.. image:: Figures/argumentstoserver.png + * Step 2: the server responds to the client. * The server first sends back some HTTP headers. These include: * a response code indicating whether the server thinks it has fulfilled the request or not. * a description of the type of content it is sending back (e.g., text/html when it is sending html-formatted text). * any cookies it would like the client to hold onto and send back the next time it communicates with the server. - * After the headers come the contents. This is the stuff that you would see if you ask to "View Source" in a browser. \ No newline at end of file + * After the headers come the contents. This is the stuff that you would see if you ask to "View Source" in a browser. + +.. image:: Figures/serverresponse.png diff --git a/_sources/Requests/urls.rst b/_sources/Requests/urls.rst index e83fea4..d87ae8f 100644 --- a/_sources/Requests/urls.rst +++ b/_sources/Requests/urls.rst @@ -6,8 +6,6 @@ the license is included in the section entitled "GNU Free Documentation License". - - Anatomy of URLs =============== @@ -37,3 +35,9 @@ For example, consider the url https://github.com/presnick/runestone: * /presnick/runestone says to ask the remote server for the page presnick/runestone. It is up to the remote server to decide how to map that to the contents of a file it has access to, or to some content that it generates on the fly. +The url http: //blueserver.com/path?k=val is another example that we can consider. The path here a bit different +from https://github.com/presnick/runestone because of how we ask for a specific page. Here the path is structured +similar to how we assign values of variables. + +.. image:: Figures/internet_requests.png + diff --git a/_sources/Selection/.DS_Store b/_sources/Selection/.DS_Store new file mode 100644 index 0000000..9febb45 Binary files /dev/null and b/_sources/Selection/.DS_Store differ diff --git a/_sources/Selection/Chainedconditionals.rst b/_sources/Selection/Chainedconditionals.rst index a8ee89c..6d7d3e2 100644 --- a/_sources/Selection/Chainedconditionals.rst +++ b/_sources/Selection/Chainedconditionals.rst @@ -11,8 +11,7 @@ Chained conditionals -------------------- Python provides an alternative way to write nested selection such as the one shown in the previous section. -This is sometimes referred to as a **chained -conditional** +This is sometimes referred to as a **chained conditional** .. sourcecode:: python @@ -32,6 +31,8 @@ executed. There is no limit of the number of ``elif`` statements but only a single (and optional) final ``else`` statement is allowed and it must be the last branch in the statement. +.. image:: Figures/conditionals_overview.png + Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true @@ -51,6 +52,12 @@ Here is the same program using ``elif``. else: print("x and y must be equal") +The following image highlights different kinds of valid conditionals that can be used. Though there are other +versions of conditionals that Python can understand (imagine an if statement with twenty elif statements), those +other versions must follow the same order as seen below. + +.. image:: Figures/valid_conditionals.png + :alt: shows a unary conditiona, a binary conditional, a conditional with if, elif, else, and a conditional with if, elif, and elif. .. note:: @@ -58,7 +65,6 @@ Here is the same program using ``elif``. .. activecode:: scratch_06_02 - **Check your understanding** .. mchoice:: test_question6_7_1 diff --git a/_sources/Selection/Figures/conditionals_overview.png b/_sources/Selection/Figures/conditionals_overview.png new file mode 100644 index 0000000..3e0aa2e Binary files /dev/null and b/_sources/Selection/Figures/conditionals_overview.png differ diff --git a/_sources/Selection/Figures/valid_conditionals.png b/_sources/Selection/Figures/valid_conditionals.png new file mode 100644 index 0000000..fb8ed25 Binary files /dev/null and b/_sources/Selection/Figures/valid_conditionals.png differ diff --git a/_sources/Sequences/.DS_Store b/_sources/Sequences/.DS_Store new file mode 100644 index 0000000..ff0f14e Binary files /dev/null and b/_sources/Sequences/.DS_Store differ diff --git a/_sources/Sequences/DisabmiguatingSquareBrackets.rst b/_sources/Sequences/DisabmiguatingSquareBrackets.rst new file mode 100644 index 0000000..1bd6d49 --- /dev/null +++ b/_sources/Sequences/DisabmiguatingSquareBrackets.rst @@ -0,0 +1,71 @@ +.. 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". + +Disabmiguating []: creation vs indexing +======================================= + +Square brackets ``[]`` are used in quite a few ways in python. +When you're first learning how to use them it may be confusing, but with practice and repetition they'll be easy to incorporate! + +There are currently three instances where we use square brakets. +First, when we are creating lists, second when we are indexing, and third when we are slicing. + +Slicing is the most distinct as it requires using a colon inside the brackets. +At first glance though, creating and indexing are harder to distinguish. +However, indexing requires referencing an already created list while simply creating a list does not. + +.. activecode:: chap09_disambig_01 + + new_lst = [] + +In the code above, a new list is created using the empty brackets. Since there's nothing in it though, we can't index into it. + +.. activecode:: chap09_disambig_02 + + new_lst = ["NFLX", "AMZN", "GOOGL", "DIS", "XOM"] + part_of_new_lst = new_lst[0] + +In the code above, you'll see how, now that we have elements inside of ``new_lst``, we can index into it. +In order to extract an element of the list, we do use ``[]``, but we first have to specify which list we are indexing. +Imagine if there was another list in the activecode. +How would python know which list we want to index into if we don't tell it? +Additionally, we have to specify what element we want to extract. This belongs inside of the brakets. + +Though it may be easier to distinguish in this above activecode, below may be a bit more difficult. + +.. activecode:: chap09_disambig_03 + + lst = [0] + n_lst = lst[0] + + print(lst) + print(n_lst) + +Here, we see a list called ``lst`` being assigned to a list with one element, zero. +Then, we see how ``n_lst`` is assigned the value associated with the first element of lst. +Dispite the variable names, only one of the above variables is assigned to a list. +Note that in this example, what sets creating appart from indexing is the reference to the list to let python know that you are extracting an element from another list. + +.. mchoice:: testquestion_chap09_disambig_01 + :multiple_answers: + :answer_a: w = [a] + :answer_b: y = a[] + :answer_c: x = [8] + :answer_d: t = a[0] + :feedback_a: No, due to the way the code was written it creates a list. This list would have one element which is the value assigned to the variable a. + :feedback_b: Though this tries to use indexing, it does not specify what element should be taken from a. + :feedback_c: No, this is an example of creating a list. + :feedback_d: Yes, this will using indexing to get the value of the first element of a. + :correct: d + :practice: T + :topics: + + Which of the following correctly uses indexing? Assume that ``a`` is a list or string. Select as many as apply. + + diff --git a/_sources/Sequences/Figures/.DS_Store b/_sources/Sequences/Figures/.DS_Store new file mode 100644 index 0000000..7d0c348 Binary files /dev/null and b/_sources/Sequences/Figures/.DS_Store differ diff --git a/_sources/Sequences/Figures/join.gif b/_sources/Sequences/Figures/join.gif new file mode 100644 index 0000000..54e889c Binary files /dev/null and b/_sources/Sequences/Figures/join.gif differ diff --git a/_sources/Sequences/Figures/refdiag1.png b/_sources/Sequences/Figures/refdiag1.png index 08a9041..42c80ac 100644 Binary files a/_sources/Sequences/Figures/refdiag1.png and b/_sources/Sequences/Figures/refdiag1.png differ diff --git a/_sources/Sequences/Figures/refdiag2.png b/_sources/Sequences/Figures/refdiag2.png index 434584b..3d9e55f 100644 Binary files a/_sources/Sequences/Figures/refdiag2.png and b/_sources/Sequences/Figures/refdiag2.png differ diff --git a/_sources/Sequences/Figures/refdiag3.png b/_sources/Sequences/Figures/refdiag3.png index 9a03c12..13a548b 100644 Binary files a/_sources/Sequences/Figures/refdiag3.png and b/_sources/Sequences/Figures/refdiag3.png differ diff --git a/_sources/Sequences/Figures/refdiag4.png b/_sources/Sequences/Figures/refdiag4.png index 66cc194..c061f43 100644 Binary files a/_sources/Sequences/Figures/refdiag4.png and b/_sources/Sequences/Figures/refdiag4.png differ diff --git a/_sources/Sequences/Figures/slicing.png b/_sources/Sequences/Figures/slicing.png new file mode 100644 index 0000000..85fffa8 Binary files /dev/null and b/_sources/Sequences/Figures/slicing.png differ diff --git a/_sources/Sequences/Figures/split_default.gif b/_sources/Sequences/Figures/split_default.gif new file mode 100644 index 0000000..7d71a20 Binary files /dev/null and b/_sources/Sequences/Figures/split_default.gif differ diff --git a/_sources/Sequences/Figures/split_on_e.jpeg b/_sources/Sequences/Figures/split_on_e.jpeg new file mode 100644 index 0000000..5331b19 Binary files /dev/null and b/_sources/Sequences/Figures/split_on_e.jpeg differ diff --git a/_sources/Sequences/SplitandJoin.rst b/_sources/Sequences/SplitandJoin.rst index 4b69949..c7d7da1 100644 --- a/_sources/Sequences/SplitandJoin.rst +++ b/_sources/Sequences/SplitandJoin.rst @@ -1,10 +1,11 @@ Splitting and Joining Strings ============================= -Two of the most useful methods on strings involve lists of -strings. The ``split`` method -breaks a string into a list of words. By -default, any number of whitespace characters is considered a word boundary. +Two of the most useful methods on strings involve lists of strings. The ``split`` method breaks a string into a list +of words. By default, any number of whitespace characters is considered a word boundary. + +.. image:: Figures/split_default.gif + :alt: shows the phrase "leaders and best" being split on spaces .. activecode:: ch09_split1 @@ -12,9 +13,12 @@ default, any number of whitespace characters is considered a word boundary. wds = song.split() print(wds) -An optional argument called a **delimiter** can be used to specify which -characters to use as word boundaries. The following example uses the string -``ai`` as the delimiter: +An optional argument called a **delimiter** can be used to specify which characters to use as word boundaries. + +.. image:: Figures/split_on_e.jpeg + :alt: shows example of splitting "leaders and best" on "e" + +The following example uses the string ``ai`` as the delimiter: .. activecode:: ch09_split2 @@ -28,6 +32,9 @@ The inverse of the ``split`` method is ``join``. You choose a desired **separator** string, (often called the *glue*) and join the list with the glue between each of the elements. +.. image:: Figures/join.gif + :alt: shows process of a "/" separating the words "leaders", "and", "best" + .. activecode:: ch09_join wds = ["red", "blue", "green"] diff --git a/_sources/Sequences/TheSliceOperator.rst b/_sources/Sequences/TheSliceOperator.rst index 33cb1a5..31c4a1c 100644 --- a/_sources/Sequences/TheSliceOperator.rst +++ b/_sources/Sequences/TheSliceOperator.rst @@ -20,6 +20,8 @@ selecting a character: print(singers[7:11]) print(singers[17:21]) +.. image:: Figures/slicing.png + :alt: visual of variable [first point : last point] 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*. diff --git a/_sources/SimplePythonData/.DS_Store b/_sources/SimplePythonData/.DS_Store new file mode 100644 index 0000000..f5a6133 Binary files /dev/null and b/_sources/SimplePythonData/.DS_Store differ diff --git a/_sources/SimplePythonData/Figures/.DS_Store b/_sources/SimplePythonData/Figures/.DS_Store new file mode 100644 index 0000000..62d7cb5 Binary files /dev/null and b/_sources/SimplePythonData/Figures/.DS_Store differ diff --git a/_sources/SimplePythonData/Figures/expression_value_type.png b/_sources/SimplePythonData/Figures/expression_value_type.png new file mode 100644 index 0000000..543d8a0 Binary files /dev/null and b/_sources/SimplePythonData/Figures/expression_value_type.png differ diff --git a/_sources/SimplePythonData/Figures/function_calls.gif b/_sources/SimplePythonData/Figures/function_calls.gif new file mode 100644 index 0000000..2d0bcb2 Binary files /dev/null and b/_sources/SimplePythonData/Figures/function_calls.gif differ diff --git a/_sources/SimplePythonData/Figures/function_object.png b/_sources/SimplePythonData/Figures/function_object.png new file mode 100644 index 0000000..5267e78 Binary files /dev/null and b/_sources/SimplePythonData/Figures/function_object.png differ diff --git a/_sources/SimplePythonData/Figures/square_function.gif b/_sources/SimplePythonData/Figures/square_function.gif new file mode 100644 index 0000000..e4261ab Binary files /dev/null and b/_sources/SimplePythonData/Figures/square_function.gif differ diff --git a/_sources/SimplePythonData/Figures/type_cast.gif b/_sources/SimplePythonData/Figures/type_cast.gif new file mode 100644 index 0000000..eee95ba Binary files /dev/null and b/_sources/SimplePythonData/Figures/type_cast.gif differ diff --git a/_sources/SimplePythonData/FunctionCalls.rst b/_sources/SimplePythonData/FunctionCalls.rst index 9931d93..f76d98e 100644 --- a/_sources/SimplePythonData/FunctionCalls.rst +++ b/_sources/SimplePythonData/FunctionCalls.rst @@ -16,6 +16,16 @@ Python adopts a similar syntax for invoking functions. If there is a named funct There are many built-in functions available in python. You'll be seeing some in this chapter and the next couple of chapters. +Functions are like factories that take in some material, do some operation, and then send out the resulting object. + +.. image:: Figures/function_object.png + :alt: Represenation of a Function + +In this case, we refer to the materials as arguments or inputs and the resulting object is refered to as output or return value. This process of taking input, doing something, and then sending back the output is demonstrated in the gif below. + +.. image:: Figures/function_calls.gif + :alt: Represenation of a Function + It is also possible for programmers to define new functions in their programs. You will learn how to do that later in the course. For now, you just need to learn how to invoke, or call, a function, and understand that the execution of the function returns a computed value. .. activecode:: functionCalls_1 @@ -28,7 +38,13 @@ It is also possible for programmers to define new functions in their programs. Y def sub(x, y): return x - y -We've defined two functions above. The code is hidden so as not to bother you (yet) with how functions are defined. ``square`` takes a single input parameter, and returns that input multiplied by itself. ``sub`` takes two input parameters and returns the result of subtracting the second from the first. Obviously, these functions are not particularly useful, since we have the operators ``*`` and ``-`` available. But they illustrate how functions work. +We've defined two functions above. The code is hidden so as not to bother you (yet) with how functions are defined. +``square`` takes a single input parameter, and returns that input multiplied by itself. ``sub`` takes two input +parameters and returns the result of subtracting the second from the first. Obviously, these functions are not +particularly useful, since we have the operators ``*`` and ``-`` available. But they illustrate how functions work. The visual below illustrates how the ``square`` function works. + +.. image:: Figures/square_function.gif + :alt: a visual of the square function. Four is provided as the input, the function object shakes, and then sixteen comes out from the bottom of the function object. .. activecode:: functionCalls_2 :include: functionCalls_1 @@ -40,10 +56,20 @@ We've defined two functions above. The code is hidden so as not to bother you (y print(sub(6, 4)) print(sub(5, 9)) +Notice that when a function takes more than one input parameter, the inputs are separated by a comma. Also notice +that the order of the inputs matters. The value before the comma is treated as the first input, the value after it +as the second input. -Notice that when a function takes more than one input parameter, the inputs are separated by a comma. Also notice that the order of the inputs matters. The value before the comma is treated as the first input, the value after it as the second input. +Again, remember that when python performs computations, the results are only shown in the output window if there's +a print statement that says to do that. -Again, remember that when python performs computations, the results are only shown in the output window if there's a print statement that says to do that. +You may be wondering now if print is a function. As mentioned above, functions can compute new values when the +functions are called or invoked. Fuctions can be used for more than mathmatical computation though. Print is also a +function that programmers use often to output data or check what is happenning in their code. If you come across +Python 2 code you may notice that print statements do not require parentheses even though print is still a function +in that version of Python. This is one of the differences between Python 2 and Python 3. In this course, we will be +teaching Python 3 and using the parentheses. Each time we use a print statement we are calling the print function +to execute the code. Function calls as part of complex expressions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -77,7 +103,10 @@ Let's take a look at how that last execution unfolds. Functions are objects; parentheses invoke functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Remember the earlier mention that some kinds of python objects don't have a nice printed representation? Functions are themselves just objects. If you tell python to print the function object, rather than printing the results of invoking the function object, you'll get one of those not-so-nice printed representations. Just stating the name of the function refers to the function. The name of the function followed by parentheses ``()`` invokes the function. +Remember the earlier mention that some kinds of python objects don't have a nice printed representation? Functions +are themselves just objects. If you tell python to print the function object, rather than printing the results of +invoking the function object, you'll get one of those not-so-nice printed representations. Just stating the name of +the function refers to the function. The name of the function followed by parentheses ``()`` invokes the function. .. activecode:: functionCalls_3 :include: functionCalls_1 @@ -87,90 +116,11 @@ Remember the earlier mention that some kinds of python objects don't have a nice print(square) print(sub) -.. mchoice:: exercise_functionCalls_1 - :answer_a: sub(5, 8) - :answer_b: -3 - :answer_c: 3 - :answer_d: nothing will print - :feedback_a: The result of executing the function call will print out - :feedback_b: The second is subtracted from the first - :feedback_c: The second is subtracted from the first - :feedback_d: The print statement makes the results print - :correct: b - :practice: T - :topics: SimplePythonData/FunctionCalls - - What will the output be from this code? - - .. code-block:: python - - def sub(x, y): - return x - y - - print(sub(5, 8)) - -.. mchoice:: exercise_functionCalls_2 - :answer_a: sub(5, 8) - :answer_b: -3 - :answer_c: 3 - :answer_d: nothing will print - :feedback_a: The character sting is treated as a literal and printed out, without executing. - :feedback_b: The character sting is treated as a literal and printed out, without executing. - :feedback_c: The character sting is treated as a literal and printed out, without executing. - :feedback_d: The character sting is treated as a literal and printed out, without executing. - :correct: a - :practice: T - :topics: SimplePythonData/FunctionCalls - - What will the output be from this code? - - .. code-block:: python - - def sub(x, y): - return x - y - - print("sub(5, 8)") - -.. mchoice:: exercise_functionCalls_3 - :answer_a: sub(5, 8) - :answer_b: -3 - :answer_c: 3 - :answer_d: nothing will print - :feedback_a: There is no print statement - :feedback_b: There is no print statement - :feedback_c: There is no print statement - :feedback_d: There is no print statement - :correct: d - :practice: T - :topics: SimplePythonData/FunctionCalls - - What will the output be from this code? - - .. code-block:: python - - def sub(x, y): - return x - y - - sub(5, 8) - -.. mchoice:: exercise_functionCalls_4 - :answer_a: sub(5, 8) - :answer_b: -3 - :answer_c: 3 - :answer_d: nothing will print - :feedback_a: There is no print statement - :feedback_b: There is no print statement - :feedback_c: There is no print statement - :feedback_d: There is no print statement - :correct: d - :practice: T - :topics: SimplePythonData/FunctionCalls - - What will the output be from this code? - - .. code-block:: python - - def sub(x, y): - return x - y - - "sub(5, 8)" +We can do the same thing with the print function, however it looks odd in the textbook. If you print the print +function in the textbook, then you will see ``>``. +Executing this code outside of the textbook though will return ````. + +.. activecode:: functionCalls_4 + :nocanvas: + + print(print) \ No newline at end of file diff --git a/_sources/SimplePythonData/StatementsandExpressions.rst b/_sources/SimplePythonData/StatementsandExpressions.rst index fdf967b..ca484b0 100644 --- a/_sources/SimplePythonData/StatementsandExpressions.rst +++ b/_sources/SimplePythonData/StatementsandExpressions.rst @@ -10,16 +10,17 @@ Statements and Expressions -------------------------- -A **statement** is an instruction that the Python interpreter can execute. You -have only seen the assignment statement so far . Some other kinds of statements -that you'll see shortly are ``while`` statements, ``for`` statements, ``if`` -statements, and ``import`` statements. (There are other kinds too!) - +A **statement** is an instruction that the Python interpreter can execute. You have only seen the assignment +statement so far . Some other kinds of statements that you'll see shortly are ``while`` statements, ``for`` +statements, ``if`` statements, and ``import`` statements. (There are other kinds too!) .. index:: expression -An **expression** is a combination of literals, variable names, operators, and calls -to functions. Expressions need to be evaluated. The result of evaluating an expression is a *value* or *object*. +An **expression** is a combination of literals, variable names, operators, and calls to functions. +Expressions need to be evaluated. The result of evaluating an expression is a *value* or *object*. + +.. image:: Figures/expression_value_type.png + :alt: table that shows expressions and their value, and type. If you ask Python to ``print`` an expression, the interpreter **evaluates** the expression and displays the result. @@ -29,12 +30,11 @@ If you ask Python to ``print`` an expression, the interpreter **evaluates** the print(1 + 1 + (2 * 3)) print(len("hello")) -In this example ``len`` is a built-in Python function that returns the number -of characters in a string. +In this example ``len`` is a built-in Python function that returns the number of characters in a string. -The *evaluation of an expression* produces a value, which is why expressions -can appear on the right hand side of assignment statements. A literal all by -itself is a simple expression, and so is a variable. Evaluating a variable gives the value that the variable refers to. +The *evaluation of an expression* produces a value, which is why expressions can appear on the right hand side of +assignment statements. A literal all by itself is a simple expression, and so is a variable. Evaluating a variable +gives the value that the variable refers to. .. activecode:: ch02_14 :nocanvas: @@ -45,7 +45,8 @@ itself is a simple expression, and so is a variable. Evaluating a variable give print(y) -In a program, anywhere that a literal value (a string or a number) is acceptable, a more complicated expression is also acceptable. Here are all the kinds of expressions we've seen so far: +In a program, anywhere that a literal value (a string or a number) is acceptable, a more complicated expression is +also acceptable. Here are all the kinds of expressions we've seen so far: literal e.g., "Hello" or 3.14 @@ -59,14 +60,18 @@ operator expression function call expressions () -Notice that operator expressions (like ``+`` and ``*``) have sub-expressions before and after the operator. Each of these can themselves be simple or complex expressions. In that way, you can build up to having pretty complicated expressions. +Notice that operator expressions (like ``+`` and ``*``) have sub-expressions before and after the operator. Each of +these can themselves be simple or complex expressions. In that way, you can build up to having pretty complicated +expressions. .. activecode:: ch02_14a :nocanvas: print(2 * len("hello") + len("goodbye")) -Similarly, when calling a function, instead of putting a literal inside the parentheses, a complex expression can be placed inside the parentheses. (Again, we provide some hidden code that defines the functions ``square`` and ``sub``). +Similarly, when calling a function, instead of putting a literal inside the parentheses, a complex expression can +be placed inside the parentheses. (Again, we provide some hidden code that defines the functions ``square`` and +``sub``). .. activecode:: function_square_include :nocanvas: @@ -88,22 +93,41 @@ Similarly, when calling a function, instead of putting a literal inside the pare print(square(y + square(x))) print(sub(square(y), square(x))) -With a function call, it's even possible to have a complex expression before the left parenthesis, as long as that expression evaluates to a function object. For now, though, we will just use variable names (like square, sub, and len) that are directly bound to function objects. - -It is important to start learning to read code that contains complex expressions. The Python interpreter examines any line of code and *parses* it into components. For example, if it sees an ``=`` symbol, it will try to treat the whole line as an assignment statement. It will expect to see a valid variable name to the left of the =, and will parse everything to the right of the = as an expression. It will try to figure out whether the right side is a literal, a variable name, an operator expression, or a function call expression. If it's an operator expression, it will further try to parse the sub-expressions before and after the operator. And so on. You should learn to parse lines of code in the same way. - -In order to evaluate an operator expression, the Python interpreter first completely evaluates the expression before the operator, then the one after. In order to evaluate a function call expression, the interpreter evaluates the expression before the parentheses (i.e., it looks up the name of the function). Then it tries to evaluate each of the expressions inside the parentheses. There may be more than one, separated by commas. The values of those expressions are passed as inputs to the function when the function is called. - -If a function call expression is a sub-expression of some more complicated expression, as ``square(x)`` is in ``sub(square(y), square(x))``, then the return value from ``square(x)`` is passed as an input to the ``sub`` function. This is one of the tricky things that you will have to get used to working out when you read (or write) code. In this example, the ``square`` function is called (twice) before the ``sub`` function is called, even though the ``sub`` function comes first when reading the code from left to right. - -To start giving you some practice in reading and understanding complicated expressions, try doing the Parsons problem below. Be careful not to indent any of the lines of code; that's something that will come later in the course. +With a function call, it's even possible to have a complex expression before the left parenthesis, as long as that +expression evaluates to a function object. For now, though, we will just use variable names (like square, sub, and +len) that are directly bound to function objects. + +It is important to start learning to read code that contains complex expressions. The Python interpreter examines +any line of code and *parses* it into components. For example, if it sees an ``=`` symbol, it will try to treat the +whole line as an assignment statement. It will expect to see a valid variable name to the left of the =, and will +parse everything to the right of the = as an expression. It will try to figure out whether the right side is a +literal, a variable name, an operator expression, or a function call expression. If it's an operator expression, it +will further try to parse the sub-expressions before and after the operator. And so on. You should learn to parse +lines of code in the same way. + +In order to evaluate an operator expression, the Python interpreter first completely evaluates the expression +before the operator, then the one after. In order to evaluate a function call expression, the interpreter evaluates +the expression before the parentheses (i.e., it looks up the name of the function). Then it tries to evaluate each +of the expressions inside the parentheses. There may be more than one, separated by commas. The values of those +expressions are passed as inputs to the function when the function is called. + +If a function call expression is a sub-expression of some more complicated expression, as ``square(x)`` is in +``sub(square(y), square(x))``, then the return value from ``square(x)`` is passed as an input to the ``sub`` +function. This is one of the tricky things that you will have to get used to working out when you read (or write) +code. In this example, the ``square`` function is called (twice) before the ``sub`` function is called, even though +the ``sub`` function comes first when reading the code from left to right. + +To start giving you some practice in reading and understanding complicated expressions, try doing the Parsons +problem below. Be careful not to indent any of the lines of code; that's something that will come later in the +course. .. parsonsprob:: ch02_14c :practice: T :topics: SimplePythonData/StatementsandExpressions - Please order the code fragments in the order in which the Python interpreter would evaluate them. x is 2 and y is 3. Now the interpreter is executing ``square(x + sub(square(y), 2 *x))``. + Please order the code fragments in the order in which the Python interpreter would evaluate them. x is 2 and y + is 3. Now the interpreter is executing ``square(x + sub(square(y), 2 *x))``. ----- look up the variable square to get the function object @@ -127,5 +151,3 @@ To start giving you some practice in reading and understanding complicated expre add 2 and 5 to get 7 ===== run the square function, again, on input 7, returning the value 49 - - diff --git a/_sources/SimplePythonData/Typeconversionfunctions.rst b/_sources/SimplePythonData/Typeconversionfunctions.rst index beadae0..779c298 100644 --- a/_sources/SimplePythonData/Typeconversionfunctions.rst +++ b/_sources/SimplePythonData/Typeconversionfunctions.rst @@ -57,6 +57,12 @@ quotes are removed. However, if we print the type, we can see that it is defini print(str(123.45)) print(type(str(123.45))) +Because we can only print one type at a time, if we want to print out a string and an integer then we have to convert +the type. Think about which type you'd need to convert, a string to an integer or an integer to a string? + +.. image:: Figures/type_cast.gif + :alt: a variable stores the value 55. a print statement tries to print "the value is" and the integer, but a runtime error occurs. Solution is to convert the integer into a string so that it only prints one type. + **Check your understanding** .. mchoice:: test_question2_2_1 @@ -79,5 +85,4 @@ quotes are removed. However, if we print the type, we can see that it is defini print(int(53.785)) -.. index:: variable, assignment, assignment statement, state snapshot diff --git a/_sources/SimplePythonData/VariableNamesandKeywords.rst b/_sources/SimplePythonData/VariableNamesandKeywords.rst index 4291785..daf6c1b 100644 --- a/_sources/SimplePythonData/VariableNamesandKeywords.rst +++ b/_sources/SimplePythonData/VariableNamesandKeywords.rst @@ -90,5 +90,5 @@ remember, what the variable is used for. True or False: the following is a legal variable name in Python: A_good_grade_is_A+ -.. index:: statement + diff --git a/_sources/SimplePythonData/Variables.rst b/_sources/SimplePythonData/Variables.rst index 496b48e..27b5aab 100644 --- a/_sources/SimplePythonData/Variables.rst +++ b/_sources/SimplePythonData/Variables.rst @@ -157,5 +157,5 @@ For example, we can find out the data type of the current value of a variable by print(day) -.. index:: keyword, underscore character + diff --git a/_sources/Sort/.DS_Store b/_sources/Sort/.DS_Store new file mode 100644 index 0000000..adcd829 Binary files /dev/null and b/_sources/Sort/.DS_Store differ diff --git a/_sources/Sort/Anonymousfunctionswithlambdaexpressions.rst b/_sources/Sort/Anonymousfunctionswithlambdaexpressions.rst index e17d846..047ee5f 100644 --- a/_sources/Sort/Anonymousfunctionswithlambdaexpressions.rst +++ b/_sources/Sort/Anonymousfunctionswithlambdaexpressions.rst @@ -10,18 +10,20 @@ Anonymous functions with lambda expressions ------------------------------------------- -To further drive home the idea that we are passing a function object as a parameter -to the sorted object, let's see an alternative notation for creating a function, -a **lambda expression**. The syntax of a lambda expression is the word "lambda" followed -by parameter names, separated by commas but not inside (parentheses), followed -by a colon and then an expression. ``lambda arguments: expression`` yields a function object. -This unnamed object behaves like a function object defined with +To further drive home the idea that we are passing a function object as a parameter to the sorted object, +let's see an alternative notation for creating a function, a **lambda expression**. The syntax of a lambda +expression is the word "lambda" followed by parameter names, separated by commas but not inside (parentheses), +followed by a colon and then an expression. ``lambda arguments: expression`` yields a function object. This +unnamed object behaves just like the function object constructed below. .. sourcecode:: python def fname(arguments): return expression +.. image:: Figures/lambda.gif + :alt: image showing how elements of a lambda expression are like a function definition. + Consider the following code .. activecode:: sort_7 @@ -38,9 +40,8 @@ Consider the following code print((lambda x: x-2)(6)) Note the paralells between the two. At line 4, f is bound to a function object. Its printed representation -is "". At line 8, the lambda expression produces a function object. Because it is -unnamed (anonymous), its printed representation doesn't include a name for it, ">". Both are of type -'function'. +is "". At line 8, the lambda expression produces a function object. Because it is unnamed (anonymous), +its printed representation doesn't include a name for it, ">". Both are of type 'function'. A function, whether named or anonymous, can be called by placing parentheses () after it. In this case, because there is one parameter, there is one value in parentheses. This @@ -50,9 +51,9 @@ of grouping all its contents together. Without the extra parentheses around it o the interpreter would group things differently and make a function of x that returns x - 2(6). Some students find it more natural to work with lambda expressions than to refer to a function -by name. Others find the syntax of lambda expressions confusing. It's up to you -which version you want to use. In all the examples below, both ways of doing it will -be illustrated. +by name. Others find the syntax of lambda expressions confusing. It's up to you which version you want to +use though you will need to be able to read and understand lambda expressions that are written by others. +In all the examples below, both ways of doing it will be illustrated. Below, sorting on absolute value has been rewritten using lambda notation and the built-in function abs. diff --git a/_sources/Sort/Figures/lambda.gif b/_sources/Sort/Figures/lambda.gif new file mode 100644 index 0000000..c545f36 Binary files /dev/null and b/_sources/Sort/Figures/lambda.gif differ diff --git a/_sources/UMich-SI106-F17/.DS_Store b/_sources/UMich-SI106-F17/.DS_Store new file mode 100644 index 0000000..f55396f Binary files /dev/null and b/_sources/UMich-SI106-F17/.DS_Store differ diff --git a/_sources/Unix/Figures/file_system_unix.jpeg b/_sources/Unix/Figures/file_system_unix.jpeg new file mode 100644 index 0000000..23da838 Binary files /dev/null and b/_sources/Unix/Figures/file_system_unix.jpeg differ diff --git a/_sources/Unix/Figures/unix_command_to_home.gif b/_sources/Unix/Figures/unix_command_to_home.gif new file mode 100644 index 0000000..7193df6 Binary files /dev/null and b/_sources/Unix/Figures/unix_command_to_home.gif differ diff --git a/_sources/Unix/Figures/unix_command_to_parent.gif b/_sources/Unix/Figures/unix_command_to_parent.gif new file mode 100644 index 0000000..0be01a6 Binary files /dev/null and b/_sources/Unix/Figures/unix_command_to_parent.gif differ diff --git a/_sources/Unix/Figures/unix_command_to_relative.gif b/_sources/Unix/Figures/unix_command_to_relative.gif new file mode 100644 index 0000000..8211abc Binary files /dev/null and b/_sources/Unix/Figures/unix_command_to_relative.gif differ diff --git a/_sources/Unix/Figures/unix_command_to_root.gif b/_sources/Unix/Figures/unix_command_to_root.gif new file mode 100644 index 0000000..6bfef33 Binary files /dev/null and b/_sources/Unix/Figures/unix_command_to_root.gif differ diff --git a/_sources/Unix/FoldersAndPaths.rst b/_sources/Unix/FoldersAndPaths.rst index 503e73c..692b76e 100644 --- a/_sources/Unix/FoldersAndPaths.rst +++ b/_sources/Unix/FoldersAndPaths.rst @@ -7,9 +7,6 @@ the license is included in the section entitled "GNU Free Documentation License". - - - Directories and Paths --------------------- @@ -25,26 +22,63 @@ When you are in a command prompt window, you are always connected to some partic The stuff before the $ indicates that you are connected to the ~/Desktop directory. After the $ is a blinking cursor, indicating that you are free to type in a new command there. +Here is an example system that we will be referencing later on: + +.. image:: Figures/file_system_unix.jpeg + :alt: a flow chart where the root directory is at the top, the next level are 'folders' for Applications, System, and Users. Below Users are 'folders' for Steve and Anne. Below Anne is the 'folder' Documents. Below Steve are the 'folders' Desktop and Documents. Below Steve's Documents folder are two files, file1.py and my_prog.py + Unix Commands: cd, ls, and pwd ------------------------------ -From there, you can use commands to move to other directories. The ``cd`` command stands for "change directory." After the letters cd and a space, you will type a path string that specifies the directory to connect to. +From there, you can use commands to move to other directories. The ``cd`` command stands for "change directory." +After the letters cd and a space, you will type a path string that specifies the directory to connect to. -Starting a path with ``/`` means you're providing a **full path**. For example, if you have a path such as ``/Users/kniznica/Desktop``, you can type ``cd /Users/kniznica/Desktop`` to connect to that directory. +Starting a path with ``/`` means you're providing a **full path**. For example, if you have a path such as +``/Users/kniznica/Desktop``, you can type ``cd /Users/kniznica/Desktop`` to connect to that directory. If you only +provide the ``/`` while changing directories then you will move directly to the root of your computer. -The symbol ``~`` refers to your **home directory**. For example, if your username that you use to logon to the computer is kniznica, your home direcdtory might be ``/Users/kniznica``. To connect to your home directory, you would type ``cd ~``, or spell it out as ``cd Users/kniznica``. The advantage of ``cd ~``, beyond being shorter, is that you don't have to remember the full path name of your home directory. +.. image:: Figures/unix_command_to_root.gif -You can also use ~ as a prefix in a longer pathname. Usually, your Desktop folder will be a subdirectory of your home directory. Thus, you could type, ``cd ~/Desktop``. +The symbol ``~`` refers to your **home directory**. For example, if your username that you use to logon to the +computer is kniznica, your home direcdtory might be ``/Users/kniznica``. To connect to your home directory, you +would type ``cd ~``, or spell it out as ``cd Users/kniznica``. The advantage of ``cd ~``, beyond being shorter, is +that you don't have to remember the full path name of your home directory. -If the path you specify does not begin with either ~ or /, then it is a **relative path**, relative to where you are right now. It specifies a subdirectory of the current directory. Thus, for example, suppose your home directory contains a ``Documents`` subdirectory, which contains a directory called ``106``. Suppose you are currently connected to the home directory (cd ~). Then you could type ``cd Documents`` to connect to the Document directory, or ``cd Documents/106`` to connect to the 106 directory. Alternatively, starting from your home directory, you could go in two steps, ``cd Documents``, then ``cd 106``. In my case, I have one more layer of directories in the hierarchy: with 106 being a subdirectory of Courses, which is a subdirectory of Documents, as shown in the Figure below. +You can also use ~ as a prefix in a longer pathname. Usually, your Desktop folder will be a subdirectory of your +home directory. Thus, you could type, ``cd ~/Desktop``. + +.. image:: Figures/unix_command_to_home.gif + +If the path you specify does not begin with either ~ or /, then it is a **relative path**, relative to where you +are right now. It specifies a subdirectory of the current directory. Thus, for example, suppose your home directory +contains a ``Documents`` subdirectory, which contains a directory called ``106``. Suppose you are currently +connected to the home directory (cd ~). Then you could type ``cd Documents`` to connect to the Document directory, +or ``cd Documents/106`` to connect to the 106 directory. + +.. image:: Figures/unix_command_to_relative.gif + +Alternatively, starting from your home directory, you could go in two steps, ``cd Documents``, then ``cd 106``. In +my case, I have one more layer of directories in the hierarchy: with 106 being a subdirectory of Courses, which is +a subdirectory of Documents, as shown in the Figure below. .. image:: Figures/cd_1.JPG -Now, if you are connected to this ``106`` directory, and all it has in it is document files of notes you take in class and screenshot images, you cannot do ``cd Documents`` -- you can try, but it will not work. Once you are **in** ``106``, ``cd Documents`` is trying to find a subdirectory of 106 named Documents, which doesn't exist. +Now, if you are connected to this ``106`` directory, and all it has in it is document files of notes you take in +class and screenshot images, you cannot do ``cd Documents`` -- you can try, but it will not work. Once you are +**in** ``106``, ``cd Documents`` is trying to find a subdirectory of 106 named Documents, which doesn't exist. + +If you want to go back up one level in the file structure, from a subdirectory to the containing directory, there +is a syntax especially for that: ``cd ..``. So if you are at ``~/Documents/106`` and now you want to go back to the +``Documents`` directory in your command prompt, you would type ``cd ..`` at the prompt. If you wanted to go up two +levels, back to your home directory, you would type ``cd ../..``. Of course, if the final destination is your home +directory, you could just type ``cd ~``. -If you want to go back up one level in the file structure, from a subdirectory to the containing directory, there is a syntax especially for that: ``cd ..``. So if you are at ``~/Documents/106`` and now you want to go back to the ``Documents`` directory in your command prompt, you would type ``cd ..`` at the prompt. If you wanted to go up two levels, back to your home directory, you would type ``cd ../..``. Of course, if the final destination is your home directory, you could just type ``cd ~``. +.. image:: Figures/unix_command_to_parent.gif -Once you've reached a directory, there are a lot of powerful unix commands you can use that act on the contents of the current directory. The next one we'll discuss is ``ls``, which is a command that lists all files that are in your current folder. (The directory, or folder, that you're **currently in** in the command prompt is often referred to as your **working directory**.) +Once you've reached a directory, there are a lot of powerful unix commands you can use that act on the contents of +the current directory. The next one we'll discuss is ``ls``, which is a command that lists all files that are in +your current folder. (The directory, or folder, that you're **currently in** in the command prompt is often +referred to as your **working directory**.) ``ls`` is a way to list a directory's contents. For example, now that we have gone to a folder, ``ls`` will display a list like this: diff --git a/_sources/_static/.DS_Store b/_sources/_static/.DS_Store new file mode 100644 index 0000000..d5c3b54 Binary files /dev/null and b/_sources/_static/.DS_Store differ diff --git a/_sources/index.rst b/_sources/index.rst index 8bffa5b..9b8bab9 100644 --- a/_sources/index.rst +++ b/_sources/index.rst @@ -21,6 +21,21 @@ Table of Contents ::::::::::::::::: +.. toctree:: + :maxdepth: 2 + + Assessments/week1a1.rst + Assessments/week1a2.rst + Assessments/week1a3.rst + Assessments/week1a4.rst + Assessments/week2a1.rst + Assessments/week3a1.rst + Assessments/week3a2.rst + Assessments/week3a3.rst + Assessments/week4a1.rst + Assessments/week5a1.rst + Assessments/week5a2.rst + Assessments/assigmentcourseone.rst General Introduction :::::::::::::::::::: @@ -43,7 +58,7 @@ General Introduction GeneralIntro/Comments.rst GeneralIntro/Glossary.rst - +.. the syntax errors page now has code, thanks to the coursera course. Move a Typical first program before then. Simple Python Data :::::::::::::::::: @@ -57,16 +72,15 @@ Simple Python Data SimplePythonData/FunctionCalls.rst SimplePythonData/DataTypes.rst SimplePythonData/Typeconversionfunctions.rst + SimplePythonData/StatementsandExpressions.rst SimplePythonData/Variables.rst SimplePythonData/VariableNamesandKeywords.rst - SimplePythonData/StatementsandExpressions.rst SimplePythonData/OrderofOperations.rst SimplePythonData/BooleanValuesandBooleanExpressions.rst SimplePythonData/Logicaloperators.rst SimplePythonData/PrecedenceofOperators.rst SimplePythonData/Reassignment.rst SimplePythonData/UpdatingVariables.rst - SimplePythonData/HardCoding.rst SimplePythonData/Input.rst SimplePythonData/Glossary.rst SimplePythonData/Exercises.rst @@ -117,6 +131,7 @@ Sequences Sequences/ListMembership.rst Sequences/ConcatenationandRepetition.rst Sequences/ListSlices.rst + Sequences/DisabmiguatingSquareBrackets.rst Sequences/SplitandJoin.rst Sequences/ListsareMutable.rst Sequences/ListDeletion.rst @@ -140,12 +155,15 @@ Iteration Iteration/TheforLoop.rst Iteration/FlowofExecutionoftheforLoop.rst Iteration/Stringsandforloops.rst + Iteration/TheRangeFunction.rst Iteration/TraversalandtheforLoopByIndex.rst Iteration/Listsandforloops.rst Iteration/GeneralizedSequences.rst Iteration/TheAccumulatorPattern.rst Iteration/TheAccumulatorPatternwithLists.rst Iteration/TheAccumulatorPatternwithStrings.rst + Iteration/TheAccumulatorPatternwithConditionals.rst + Iteration/AccumulatorPatternStrategies.rst Iteration/Glossary.rst Iteration/Exercises.rst Iteration/ExtraExercises.rst @@ -608,6 +626,14 @@ In Class Exercises assignments.rst +106 Specific Content +:::::::::::::::::::: + +.. toctree:: + :maxdepth: 2 + + SimplePythonData/HardCoding.rst + Discussion Section Exercises :::::::::::::::::::::::::::: diff --git a/temp_source/toc.rst b/temp_source/toc.rst index 5bda5eb..069289a 100644 --- a/temp_source/toc.rst +++ b/temp_source/toc.rst @@ -46,9 +46,9 @@ Simple Python Data SimplePythonData/ValuesandDataTypes.rst SimplePythonData/Typeconversionfunctions.rst + SimplePythonData/StatementsandExpressions.rst SimplePythonData/Variables.rst SimplePythonData/VariableNamesandKeywords.rst - SimplePythonData/StatementsandExpressions.rst SimplePythonData/OperatorsandOperands.rst SimplePythonData/Input.rst SimplePythonData/OrderofOperations.rst