Skip to content

Commit afe78ff

Browse files
committed
merge
2 parents 781c8cd + 6460bac commit afe78ff

File tree

6 files changed

+331
-57
lines changed

6 files changed

+331
-57
lines changed

Python/Module2_EssentialsOfPython/Basic_Objects.ipynb

Lines changed: 89 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,7 @@
364364
"2\\. What type of number will be returned if you perform a mathematical operation using an integer and a floating-point number? Does this hold for all the arithmetic operations? Determine this by trial and error.\n",
365365
"\n",
366366
"3\\. Given the function $f(x) = e^{|x - 2|}$, make use of the `math` module to compute $f(-0.2)$.\n",
367+
"\n",
367368
"***"
368369
]
369370
},
@@ -524,6 +525,7 @@
524525
">>> str(True)\n",
525526
"'True'\n",
526527
"```\n",
528+
"Once a string is formed, it cannot be changed (without creating an entirely new string). Thus a given string object cannot be \"mutated\" - a string is an *immutable* object.\n",
527529
"\n",
528530
"As the string stores a *sequence* of characters, Python provides a means for accessing individual characters and subsequences of characters from a string:\n",
529531
"```python\n",
@@ -538,7 +540,7 @@
538540
"### String essentials\n",
539541
"We will only scratch the surface with strings, touching on some essentials. Please refer to the [official Python tutorial](https://docs.python.org/3/tutorial/introduction.html#strings) for a more extensive, but still informal, overview of strings.\n",
540542
"\n",
541-
"In a string, `\\n` is treated as a single character. It denotes a new-line in a string, and will be rendered thusly when the string is printed.\n",
543+
"In a string, `\\n` is treated as a single character. It denotes a new-line in a string, and will be rendered thusly when the string is printed. Similarly, `\\t` will render as a tab-character.\n",
542544
"\n",
543545
"```python\n",
544546
"# using `\\n` to create a newline\n",
@@ -580,9 +582,12 @@
580582
"\n",
581583
">>> \"x: {}, y: {}, z: {}\".format(3.2, 8.4, -1.0)\n",
582584
"'x: 3.2, y: 8.4, z: -1.0'\n",
583-
"```\n",
584585
"\n",
585-
"Once a string is formed, it cannot be changed (without creating an entirely new string). Thus a given string object cannot be \"mutated\" - a string is an *immutable* object.\n",
586+
"\n",
587+
">>> \"7\".isdigit()\n",
588+
"True\n",
589+
"\n",
590+
"```\n",
586591
"\n",
587592
"### Official documentation for strings\n",
588593
"- [Built-in functions for strings](https://docs.python.org/3/library/stdtypes.html#string-methods)\n",
@@ -596,6 +601,7 @@
596601
"***\n",
597602
"\n",
598603
"**Reading Comprehension: strings**\n",
604+
"\n",
599605
"To answer some of the following questions, you will need to peruse the documentation for the built-in functions of strings. It may take a bit of experimentation to understand the documentation's use of square-brackets to indicate optional inputs for a function.\n",
600606
"\n",
601607
"1\\. Use a function that will take the string `\"cat\"`, and returns the string `\" cat \"` (which has a length of 11, including the letters c, a, t). Now, change the way you call the function so that it returns `\"----cat----\"` instead. \n",
@@ -605,6 +611,14 @@
605611
"\n",
606612
"3\\. Remove the whitespace from both ends of: `\" basket \"` \n",
607613
"\n",
614+
"\n",
615+
"4\\. Create a string that will print as (the second line begins with a tab-character):\n",
616+
"```\n",
617+
"Hello\n",
618+
"\tover there\n",
619+
"```\n",
620+
"\n",
621+
"5\\. Convert the integer `12` to the string `\"12\"`.\n",
608622
"***"
609623
]
610624
},
@@ -732,6 +746,59 @@
732746
"- [Built-in functions for a list](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)"
733747
]
734748
},
749+
{
750+
"cell_type": "markdown",
751+
"metadata": {},
752+
"source": [
753+
"***\n",
754+
"\n",
755+
"**Reading Comprehension: lists**\n",
756+
"\n",
757+
"To answer some of the following questions, you will need to peruse the documentation for the built-in functions of lists.\n",
758+
"\n",
759+
"1\\. Create a list whose sole entry is the `None` object.\n",
760+
"\n",
761+
"2\\. Assign the variable `k` to a list that contains an integer, a boolean, and a string, in that order. Then, add two more entries to the end of the list: a float and a complex number. \n",
762+
"\n",
763+
"3\\. Alphabetize the list of names: `[\"Jane\", \"Adam\", \"Ryan\", \"Bob\", \"Zordon\", \"Jack\", \"Jackenzie\"]`. \n",
764+
"\n",
765+
"***"
766+
]
767+
},
768+
{
769+
"cell_type": "markdown",
770+
"metadata": {},
771+
"source": [
772+
"**Lists**\n",
773+
"\n",
774+
"1\\.\n",
775+
"```python\n",
776+
">>> [None]\n",
777+
"[None]\n",
778+
"```\n",
779+
"\n",
780+
"2\\.\n",
781+
"```python\n",
782+
">>> k = [4, False, \"moo\"]\n",
783+
">>> k.extend([3.14, complex(9, -2)])\n",
784+
">>> k\n",
785+
"[4, False, 'moo', 3.14, (9-2j)]\n",
786+
"```\n",
787+
"\n",
788+
"3\\.\n",
789+
"```python\n",
790+
">>> names = [\"Jane\", \"Adam\", \"Ryan\", \"Bob\", \"Zordon\", \"Jack\", \"Jackenzie\"]\n",
791+
"\n",
792+
"# The documentation for `sort` says that the sorting happens \"in-place\". This\n",
793+
"# means that the original list is replaced by the sorted list. The alternative\n",
794+
"# would be that `sort` returns a new, sorted list, without changing the list\n",
795+
"# assigned to `names`.\n",
796+
">>> names.sort()\n",
797+
">>> names\n",
798+
"['Adam', 'Bob', 'Jack', 'Jackenzie', 'Jane', 'Ryan', 'Zordon']\n",
799+
"```"
800+
]
801+
},
735802
{
736803
"cell_type": "markdown",
737804
"metadata": {},
@@ -778,7 +845,13 @@
778845
">>> y = 0.5\n",
779846
">>> y.as_integer_ratio()\n",
780847
"(1, 2)\n",
848+
"\n",
849+
">>> z = [1, 2]\n",
850+
">>> z.append(3)\n",
851+
">>> z\n",
852+
"[1, 2, 3]\n",
781853
"```\n",
854+
"\n",
782855
"You should leverage the official documentation, for which links were provided throughout this section, whenever you are wondering how to best do a specific task with a given type of object.\n",
783856
"\n",
784857
"As a final reminder, we saw that that an integer in Python is able to hold a value with arbitrarily-many digits. A floating-point number, on the other hand, is restricted in the number of \"significant\" digits it can hold. Thus, where it is perfectly fine to check if two integers are exactly equal:\n",
@@ -895,6 +968,19 @@
895968
"```python\n",
896969
">>> \" basket \".strip()\n",
897970
"'basket'\n",
971+
"```\n",
972+
"\n",
973+
"4\\.\n",
974+
"```python\n",
975+
">>> print(\"Hello\\n\\tover there\")\n",
976+
"Hello\n",
977+
"\tover there\n",
978+
"```\n",
979+
"\n",
980+
"5\\.\n",
981+
"```python\n",
982+
">>> str(11)\n",
983+
"\"11\"\n",
898984
"```"
899985
]
900986
}

Python/Module2_EssentialsOfPython/ConditionalStatements.ipynb

Lines changed: 146 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,15 @@
55
"metadata": {},
66
"source": [
77
"# Conditional Statements\n",
8+
"\n",
9+
"<div class=\"alert alert-warning\">\n",
10+
"\n",
11+
"**Note**: \n",
12+
"\n",
13+
"There are reading-comprehension exercises included throughout the text. These are meant to help you put your reading to practice. Solutions for the exercises are included at the bottom of this page.\n",
14+
"</div>\n",
15+
"\n",
16+
"\n",
817
"In this section, we will be introduced to the `if`, `else`, and `elif` statements. These allow you to specify that blocks of code are to be executed only if specified conditions are found to be true, or perhaps alternative code if the condition is found to be false. \n",
918
"\n",
1019
"Please refer to the \"Basic Python Object Types\" subsection to recall the basics of the \"boolean\" type, which represents True and False. We will extend that discussion by introducing comparison operations and membership-checking, and then expanding on the utility of the built-in `bool` type. "
@@ -48,28 +57,40 @@
4857
"```python\n",
4958
">>> 2 < 3 < 1 # performs (2 < 3) and (3 < 1)\n",
5059
"False\n",
51-
"```"
52-
]
53-
},
54-
{
55-
"cell_type": "markdown",
56-
"metadata": {},
57-
"source": [
58-
"## Testing for Membership in Collections: `in` and `not in`\n",
59-
"The `in` and `not in` statements are a built-in operator for *testing for membership in a collection of items*. For example:\n",
60+
"```\n",
61+
"\n",
62+
"Whereas `==` checks to see if two objects have the same value, the `is` operator checks to see if two objects are actually the *same* object. For example, creating two lists with the same contents produces two *distinct* lists, that have the same \"value\":\n",
6063
"\n",
6164
"```python\n",
62-
">>> 2 in [3, 2, 0] # test for membership in a list\n",
65+
"# demonstrating `==` vs `is`\n",
66+
">>> x = [1, 2, 3]\n",
67+
">>> y = [1, 2, 3]\n",
68+
"\n",
69+
">>> x == y\n",
6370
"True\n",
6471
"\n",
65-
">>> 3 not in (-2, -1, 0) # test for membership in a tuple\n",
72+
"# `x` and `y` reference equivalent, but distinct lists\n",
73+
">>> x is y\n",
74+
"False\n",
75+
"```\n",
76+
"\n",
77+
"Thus the `is` operator is most commonly used to check if a variable references the `None` object, or either of the boolean objects:\n",
78+
"```python\n",
79+
">>> x = None\n",
80+
">>> x is None\n",
6681
"True\n",
6782
"\n",
68-
">>> \"a\" in \"apple\" # test for membership in a string\n",
83+
"# (2 < 0) returns the object `False`\n",
84+
"# thus this becomes: `False is False`\n",
85+
">>> (2 < 0) is False\n",
6986
"True\n",
7087
"```\n",
7188
"\n",
72-
"Whenever possible, Python uses efficient algorithms for testing membership, as invoked by `in` and `not in`."
89+
"Use `is not` to check if two objects are distinct:\n",
90+
"```python\n",
91+
">>> 1 is not None\n",
92+
"True\n",
93+
"```"
7394
]
7495
},
7596
{
@@ -124,7 +145,20 @@
124145
"metadata": {},
125146
"source": [
126147
"## `if`, `else`, and `elif`\n",
127-
"We now introduce the simple, but powerful `if`, `else`, and `elif` conditional statements. The following pseudo-code demonstrates their general usage:\n",
148+
"We now introduce the simple, but powerful `if`, `else`, and `elif` conditional statements. This will allow us to create simple branches in our code. For instance, suppose you are writing code for a videogame, and you want to update a character's status based on her/his number of health-points (an integer). The following code is representative of this:\n",
149+
"\n",
150+
"```python\n",
151+
"if num_health > 80:\n",
152+
" status = \"good\"\n",
153+
"elif num_health > 50:\n",
154+
" status = \"okay\"\n",
155+
"elif num_health > 0:\n",
156+
" status = \"danger\"\n",
157+
"else:\n",
158+
" status = \"dead\"\n",
159+
"```\n",
160+
"\n",
161+
"The following pseudo-code demonstrates their general template for conditional statements:\n",
128162
"\n",
129163
"```\n",
130164
"if <expression_1>:\n",
@@ -155,13 +189,19 @@
155189
"```python\n",
156190
"x = [1, 2]\n",
157191
"\n",
158-
"if 3 < len(x): # bool(3 < 2) returns False\n",
192+
"if 3 < len(x):\n",
193+
" # bool(3 < 2) returns False, this code \n",
194+
" # block is skipped\n",
159195
" print(\"`x` has more than three items in it\")\n",
160-
"elif len(x) == 2 # bool(len(x) == 2) returns True\n",
196+
"elif len(x) == 2\n",
197+
" # bool(len(x) == 2) returns True\n",
198+
" # this code block is executed\n",
161199
" print(\"`x` has two items in it\")\n",
162-
"elif len(x) == 1 # this statement is never reached\n",
200+
"elif len(x) == 1\n",
201+
" # this statement is never reached\n",
163202
" print(\"`x` has one items in it\")\n",
164-
"else: # this statement is never reached\n",
203+
"else:\n",
204+
" # this statement is never reached\n",
165205
" print(\"`x` is an empty list\")\n",
166206
"\n",
167207
"\"`x` has two items in it\"\n",
@@ -178,20 +218,66 @@
178218
"if x < 0:\n",
179219
" x = x ** 2\n",
180220
"# x is now 1\n",
181-
"```\n",
221+
"```\n"
222+
]
223+
},
224+
{
225+
"cell_type": "code",
226+
"execution_count": 21,
227+
"metadata": {},
228+
"outputs": [],
229+
"source": [
230+
"my_file = \"code.pdf\"\n",
182231
"\n",
183-
"#### Pitfall: Variable Assignment in Conditional Contexts\n",
184-
"It is worth pointing out a \"dangerous\" code design pattern, which is to assign a variable conditionally. Take the following code for example:\n",
232+
"if \".\" in my_file:\n",
233+
" dot_index = my_file.index(\".\")\n",
234+
" filename = my_file[:dot_index]\n",
235+
"else:\n",
236+
" filename = my_file"
237+
]
238+
},
239+
{
240+
"cell_type": "code",
241+
"execution_count": 22,
242+
"metadata": {},
243+
"outputs": [
244+
{
245+
"data": {
246+
"text/plain": [
247+
"'code'"
248+
]
249+
},
250+
"execution_count": 22,
251+
"metadata": {},
252+
"output_type": "execute_result"
253+
}
254+
],
255+
"source": [
256+
"filename"
257+
]
258+
},
259+
{
260+
"cell_type": "markdown",
261+
"metadata": {},
262+
"source": [
263+
"***\n",
264+
"\n",
265+
"**Reading Comprehension: Conditional statements**\n",
185266
"\n",
267+
"1\\. Assume `my_list` is a list. Given the following code:\n",
186268
"```python\n",
187-
"# assume x and y have not yet been defined\n",
188-
"if 0 <= z:\n",
189-
" x = 1\n",
190-
"else:\n",
191-
" y = 1\n",
269+
"first_item = None\n",
270+
"\n",
271+
"if my_list:\n",
272+
" first_item = my_list[0]\n",
192273
"```\n",
193274
"\n",
194-
"Any code following this \"if-else\" block is in a perilous state: `y` is never defined if `z` is positive, in which case any subsequent code referencing `y` will raise an error. Similarly, `x` will never be defined if `z` is negative. *Never define a variable conditionally*."
275+
"What will happen if `my_list` is `[]`? Will `IndexError` be raised? What will `first_item` be?\n",
276+
"\n",
277+
"2\\. The variable `my_file` is a string like `\"code.py\"`, `\"my_doc.txt\"`, etc, where a period demarks the end of the file-name and the beginning of the file-type. `my_file` will have at most one period in it. Write code that creates a variable which stores only the filename. Accomodate cases where `my_file` does *not* include a file-type. \n",
278+
"\n",
279+
"That is, `\"code.py\"` $\\rightarrow$ `\"code\"`, `\"doc2.pdf\"` $\\rightarrow$ `\"doc2\"`, `\"hello_world\"` $\\rightarrow$ `\"hello_world\"` \n",
280+
"***"
195281
]
196282
},
197283
{
@@ -232,13 +318,46 @@
232318
"# will append 0 to `my_list if `x` is negative\n",
233319
"my_list.append(1 if x >= 0 else 0)\n",
234320
"```\n",
321+
"```python\n",
322+
">>> x = 2\n",
323+
">>> \"a\" if x == 1 else \"b\"\n",
324+
"\"b\n",
325+
"```\n",
235326
"We will see this syntax shine when we learn about comprehension statements. That being said, this syntax should be used judiciously. For example, inline if-else statements ought not be used in arithmetic expressions, for therein lies madness:\n",
236327
"\n",
237328
"```python\n",
238329
"# don't ever do this...ever!\n",
239330
"2 - 3 if x < 1 else 1 + 6*2 if x >= 0 else 9\n",
240331
"```"
241332
]
333+
},
334+
{
335+
"cell_type": "markdown",
336+
"metadata": {},
337+
"source": [
338+
"## Reading Comprehension Exercise Solutions:"
339+
]
340+
},
341+
{
342+
"cell_type": "markdown",
343+
"metadata": {},
344+
"source": [
345+
"**Conditional statements**\n",
346+
"\n",
347+
"1\\. If `my_list` is `[]`, then `bool(my_list)` will return `False`, and the code block will be skipped. Thus `first_item` will be `None`.\n",
348+
"\n",
349+
"2\\. First, check to see if `.` is even contained in `my_file`. If it is, find its index-position, and slice the string up to that index. Otherwise, `my_file` is already the file name.\n",
350+
"```python\n",
351+
"\n",
352+
"my_file = \"code.pdf\"\n",
353+
"\n",
354+
"if \".\" in my_file:\n",
355+
" dot_index = my_file.index(\".\")\n",
356+
" filename = my_file[:dot_index]\n",
357+
"else:\n",
358+
" filename = my_file\n",
359+
"```"
360+
]
242361
}
243362
],
244363
"metadata": {

0 commit comments

Comments
 (0)