├── .gitattributes
├── LICENSE
├── README.md
├── SUMMARY.md
└── manuscript
├── 01-intro-to-python.md
├── 02-more-about-language.md
├── 03-01-understanding-variables.md
├── 03-02-operators.md
├── 04-list-set-dict.md
├── 05-constructs.md
├── 06-file-handling.md
├── 08-exception.md
├── 09-functions.md
├── 10-task.md
├── 11-function-tasks.md
├── 12-modules-tasks.md
├── 13-examples.md
├── 14-object-oriented-programming.md
└── Book.txt
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.md linguist-language=python
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | build-app-with-python-antitextbook Copyright (C) 2017 Suraj Arun Patil
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Build applications in Python the anti-textbook
2 |
3 | | Source | Read online | Watch | Download | Code |
4 | | ----| ---- | ---- | ------ | ------ |
5 | | On [Github](https://github.com/thewhitetulip/build-app-with-python-antitextbook)| Free on [Gitbooks](https://thewhitetulip.gitbook.io/py/) | The [YouTube series](https://www.youtube.com/playlist?list=PL41psiCma00wwvtQyLFMFpzWxUYmSZwZy) | [Leanpub](https://leanpub.com/antitextbookpy/) | On [Github](https://github.com/thewhitetulip/code-build-app-with-python-antitextbook) |
6 |
7 | ## Who is this tutorial for?
8 | This book is not for a completely noob programmer, it expects _some_ initial programming experience.
9 |
10 | ## What is this?
11 | It's an easy to understand introduction to the Python programming language which focuses on teaching concepts via examples. The initial chapters explain various concepts and in a later chapter, you will build a command line todo list manager.
12 |
13 | The motto of this book is not just teach the language, but to enable you to write tools which you would use in day to day life, like a simple todo list manager, we encourage you to explore the language more after you read the book and start writing tools for your daily usage.
14 |
15 | ## Why Python?
16 | There are a large number of languages out there and new ones coming out every week, thus, it begs the question _why learn Python_ over X.
17 |
18 | Python has the following advantages:
19 |
20 | 1. Easy to understand syntax. Reads just like English.
21 | 1. Huge community.
22 | 1. Open source hence millions of packages available.
23 | 1. Short time needed for writing code.
24 |
25 | A programming language's usability is direct proportion to the size of its community squared, this is because the core team writes the language, but the content(books, podcasts, tutorials, packages, Q&A) surrounding the language is created by the community.
26 |
27 | ## Which Python?
28 | This guide focuses only on Python3, Python2 is on life support and we do not recommend using it, unless there is an exceptional scenario.
29 |
30 | ## Writing Style
31 |
32 | We have thirteen chapters:
33 |
34 | * Each chapter or topic has an associated YouTube screencast.
35 | * Each chapter has concepts explained by an example (can be as stupid as 1+1=2)
36 | * Code that is supposed to run on the Interpreter starts with `>>>` like `>>> not True`.
37 | ```Python
38 | >>> not True
39 | False
40 | ```
41 | In this case, `>>> not True` is the statement and `False` is the output.
42 | * Code that doesn't start with `>>>` is supposed to be run in a file with the extension .py
43 | * If there is significant code for the chapter, you can find a file in the code repository, please look on the basis of chapters.
44 |
45 | ## How to use?
46 | * Read the chapters end to end.
47 | * Watch the YouTube screencast, there is a reason why they are free!
48 | * Do NOT search the Internet for things like "how to do X in python", use the documentation.
49 |
50 | ## Installation
51 |
52 | 1. Linux and Mac: Use a package manager to install the python3 package.
53 | 1. Windows: Download the `.msi` or `.exe` file from https://python.org, run the installer, click on Next Next until it finishes.
54 | 1. Android: Install `termux` (https://termux.com/help.html) & run `apt-get install python3` to install python inside it.
55 | 1. iOS: Python3 for iOS (not free).
56 |
57 | ## Background
58 | This tutorial is the culmination of the various Python trainings I have given in the past. There was a lack of a guide which taught programming by building tools without overwhelming the readers, thus, this project got started.
59 |
60 | They say that write the book you wish existed in the world. This is a book which I wished existed when I was learning the language.
61 |
62 | Please note that I don't profess to be a God at anything, but I do feel that good things happen when a group comes together for one goal.
63 |
64 | This is an open source guide and I invite you to contribute.
65 |
66 | ## Multiversity
67 | This guide is a part of the [Multiversity](https://github.com/thewhitetulip/multiversity) initiative. The aim is to have high quality open source tutorials along with screencasts.
68 |
69 | ## Contribution
70 | We need your help to become a great guide! All contributions are welcome. Please raise an issue on Github!
71 |
72 | ##### Links
73 |
74 | | [Next](manuscript/01-intro-to-python.md) | [Index](SUMMARY.md)
75 | | ----| ----|
76 |
--------------------------------------------------------------------------------
/SUMMARY.md:
--------------------------------------------------------------------------------
1 | * [Introduction](manuscript/01-intro-to-python.md)
2 | * [More about Language](manuscript/02-more-about-language.md)
3 | * [Variables](manuscript/03-01-understanding-variables.md)
4 | * [Operators](manuscript/03-02-operators.md)
5 | * [Lists, sets, dictionaries](manuscript/04-list-set-dict.md)
6 | * [Constructs](manuscript/05-constructs.md)
7 | * [File handling](manuscript/06-file-handling.md)
8 | * [Exception handling](manuscript/08-exception.md)
9 | * [Functions](manuscript/09-functions.md)
10 | * [Writing a todo manager](manuscript/10-task.md)
11 | * [Adding Functions](manuscript/11-function-tasks.md)
12 | * [Adding Modules](manuscript/12-modules-tasks.md)
13 | * [Some more examples](manuscript/13-examples.md)
14 | * [Object oriented programming basics](manuscript/14-object-oriented-programming.md)
15 |
--------------------------------------------------------------------------------
/manuscript/01-intro-to-python.md:
--------------------------------------------------------------------------------
1 | # Introduction
2 |
3 | [Watch on YouTube](https://www.youtube.com/watch?v=7wuKDDMb3R4)
4 |
5 | Python is an [open source](https://github.com/python/cpython), cross platform, interpreted language. Cross platform means that a program written on any platform is guaranteed to run across any platform which Python supports. It is a powerful language because there are many third party packages available. The official repository of those packages is http://pypi.python.org. Python comes with a tool called `pip` which allows downloading libraries from the official repository.
6 |
7 | Python is widely used across major domains. YouTube, Quora, Hulu, Dropbox are just a few platforms written in Python. We can write command line applications, bootloaders, Robots, Machine Learning algorithms, automate test cases, system administration automation etc using Python.
8 |
9 | There are few things which make Python an awesome language:
10 |
11 | 1. English like syntax: It takes very little time to learn the language and write code. This makes it an excellent prototyping language.
12 |
13 | 2. Less number of lines: Programs implemented in Python have significantly less number of lines as compared to other languages.
14 |
15 | 3. High level data structures: Hashmaps, sets, lists make it really easy to write complex programs with comparatively less effort..
16 |
17 | Drawbacks:
18 |
19 | 1. Speed: Since it is an interpreted language, it is slower than most languages.
20 | 2. Debugging: Being a dynamically typed language, it is somewhat difficult to debug the programs.
21 |
22 | ## Python 2 vs Python3
23 |
24 | Python3 is the successor of Python2. In 2020 Python2 will be history. This tutorial is based on Python3 as it is the present and future of the language. Python3 is a backwards incompatible with Python2, which means, code written for Python2 is not guaranteed to run on Python3. There is a way of writing code which runs both on Python 2 and 3, but it is beyond the scope of this guide.
25 |
26 |
27 | ## Installation
28 | 1. Windows: Download the latest .exe file of Python3 from https://python.org and click on Next Next.
29 | 2. Android: Install Termux (https://termux.com/help.html), and then `apt-get install python3`..
30 | 3. Linux: sudo apt-get install python3 / sudo yum install python3 / use other package manager
31 | 4. Mac: brew install python3.
32 | 1. iOS: python 3 for ios (not free).
33 |
34 |
35 | ##### Links
36 | |[Next](02-more-about-language.md) | [Previous](../README.md) | [Index](../SUMMARY.md)
37 | | ---- | ---- | ---- |
38 |
--------------------------------------------------------------------------------
/manuscript/02-more-about-language.md:
--------------------------------------------------------------------------------
1 | # How to run Python code?
2 |
3 | Watch on [YouTube](https://www.youtube.com/watch?v=wSqRUTS7uAg)
4 |
5 | There are two modes of running Python code: Interactive and Batch.
6 |
7 | ### Interactive mode
8 | Code is typed inside an interpreter session which gets evaluated immediately. This mode is suitable for small edits.
9 |
10 | To start the interpreter, type `python3` or `python` on your terminal or command prompt.
11 |
12 | #### python3 vs python
13 | You have to figure out what to use while invoking the interpreter (python3 or python) based on the following:
14 |
15 | Type `python --version` on your command prompt.
16 |
17 | If it says Python 2, then you'll need to install python3 and execute code using `python3 file.py`.
18 | If it says Python 3, then you'll need to run all the code in this book as `python file.py`
19 |
20 |
21 | The Interpreter looks like this when it starts:
22 |
23 | ```
24 | Python 3.6.0 (default, Jan 13 2017, 22:22:15)
25 | Type "help", "copyright", "credits" or "license" for more information.
26 | >>>
27 | ```
28 |
29 | If you see `>>>`, this means that the interpreter has started and is waiting for your input. Type `print("Hello Python!")`.
30 |
31 | ```python
32 | >>> print("Hello Python!")
33 | Hello Python!
34 | ```
35 |
36 | The interpreter evaluates each line which you type. The `print` function is used to print content on the terminal. This is why you saw "Hello Python!" printed immediately on the next line.
37 |
38 | #### Using the Interpreter
39 |
40 | Start a new interpreter session and type `1 + 1` and hit enter. You will see the below output.
41 |
42 | ```python
43 | >>> 1 + 1
44 | 2
45 | ```
46 |
47 | Here, `1 + 1` is called an expression and `2` is the output.
48 |
49 | `+` will calculate the sum of two numbers (1 and 1) and return the result.
50 |
51 | ```python
52 | >>> 1 - 1
53 | 0
54 | ```
55 |
56 | `-` will calculate the subtraction of 1 and 1 and return the result.
57 |
58 | ```python
59 | >>> 10 * 10
60 | 100
61 | ```
62 |
63 | `*` multiplies 10 with 10 and return the result.
64 |
65 | ```python
66 | >>> 10 ** 2
67 | 100
68 | ```
69 |
70 | `**` is called the power operator, it returns 10 to the power of 2.
71 |
72 | #### Operator Types
73 |
74 | In the above expressions, `+`, `-`, `*` are called operators, they operate on numbers (which are called operands).
75 |
76 | In general, there are three types of operators:
77 |
78 | 1. Unary operators: Require one operand to operate on.
79 | 1. Binary operators: Require two operands to operate on. Most of the operators are binary (`-, +, *, **` etc)
80 | 1. Ternary operators: Require three operators to operate on.
81 |
82 | We won't be looking at unary and ternary operators now, we need to understand the language before jumping to ternary operators.
83 |
84 | ### Batch Mode
85 | The interpreter makes it difficult to write big programs. The best you can do in an interpreter is type lines of code. But, when you want to write programs and build applications, it is better to use the batch mode. In this, you create a text file who's name ends with `.py` like `file.py` and save it to your machine on some folder. We then run the file as `python3 file.py`.
86 |
87 | To execute the program, you'd need to use the `cd` program to change folders.
88 |
89 | For this book, create a folder. Open the terminal and type this.
90 |
91 | Mac/Linux (Applications -> Terminal)
92 |
93 | 1. `mkdir ~/antitextbookpy`
94 | You will save all the code files in this folder. You have to do this only once.
95 |
96 | 2. `cd ~/antitextbookpy`
97 | This will change the current working directory to `~/antitextbookpy`, you have to do this every time you open a new terminal window or tab.
98 |
99 | Windows: (open the Command Prompt)
100 |
101 | 1. `mkdir antitextbookpy`
102 | 1. `cd antitextbookpy`
103 |
104 | You would need to create a file in this folder, save it by giving it a `.py` extension then run it like `python file.py` from the command line. If it says file not found, then you might have to check if you followed the above steps (of changing directories).
105 |
106 | ##### Links
107 |
108 | |[Next](03-01-understanding-variables.md) | [Previous](01-intro-to-python.md) | [Index](../SUMMARY.md)
109 | | --------| --------| --------|
110 |
--------------------------------------------------------------------------------
/manuscript/03-01-understanding-variables.md:
--------------------------------------------------------------------------------
1 | # Variables
2 |
3 | Watch on [YouTube](https://www.youtube.com/watch?v=3_-W0S1VdLo) | Read the [docs](https://docs.python.org/3/reference/expressions.html#atom-identifiers)
4 |
5 | Variables are used to store values in memory. When using variables in Python, we do not have to declare the datatype of the variable. Python is a dynamic typing language, which means that when the interpreter will execute the code, it will figure out the data type of the variables on it's own.
6 |
7 | Every variable has these things:
8 |
9 | 1. Name: The variable name has to start with any valid unicode letter except those that have special significance like `\` or numbers.
10 | 1. Value: The content which is being stored in the variable.
11 | 1. Address: The location of the variable in the memory.
12 |
13 | There are restrictions about the variable name,
14 |
15 | * They can't start with numbers or special characters. We can not name a variable `0b` or `\a `.
16 | * They can not use reserved keywords (try, catch, if, for, while, except, in among others).
17 |
18 | If you want to create a variable `i` with the value 1, type this in the interpreter:
19 |
20 | ```python
21 | >>> i = 1
22 | ```
23 |
24 | This will create a variable `i` which:
25 |
26 | 1. Has the value 1.
27 | 1. Is of the data type integer.
28 | 1. Is located in some memory location.
29 |
30 | #### Finding address of a variable.
31 |
32 | To find out the address of the variable, we use the [id()](https://docs.python.org/3/library/functions.html?highlight=id#id) function.
33 |
34 | ```python
35 | >>> print(id(i))
36 | 405911019
37 | ```
38 |
39 | 405911019 is the memory location of the variable `i`.
40 |
41 | #### Finding data type of a variable.
42 | `type` is a builtin function which returns the data type of the argument passed to it. Read the [docs](https://docs.python.org/3/library/functions.html?highlight=id#type)
43 |
44 | ```python
45 | >>> print(type(1))
46 |
47 | ```
48 |
49 | The type() function takes an argument and returns the data type of the argument.
50 |
51 | ## Taking input from the user.
52 |
53 | At times, we want to take input from the user, we can use the `input()` function to do so.
54 |
55 | ```python
56 | >>> name = input("enter your name: ")
57 | enter your name: python
58 |
59 | >>> print("Your name is ", name)
60 | Your name is python
61 | ```
62 |
63 | This will take the name of the user as input and store it in variable `name`. `input` takes a string argument which is the message it should print while taking the input.
64 |
65 | By default, `input` returns a string. We have to convert a variable from string to integer by using the `int()` function. Each data type provides a function for data type conversion, for instance, `str()` is used to convert a value from other data type to string.
66 |
67 | ```python
68 | >>> age = input("enter your age: ")
69 | enter your age: 23
70 |
71 | >>> age = int(age)
72 |
73 | >>> print(type(age))
74 |
75 | ```
76 |
77 | When we do `age = int(age)`, this is not a syntax error, because the interpreter is going to create a **new** integer variable with the name of age (and delete the old string variable).
78 |
79 | ## Exercise
80 | 1. Take the user's name, age and height and print it to the terminal.
81 | 1. Take a number from the user and print it.
82 |
83 | ```python
84 | >>> i = 'Python'
85 | >>> # Creates a string variable with value Python
86 | >>> print(id(i))
87 | 505911019
88 | >>> type(i) # variable i is of type string now.
89 |
90 | ```
91 |
92 | ## Variable types
93 |
94 | ## Numeric
95 | Read the [docs](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex).
96 |
97 | #### Integer
98 |
99 | ```python
100 | >>> i = 0
101 | >>> i = 10000
102 | >>> i = 123333
103 | >>> print(type(1))
104 |
105 | ```
106 |
107 | #### Float
108 |
109 | ```python
110 | >>> i = 1.1
111 | >>> i = 3.3333344445
112 | >>> print(type(1.0))
113 |
114 | ```
115 |
116 | #### Complex
117 |
118 | ```python
119 | i = complex(1,2) # 1+2j
120 | i = complex(12,23) # 12 + 23j
121 | ```
122 |
123 | #### String
124 | Read the [docs](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str)
125 |
126 | ```python
127 | i = "this string\n\t" # \n and \t are special values if used with "
128 | i = 'this string\n\t' # \n and \t are special values if used with '
129 | i = r'this string\n\t' # \n and \t do not hold special value if prepended with r, r stands for raw'
130 | i = ''' multi line string
131 | which has
132 | multi lines'''
133 | i = """
134 | a ridiculously multi line string
135 | """
136 | ```
137 |
138 | ##### String validity
139 |
140 | The location of the ending quotes doesn't matter, the only thing which matters is that **it should exist**. The value of a string is in between the starting and ending quotes, either single, double or triple.
141 |
142 | `'this is a string', "this is a string", "'this is a string", '"this is a string', """ this is 'a string '""", '"""hi'`
143 |
144 | All are *valid* strings, they start and end with the same quote. If a string starts and ends with a single quote, then any number of double quotes can be part of the string, the same is true vice versa.
145 |
146 | `'"python"` and `"python''` are invalid strings. Both of them do not start and end with the same quote.
147 |
148 | #### Boolean
149 |
150 | `True` and `False` are special values in Python3. In previous version of the language, we were allowed to create a variable of name True and False, but now they are reserved.
151 |
152 | Read the [docs](https://docs.python.org/3/library/stdtypes.html#boolean-values)
153 |
154 | ```python
155 | >>> i = True
156 | >>> j = False
157 | >>> print(i)
158 | True
159 | ```
160 |
161 | ### Sequence type
162 |
163 | Read the [docs](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range)
164 |
165 | #### List
166 |
167 | List stores multiple values of any data type.
168 |
169 | ```python
170 | >>> i = [1,"Linux",3,"bash",[1,2,"sh"]]]
171 | ```
172 | #### Tuples
173 |
174 | Read the [docs](https://docs.python.org/3/library/stdtypes.html#tuple)
175 |
176 | Tuples are lists from which elements can't be added/deleted/modified.
177 |
178 | ```python
179 | >>> a = (1,2)
180 | >>> a[0]=2
181 | Traceback (most recent call last):
182 | File "", line 1, in
183 | TypeError: 'tuple' object does not support item assignment
184 | ```
185 |
186 | ```python
187 | a = (1,2,3)
188 | print(a)
189 | ```
190 |
191 | #### Dictionary
192 | Read the [docs](https://docs.python.org/3/library/stdtypes.html#dict)
193 |
194 | Dictionaries are a collection of key value pairs, lists/tuples/sets are indexed sequences, dictionaries aren't.
195 |
196 | Here, 'IN' and 'US' are the keys and 'India', 'United States' are the values. The values can be any Python data type, but keys can only be hashable data types (basic data types, int/float/string/complex).
197 |
198 | ```python
199 | i = {'IN':'India', 'US': 'United States'}
200 | print(i['IN'])
201 | print(i['US'])
202 | ```
203 |
204 | **Output:**
205 | ```
206 | India
207 | United States
208 | ```
209 |
210 | #### Set
211 | Read the [docs](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset)
212 |
213 | ```python
214 | i = set([1,2,3,4,5])
215 | ```
216 |
217 | Sets are same as lists, but they don't allow duplicates. Only hashable elements are allowed as their members (int, float, string, complex, tuples).
218 |
219 | ### Immutability
220 | When a data type is said to be immutable, the data type doesn't allow modifications.
221 |
222 | ### Hashing
223 | Hashing is a complicated process, just remember, hashable data types = immutable data types.
224 |
225 |
226 | ##### Links
227 |
228 | |[Next](03-02-operators.md) | [Previous](02-more-about-language.md) | [Index](../SUMMARY.md)
229 | | ----| ----| ----|
230 |
--------------------------------------------------------------------------------
/manuscript/03-02-operators.md:
--------------------------------------------------------------------------------
1 | # Operators
2 |
3 | Python has the following major operators:
4 |
5 | `<, >, =, ==, >=, <=, !=, *, +, -, **, +=, -=, /=, *=, in, and, not, is.`
6 |
7 | ## Operator priority
8 | When expressions containing more than one operators are evaluated, the operator priority is followed, it is just like the BODMAS (PEMDAS for Americans) rule of maths. Usage of `()` can override priority.
9 |
10 | ```python
11 | >>> 3 * 2 + 20 - 46
12 | -20
13 | >>> 3 * (2 + 20 - 46)
14 | -72
15 | ```
16 |
17 | ## Assignment
18 |
19 | `=` is the assignment operator.
20 |
21 | ```python
22 | >>> a = 1 # creates a new integer object of value 1
23 | # and stores the address in variable a.
24 | >>> a = 2 # creates a new integer object of value 2
25 | # and stores the address in variable a.
26 | >>> b = a # stores the address of variable a inside
27 | # variable b, they point to the same object.
28 | ```
29 |
30 | ## Multiply
31 |
32 | ```python
33 | >>> a = 12
34 | >>> a * 12
35 | 144
36 | >>> a = "ab_"
37 | >>> a * 2 # when * is used with strings,
38 | # it returns a new string twice.
39 | ab_ab_
40 | ```
41 |
42 | ## Exercise:
43 | 1. Take two numbers from the user and print their multiplication.
44 | 1. Take three numbers from the user and print their multiplication.
45 |
46 | ## Add
47 |
48 | ```python
49 | >>> a = 1
50 | >>> a + 1
51 | 2
52 | >>> a = 'py'
53 | >>> a + 'thon' # concatenates 'thon' to 'py' and creates a new string.
54 | python
55 | >>> a # we did not reassign a, so it's value is unchanged.
56 | py
57 | ```
58 |
59 | ## Exercise:
60 | 1. Take two strings from a variable and print their concatenation.
61 | 1. Take two numbers from the user and add them (you need to use the int() to convert the input to integer)
62 | 1. Take three numbers from the user and print their addition.
63 |
64 | ## Equality
65 | `==` is the equality operator, it returns true if both operands have the same value.
66 |
67 | ```python
68 | >>> a = 1 # creates variable a with value 1.
69 | >>> b = 1 # creates variable a with value 1
70 | >>> a == b # checks if a and b are equal.
71 | True
72 | ```
73 |
74 | > Note: It is a classic mistake to use `==` when you really want to use `=` or vice versa.
75 |
76 | ## Division
77 |
78 | `27/7` divides 27 by 7 and returns a floating point result
79 |
80 | `27//7` divides 27 by 7 and returns an integer result.
81 |
82 | ```python
83 | >>> 27/7
84 | 3.85714
85 | >>> 27//7
86 | 3
87 | >>> 27%7
88 | 1
89 | ```
90 |
91 | ## Power
92 |
93 | `**` is the operator for calculating power.
94 |
95 | ```python
96 | >>> a = 2
97 | >>> a**3
98 | 8
99 | ```
100 |
101 | ## Shortcut operators
102 |
103 | Consider that you have to create a variable `a = 3`. If you want to add `4` to the variable `a`.
104 |
105 | You can do the following:
106 |
107 | 1. `a = a + 4`. But this tends to be verbose.
108 | 1. `a += 4`: Another way to do exactly the same calculation.
109 |
110 | `+=` is a shortcut operator. There are other shortcut operators like: `+=, -=, /=, *=`. No spaces are allowed between -=, +=.
111 |
112 | In other languages, you can use `++` or `--`, but they are not available in Python.
113 |
114 | ```python
115 | >>> a = 10
116 | >>> a += 10
117 | >>> a = a + 10 # same as a += 10
118 | >>> a *= 10
119 | >>> a /= 10
120 | ```
121 |
122 | ## Membership test
123 |
124 | The `in` operator tests if the element on the left hand side is present in the right hand side sequence (list, tuple, set).
125 |
126 | ```python
127 | >>> a = [1,2,3] # also works on set and tuples.
128 | >>> 3 in a
129 | True
130 | ```
131 |
132 | ## Boolean operators
133 |
134 | Read the [docs](http://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not)
135 |
136 | ### not
137 |
138 | Read the [docs](http://docs.python.org/3/library/stdtypes.html#truth-value-testing)
139 | `not` converts True to False and vice versa.
140 |
141 | ```python
142 | >>> not True
143 | False
144 | >>> not False
145 | True
146 | ```
147 |
148 | #### False like values
149 | Variables of any data type when they are null or have no value, they are False like values.
150 | The negation of a False like value is True
151 |
152 | ```python
153 | >>> not '' # empty string is False like.
154 | True
155 | >>> not 0 # 0 is False like.
156 | True
157 | >>> not dict() # empty dict is False like.
158 | True
159 | >>> not list() # empty list is False like.
160 | True
161 | ```
162 |
163 | #### True like
164 | Variables of any data type when have _some_ value, any value, they are True like values.
165 | The negation of a True like value is False
166 |
167 | ```python
168 | >>> not 'dd'
169 | False
170 | >>> not 1 # non zero is True like.
171 | False
172 | >>> not -1 # non zero is True like.
173 | False
174 | >>> not [1,2,3] # list having any value is True like.
175 | False
176 | ```
177 |
178 | ### or
179 |
180 | OR is true when either of the operand is true.
181 |
182 | ```python
183 | >>> True or False
184 | True
185 | >>> False or False
186 | False
187 | ```
188 |
189 | ### and
190 |
191 | AND is true when both the operands are true.
192 |
193 | ```python
194 | >>> True and False
195 | False
196 | >>> False and False
197 | False
198 | >>> True and True
199 | True
200 | ```
201 |
202 | ### Comparision Operators
203 |
204 | Read the [docs](https://docs.python.org/3/library/stdtypes.html#comparisons)
205 |
206 | There are eight comparison operations in Python. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases y <= z is not evaluated at all if x < y is found to be false).
207 |
208 | This table summarizes the comparison operations:
209 |
210 | |Operation | Meaning|
211 | |------|------|
212 | |< | strictly less than|
213 | |<= | less than or equal|
214 | |> |strictly greater than|
215 | |>= | greater than or equal|
216 | |== | equal|
217 | |!= | not equal|
218 | |is | object identity|
219 | |is not | negated object identity|
220 |
221 | ##### Links
222 |
223 | |[Next](04-list-set-dict.md) | [Previous](03-01-understanding-variables.md) | [Index](../SUMMARY.md)
224 | | ----| ----| ----|
225 |
--------------------------------------------------------------------------------
/manuscript/04-list-set-dict.md:
--------------------------------------------------------------------------------
1 | # High level data structures
2 |
3 | In the last chapter we saw the various data types present in Python, in this chapter we'll look at the high level data types in detail.
4 |
5 | ## List
6 |
7 | Watch on [YouTube](https://www.youtube.com/watch?v=30S9LnvanwY) | Read the [docs](https://docs.python.org/3/library/stdtypes.html#list)
8 |
9 | An ordered collection of n values (n >= 0)
10 |
11 | Creating a list is simple:
12 |
13 | ```python
14 | >>> l = [] # creates an empty list.
15 | >>> l = list() # creates an empty list.
16 | >>> l = [1, 2, 3]
17 | ```
18 |
19 | Each element of a list has an index, indices in Python start with 0.
20 |
21 | Let's say we have a list of five values, `a = [11,22,33,44,55]`.
22 |
23 | | Value | Positive Index |
24 | | ----| ----|
25 | |11|0|
26 | |22|1|
27 | |33|2|
28 | |44|3|
29 | |55|4|
30 |
31 | Indices can be negative.
32 |
33 | | Value | Negative Index |
34 | | ----| ----|
35 | |11|-5|
36 | |22|-4|
37 | |33|-3|
38 | |44|-2|
39 | |55|-1|
40 |
41 | List elements can be accessed using indices.
42 |
43 | ```python
44 | l = [11,22,33,44,55]
45 | print(l[0]) # first value.
46 | print(l[1]) # second value.
47 | print(l[-1]) # last value.
48 | print(l[-2]) # second last value.
49 | print(l[-100]) # index out of range error.
50 | ```
51 |
52 | List elements can be modified.
53 |
54 | ```python
55 | l[0] = 12 # will replace the value at the
56 | # index 0 to 12.
57 | ```
58 |
59 | List elements can be used just like any other variable.
60 |
61 | ```python
62 | l[0]*12 # multiplies value at l[0] by 12.
63 | ```
64 |
65 | ## List Methods.
66 |
67 | ### append
68 | The `append` function takes **one** argument and adds it to the end of the list.
69 |
70 | ```python
71 | >>> a = []
72 | >>> a.append(1)
73 | >>> a
74 | [1]
75 | >>> a.append("2")
76 | >>> a
77 | [1, '2']
78 | # here '2' was added at the end of the existing list.
79 | >>> a.append(1.11111)
80 | >>> a
81 | [1, '2', 1.11111]
82 | >>> a.append([1,2,3])
83 | >>> a
84 | [1, '2', 1.11111, [1, 2, 3]]
85 | # here, the entire list was inserted at the end of
86 | # the existing list.
87 | ```
88 |
89 | ### extend
90 |
91 | ```python
92 | >>> a
93 | [1, '2', 1.11111, [1, 2, 3]]
94 | >>> b = [1,2,3]
95 | >>> a.extend(b)
96 | >>> a
97 | [1, '2', 1.11111, [1, 2, 3], 1, 2, 3]
98 | # All elements of the list b were added individually
99 | # to the list a.
100 | ```
101 |
102 | ### pop
103 | pop deletes and returns one element. It takes one optional argument.
104 |
105 | * No argument is passed: Deletes and returns the last element.
106 |
107 | ```python
108 | >>> a
109 | [1, '2', 1.11111, [1, 2, 3], 1, 2, 3]
110 | >>> a.pop()
111 | 3
112 | >>> a
113 | [1, '2', 1.11111, [1, 2, 3], 1, 2]
114 | ```
115 | * Valid index is passed: Deletes and returns the value at that index.
116 |
117 | ```python
118 | >>> a
119 | [1, '2', 1.11111, [1, 2, 3], 1]
120 | >>> a.pop(0)
121 | 1
122 | >>> a
123 | ['2', 1.11111, [1, 2, 3], 1]
124 | ```
125 | ### copy
126 | `a.copy()` creates a new list with the values of list `a`.
127 |
128 | ```python
129 | >>> a = [1, 2, 3, 4, 5, 6]
130 | >>> b = a # a and b are pointing to same object.
131 | >>> a[1]=-111 # when we change a, b also changes.
132 | >>> a
133 | [1, -111, 3, 4, 5, 6]
134 | >>> b # b changed when a changed.
135 | [1, -111, 3, 4, 5, 6]
136 | >>> c = a.copy() # creates a new list object.
137 | # having the values of list a.
138 | >>> a
139 | [1, -111, 3, 4, 5, 6]
140 | >>> a[1]=999
141 | >>> a
142 | [1, 999, 3, 4, 5, 6]
143 | >>> c # c didn't change when a changed.
144 | [1, -111, 3, 4, 5, 6]
145 | >>> b # b changed when a changed.
146 | [1, 999, 3, 4, 5, 6]
147 | ```
148 | #### Other functions
149 | Learning a language requires self practice! If we explain each and every function, we will hinder your path of exploring the language, we encourage you to use the `help()` function to find out more about other functions which are allowed on Lists.
150 |
151 | ## Getting Help
152 |
153 | We need to understand how to get help in Python.
154 |
155 | * `help`: returns the documentation of the data type.
156 | * `dir`: returns all the methods valid for that data type.
157 |
158 | Example:
159 |
160 | ```python
161 | help(1) # help about integer class.
162 | help('') # help about strings.
163 | help(1.1) # help about float.
164 | help([]) # help about lists
165 | ```
166 |
167 | ### Output of `help`
168 |
169 | ```python
170 | >>> help('')
171 | Help on class str in module builtins:
172 |
173 | class str(object)
174 | | str(object='') -> str
175 | | str(bytes_or_buffer[, encoding[, errors]]) -> str
176 | |
177 | | Create a new string object from the given object. If encoding or
178 | | errors is specified, then the object must expose a data buffer
179 | | that will be decoded using the given encoding and error handler.
180 | | Otherwise, returns the result of object.__str__() (if defined)
181 | | or repr(object).
182 | ```
183 |
184 | ### Output of `dir`
185 |
186 | ```python
187 | >>> dir('')
188 | ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
189 | '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
190 | '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
191 | '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find',
192 | 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable',
193 | 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust',
194 | 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
195 | ```
196 |
197 | #### Slicing
198 |
199 | Slicing is an easy way to fetch sub parts of them. Lists, strings and tuples allow Slicing.
200 |
201 | The syntax of slicing is `l[start_index : end_index]`.
202 |
203 | ```
204 | l: the list
205 | start_index: Starting point with the element at this
206 | index included; defaults to 0 if left blank.
207 | end_index: Ending point, but this index is excluded;
208 | defaults to -1 if left blank.
209 | ```
210 |
211 | Slicing returns a new object (list or string or tuple) from the `start_index` to the `end_index` without including `end_index`.
212 |
213 | ```python
214 | >>> l = [0,1,2,3,4]
215 | >>> l[0:3] # from 0 till 2nd element
216 | # the element of index 3 is not returned
217 | [0, 1, 2]
218 | >>> l[1:3] # new list starting from 1 till 2nd element
219 | # 3rd element is not returned
220 | [1, 2]
221 | >>> l[-1:] # new list containing the last element
222 | [4]
223 | >>> l[0:-1] # new list from 0 excluding last element
224 | [0, 1, 2, 3]
225 | >>> l[0:-2]
226 | [0, 1, 2]
227 | >>> l[::-1] # returns a new list with values reversed
228 | [4, 3, 2, 1, 0]
229 | >>> for i in l:
230 | ... print(i)
231 | ...
232 | 0
233 | 1
234 | 2
235 | 3
236 | 4
237 | ```
238 |
239 | Slicing also works with strings and tuples. We invite you to try them out. Don't just read this book, execute code!
240 |
241 | ## Tuples
242 |
243 | Read the [docs](https://docs.python.org/3/library/stdtypes.html#tuple) | Watch the [video]()
244 |
245 | Tuples are read only lists. A tuple object, once created, doesn't allow us to add, delete or update an element. When we use the `dir` on a tuple object, we find that there are only two methods, `count` and `index`.
246 |
247 | ```python
248 | >>> a = (1,2,3,4)
249 | >>> type(a)
250 |
251 | >>> 1 in a
252 | True
253 | >>> a[0]
254 | 1
255 | >>> a[::-1]
256 | (4,3,2,1)
257 | >>> a[0:2]
258 | (1,2)
259 | ```
260 |
261 | ### List vs Tuple
262 | Lists are used when we are not sure how many values we'll be having.
263 |
264 | Tuples are used when there is a fixed number of values to deal with.
265 |
266 | ## Set
267 |
268 | Watch on [YouTube](https://www.youtube.com/watch?v=QmfDyjp0Z8E) | Read the [docs](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset)
269 |
270 | Sets are same as lists with the following limitations:
271 |
272 | 1. Duplicate entries are not allowed
273 | 1. Sets can only have basic data types as elements (lists/dictionary/set/tuple)
274 | 1. Sets do not allow indexing
275 |
276 | ```python
277 | >>> a = [1,2,3,4]
278 | >>> b = set(a)
279 | >>> b
280 | {1, 2, 3, 4}
281 | >>> type(b)
282 |
283 | >>> b[0] # sets do not allow this.
284 | TypeError: 'set' object does not support indexing
285 | ```
286 |
287 | When we try to create a set from a list which has a list element, it is an error (only basic elements int, float, string are allowed) :
288 |
289 | ```python
290 | a = [1,2,3,[2,3]]
291 | set(a)
292 | ## Throws an error.
293 | ```
294 | Sets allow various methods like add, copy, deepcopy, update, pop, remove.
295 |
296 | ```python
297 | >>> a = set() # creates a blank set
298 | >>> a.add("this")
299 | >>> a.add("that")
300 | >>> a.add("this and that")
301 | >>> a
302 | {'that', 'this and that', 'this'}
303 | >>> a.remove("this")
304 | >>> a
305 | {'that', 'this and that'}
306 | >>> a.pop()
307 | 'that'
308 | >>> a
309 | {'this and that'}
310 | >>> a.add("zebra")
311 | >>> a
312 | {'zebra', 'this and that'}
313 | >>> b = set([1,2,3,4,5])
314 | >>> b
315 | {1, 2, 3, 4, 5}
316 | >>> b = set([1,2,3,4,5])
317 | >>> c = b # c and b point to the **same** set object
318 | >>> c
319 | {1, 2, 3, 4, 5}
320 | >>> b
321 | {1, 2, 3, 4, 5}
322 | >>> c.add(12) # changing c changes b
323 | >>> b
324 | {1, 2, 3, 4, 5, 12}
325 | >>> c
326 | {1, 2, 3, 4, 5, 12}
327 | >>>
328 | >>> d = b.copy() # creates a COPY of b
329 | >>> d
330 | {1, 2, 3, 4, 5, 12}
331 | >>> b
332 | {1, 2, 3, 4, 5, 12}
333 | >>> b.add(1000) # changing b does NOT change d
334 | >>> b
335 | {1, 2, 3, 4, 5, 1000, 12}
336 | >>> d
337 | {1, 2, 3, 4, 5, 12}
338 | ```
339 |
340 | ## Dictionary
341 |
342 | Read the [docs](https://docs.python.org/3/library/stdtypes.html#dict) | Watch on [YouTube](https://www.youtube.com/watch?v=pQV3wbSMBRI)
343 |
344 | Dictionaries are key value pairs. Keys can only be hashable data types i.e. basic data types. There is no such restriction on the values.
345 |
346 | Lists are indexed starting from 0, it is done by the interpreter itself. Dictionaries allow custom indexes i.e. keys.
347 |
348 | > Note: the representation of both set and dictionary is by using curly braces, `{}`.
349 |
350 | ```python
351 | >>> a = dict() # creates an empty dictionary
352 | >>> a
353 | {}
354 | >>> a["IN"] = "India" # creates a new key value pair
355 | >>> a
356 | {'IN': 'India'}
357 | >>> a["US"] = "United States of America" # new key value pair
358 | >>> a
359 | {'IN': 'India', 'US': 'United States of America'}
360 | >>> a["ES"] = "Espanol"
361 | >>> a
362 | {'IN': 'India', 'US': 'United States of America', 'ES': 'Espanol'}
363 | >>> a["IN"] # returns the value of "IN" key.
364 | 'India'
365 | ```
366 |
367 | Dictionaries do not support slicing.
368 |
369 | `keys()` and `values()` are two functions which return all the keys and values of the dictionary object. Since we can't use `for i in ` syntax to loop over dictionaries, we have to do this
370 |
371 | ```python
372 | >>> a.keys()
373 | dict_keys(['IN', 'US', 'ES'])
374 | >>> a.values()
375 | dict_values(['India', 'United States of America', 'Espanol'])
376 | ```
377 |
378 | ```python
379 | >>> for i in a.keys():
380 | ... print(i, ":", a[i])
381 | ...
382 | IN : India
383 | US : United States of America
384 | ES : Espanol
385 | ```
386 |
387 | We also encourage you to try out everything we did in this chapter, again! (on strings too)
388 |
389 | Exercises:
390 |
391 | 1. Find the number of occurances of 1 in the list [1,2,1,2,1,2,3,4,1,2,3].
392 | 1. Find all the unique elements of a list. Input; a = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]. Output; [1, 2, 3, 4].
393 | 1. Solve the above problem using a dictionary.
394 | 1. Find the count of each element of a list except "\n". a = [1, 2, 2, 3] should return this output. 1 : 1,, 2 : 2, 3 : 1.
395 | 1. Create a random dictionary and print key : value pair in ascending order of keys. Input: a = {"IN":"India", "ES":"Español"}, output: "ES"":"Español", "IN":"India". You have to use `dir` to find out the necessary functions.
396 | 1. The same example as above, print in descending order.
397 | 1. Given two list, find their
398 | 1. common elements.
399 | 1. elements present in list a but not in b.
400 | 1. elements present in list b but not in a.
401 | hint: use sets.
402 | 1. Print a reverse of a list without using the `reverse` method.
403 |
404 | ##### Links
405 |
406 | |[Next](05-constructs.md) | [Previous](03-02-operators.md) | [Index](../SUMMARY.md)
407 | | ----| ----| ----|
408 |
--------------------------------------------------------------------------------
/manuscript/05-constructs.md:
--------------------------------------------------------------------------------
1 | # Constructs
2 |
3 | ### del
4 |
5 | `del` can be used to delete any variable, it de-allocates a variable. After you run `del a`, the variable `a` was deleted, so we can't access it.
6 |
7 | ```python
8 | >>> a
9 | ['2', 1.11111, [1, 2, 3], 1, 2, 3]
10 | >>> del a
11 | >>> a
12 | Traceback (most recent call last):
13 | File "", line 1, in
14 | a
15 | NameError: name 'a' is not defined
16 | ```
17 |
18 | ### Exercise:
19 |
20 | 1. Given that a = [1,2,3,4,[5,6,7]]
21 | 1. Delete the first value.
22 | 2. Delete the second value of the list present at index 4.
23 | 1. Delete the variable a.
24 | 1. Take an input value from the user and delete it (if it is present), print "value not present" if the value is not present in the list.
25 | 1. Given that a = {"IN":"India", "ES":"Espanol"}
26 | 1. Delete the key "IN".
27 | 1. Delete the key "ES"
28 | 1. Delete the variable a.
29 |
30 |
31 | ### if-else statment
32 |
33 | Read the [docs](https://docs.python.org/3/reference/compound_stmts.html#the-if-statement) | Watch [video 1](https://youtu.be/fbCsCFuj6zE)| Watch [video 2](https://youtu.be/YjUo6TQ2EzE)
34 |
35 | Let's say we work for a school and we are asked to write a program to print out if a student has passed or failed for a particular exam. `a` is the score that the student scored in a subject, `b` is the maximum marks for the subject. Passing percentage is 35.
36 |
37 | ```python
38 | a = 67
39 | b = 100
40 | percent = (a/b)*100 # calculating percentage marks.
41 |
42 | if percent < 35:
43 | # block executes if percent is less than 35.
44 | print("Failed.")
45 | else:
46 | # block executes if percent is greater than 35.
47 | print("Passed! Keep it up!")
48 | ```
49 | **Output:**
50 |
51 | ```
52 | Passed! Keep it up!
53 | ```
54 |
55 | ## Indentation
56 |
57 | Python uses spaces for indentation. Either spaces or tabs can be used for indentation, but not both. Usage of four spaces is recommended.
58 |
59 | ```python
60 | a = 67
61 | b = 100
62 | percent = (a/b)*100 # calculating percentage marks.
63 |
64 | if percent < 35:
65 | # block belongs to the if statement.
66 | print("Failed.")
67 | print("Please appear for exams again.")
68 | else:
69 | # block belongs to the else statement.
70 | print("Passed!")
71 | print("Study for the next exams now.")
72 | print("END")
73 | ```
74 |
75 | #### Scoping
76 |
77 | Each statement belongs to one or more "scopes", one direct scope and multiple indirect scopes.
78 |
79 | For visualization, let's draw `[]` around the spaces, so the code now looks like this:
80 |
81 | > Note: This is not valid Python code, `[]` is used just to show the indentation.
82 |
83 | ```
84 | if percent < 35: # global scope
85 | [ ]print("Failed.")
86 | [ ]print("Please appear for exams again.")
87 | else:
88 | [ ]print("Passed!")
89 | [ ]print("Study for the next exams now.")
90 | print("END") # global scope
91 | ```
92 |
93 | #### How to find scope?
94 | 1. After a construct which ends with a colon (if/for/while/try/except), calculate the number of spaces in the immediate next line. In this example, it is `four spaces`. The first `[]` block.
95 | 1. Every line below this line which has `four spaces` at the start until we get a line which **doesn't** have four spaces is in the if block.
96 |
97 | > Note: Having indentation **without** an if/for/while/elif block is a syntax error, for instance, you can't do the following:
98 |
99 | ```python
100 | if a > 1:
101 | print("hi")
102 | print("bye")
103 | print("hi")
104 | ```
105 |
106 | The error is because the interpreter isn't able to find out what block the statement belongs to.
107 |
108 | #### elif
109 |
110 | The `elif` block is special, it gets evaluated if the parent `if` block has been evaluated to False.
111 |
112 | In our school, we now want to print the grades of students.
113 |
114 | F: percentage < 35
115 | C: 35 < percentage <= 50
116 | B: 50 < percentage <= 70
117 | A: 70 < percentage <= 90
118 | A+ 90 < percentage
119 |
120 | > Note: `elif` and `else` can't exist without a corresponding `if` block. Only the `if` block can exist independently.
121 |
122 | ```python
123 | a = 67
124 | b = 100
125 | percent = (a/b)*100 # calculating percentage marks.
126 |
127 | if percent < 35:
128 | # block belongs to the if statement.
129 | print("F")
130 | elif percent <= 50:
131 | print("C")
132 | elif percent <= 70:
133 | print("B")
134 | elif percent <= 90:
135 | print("A")
136 | else:
137 | print("A+")
138 | ```
139 |
140 | **Output:**
141 | ```
142 | B
143 | ```
144 |
145 | #### Nesting
146 |
147 | We can have multiple if blocks inside an if block (same is true with for/while statements). This is called nesting. When we write nested if statements, then the same logic applies to indentation.
148 |
149 | This is an example of two level nesting:
150 |
151 | ```python
152 | if a > 1:
153 | if b < 1:
154 | print(" b is less than 1")
155 | print("a is greater than 1")
156 | print("This is not in either of the above blocks")
157 | ```
158 | Let's add `[]` to the code to understand scoping for nested blocks.
159 |
160 | Each `[ ]` can be considered as an indentation block, we can see that `if b < 1` has only one block, but this statement, `print(" b is less than 1")` has two blocks of spaces, the first one is to `if b < 1` which is the primary scope, the secondary scope is to `if a > 1`.
161 |
162 | > Note: This is not valid Python code, `[]` is used just to show the indentation.
163 |
164 | ```
165 | if a > 1:
166 | [ ]if b < 1:
167 | [ ][ ]print(" b is less than 1")
168 | [ ]print("a is greater than 1")
169 | print("This is not in either of the above blocks")
170 | ```
171 | ### Scoping for nested blocks
172 |
173 | Here, the statements which lie in the inner if statement lie in two blocks, the inner if statement's block and the outer if statement's block.
174 |
175 | ```python
176 | if True:
177 | # statements here are in the
178 | # scope of the if statement.
179 | print("Statement is true")
180 | if True:
181 | # statements here are in the inner if
182 | # but overall, lie in the scope of
183 | # the outer if.
184 | print("Another statement")
185 | else:
186 | # statements here are in the
187 | # scope of the else statement.
188 | print("Statement is false")
189 | if True:
190 | # statements here are in the inner if
191 | # but overall, lie in the scope of
192 | # the outer else.
193 | print("Another statement")
194 | ```
195 |
196 | ## Exercise
197 | 1. Take the name, age and score of the user as input. Print their percentage. If the percentage is less than 60, print F, if percentage is between 60 and 70 print B and if percentage is greater than 70 print A. Marks are out of 100.
198 | 1. Take a number from the user and print if it is even or odd.
199 | 1. Take two numbers from the user and print which number is largest.
200 | 1. Take two numbers from the user and print which number is smallest.
201 | 1. Take three numbers from the user and print largest and smallest number.
202 | 1. Take four numbers from the user and create a list.
203 | 1. Take four numbers from the user and create a set.
204 |
205 | ### for loop.
206 |
207 | Read the [docs](https://docs.python.org/3/reference/compound_stmts.html#the-for-statement)
208 |
209 | `for` statement is used to cycle over a list/set/tuple.
210 |
211 | ```python
212 | l = [1,2,3,4,5]
213 | for i in l:
214 | print(i)
215 | ```
216 | **Output:**
217 | ```
218 | 1
219 | 2
220 | 3
221 | 4
222 | 5
223 | ```
224 |
225 | **Explanation:**
226 |
227 | The program goes through five iterations
228 |
229 | Iteration 1: Value of i is 1; loop prints 1;
230 |
231 | Iteration 2: Value of i is 2; loop prints 2;
232 |
233 | Iteration 3: Value of i is 3; loop prints 3;
234 |
235 | Iteration 4: Value of i is 4; loop prints 4;
236 |
237 | Iteration 5: Value of i is 5; loop prints 5;
238 |
239 | In a `for` loop, we can perform other operations too, for the sake of simplicity, we just printed the value of the variable i.
240 |
241 | #### Another approach.
242 |
243 | ```
244 | for i in range(len(l)):
245 | print(l[i])
246 | ```
247 | **Output:**
248 | ```
249 | 1
250 | 2
251 | 3
252 | 4
253 | 5
254 | ```
255 |
256 | **Explanation:**
257 | `range(5)` returns a list [0,1,2,3,4].
258 |
259 | #### The Else Block
260 |
261 | `for` has an else block. It is strange at first glance, but it is quite helpful in certain cases, like finding if a number if prime or not.
262 |
263 | We will take a simple example where we want to find out if an element is present in a list or not.
264 |
265 | ```python
266 | l = [1,2,3,4,5]
267 | val = 99
268 |
269 | for i in l:
270 | if i == val:
271 | # for understanding break
272 | # check the below section.
273 | break
274 | else:
275 | print("Not present")
276 | ```
277 |
278 | **Output:**
279 | ```
280 | Not present
281 | ```
282 |
283 | **Explanation:**
284 | The loop is killed by using a `break`, if the loop does not get killed, then the value is not present in the list.
285 |
286 | ### Exercise:
287 |
288 | 1. Print all numbers till 100.
289 | 1. Print all numbers from 20 to 100.
290 | 1. Print all even numbers less than 100.
291 | 1. Print all odd numbers less than 100.
292 |
293 | #### break, continue, pass
294 |
295 | #### break
296 |
297 | Read the [docs](https://docs.python.org/3/reference/simple_stmts.html#break)
298 |
299 | The break statement kills the current loop. If we have nested loops, then we have to position the `break` properly to kill the correct loop.
300 |
301 | ```python
302 | for i in range(10):
303 | if i == 4:
304 | break
305 | print(i)
306 | ```
307 |
308 | The above block will print all the numbers until it hits 4. The moment it hits 4, the for loop will stop executing.
309 |
310 | #### continue
311 |
312 | Read the [docs](https://docs.python.org/3/reference/simple_stmts.html#continue)
313 |
314 | The continue statement takes the execution to the next iteration.
315 |
316 | ```python
317 | for i in range(100):
318 | if i == 4:
319 | continue
320 | print(i)
321 | ```
322 |
323 | The above block will print all numbers **except** 4. It continues to the next iteration.
324 |
325 | > Note: break and continue work with loops only, either `for` or `while`.
326 |
327 | ## Exercise:
328 | 1. Print all numbers from 0 till 10 except 4 and 5.
329 | 1. Print all numbers from 0 till 20 except those divisible by 3.
330 | 1. a = [1,2,3,4,5], take an integer as input from the user. Print all numbers which are less than the input number using break.
331 |
332 | #### pass
333 | Pass can be used as an empty placeholder in places where you don't have anything to add.
334 |
335 | ```python
336 | if a > 1:
337 | pass
338 | else:
339 | print("TODO")
340 | ```
341 |
342 | For instance, in the above if-else block, you really don't know what logic you are going to put, so you can either use `print("TODO")`, or use the pass statement. pass doesn't print anything. You can use pass in any loop.
343 |
344 |
345 | ### while loop.
346 |
347 | Read the [docs](https://docs.python.org/3/reference/compound_stmts.html#the-while-statement)
348 |
349 | `while` is used when you have to loop for a specific condition. If you don't have a condition, you can use `True` and that would result in an infinite loop.
350 |
351 | ```python
352 | i = 10
353 | while i >= 0:
354 | print(i)
355 | i = i - 1
356 | ```
357 |
358 | **Output:**
359 | ```
360 | 10
361 | 9
362 | 7
363 | 6
364 | 5
365 | 4
366 | 3
367 | 2
368 | 1
369 | 0
370 | ```
371 |
372 | **Explanation:**
373 | The `while` statement will loop on the condition, until the condition evaluates to `False`. The loop exits when the condition becomes False.
374 |
375 | > Note: The `while` statement also has an else block, we encourage you to play with it to understand it better.
376 |
377 | ### Exercise:
378 |
379 | 1. Print all numbers till 100 using while.
380 | 1. Print all numbers from 100 to 1 using while.
381 | 1. Print all even numbers less than 100 using while.
382 | 1. Print all odd numbers less than 100 using while.
383 | 1. For a list [1,2,3,4,5], write a program which checks if 6 is present in the list, using while.
384 | 1. Print all numbers from 0 to 10 except 4 and 5.
385 |
386 | #### try - except - finally
387 | Read the [docs](https://docs.python.org/3/reference/compound_stmts.html#the-try-statement)
388 |
389 | try-except is used for exception handling, we'll take a look at it in a later chapter.
390 |
391 | #### with
392 | > Note: requires the knowledge of file handling, you can come back to this chapter after reading the file handling chapter.
393 |
394 | Read the [docs](https://docs.python.org/3/reference/compound_stmts.html#the-with-statement)
395 |
396 | The with block was added in [PEP 343](https://www.python.org/dev/peps/pep-0343/). support of the [Resource Acquisition Is Initialization](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization) idiom commonly used in C++. It is intended to allow safe acquisition and release of operating system resources.
397 |
398 | Resources are created within a scope/block, resources are cleanly released whether the block exists normally or because of an exception.
399 |
400 | ```python
401 | with open('file.py') as ip, open('op.txt','w') as op:
402 | for line in ip.readlines():
403 | op.write(line)
404 | ```
405 | **Output:**
406 | ```
407 | 10
408 | 1
409 | 21
410 | 19
411 | 30
412 | 20
413 | ```
414 |
415 | Because of scoping, the `input_file` and `output_file` variables are only available within the with clause. This can result in some clean code, but it is upto you totally. I like to use try-except-finally.
416 |
417 | We encourage you to read more about the `range` function. Please **do not use the Internet**, use the `help` function. The faster you get familiar to using the documentation, the better programmer you become. In a world full of people Googling "how to create a string in Python", we really need to be self sufficient as to using the documentation that a language provides to differentiate from others. The mark of a great programmer isn't in how much things she can store in her memory, it is in the mastery of the tools she uses, documentation and the help command are among the tools.
418 |
419 | ##### Links
420 |
421 | |[Next](06-file-handling.md) | [Previous](04-list-set-dict.md) | [Index](../SUMMARY.md)
422 | | ----| ----| ----|
423 |
--------------------------------------------------------------------------------
/manuscript/06-file-handling.md:
--------------------------------------------------------------------------------
1 | # File handling
2 |
3 | Managing files is one of the most important features of any programming language. Python supports file handling via the io module's TextIOWrapper class, [docs](https://docs.python.org/3/library/io.html#io.TextIOWrapper)
4 |
5 | There are two basic modes in which we can manipulate files, Text and Binary.
6 |
7 | ## Writing files
8 | Write all even numbers till 100 to a file named "even.txt" and write all odd numbers to "odd.txt".
9 |
10 | ```python
11 | # open() opens a file and returns the address of the object
12 | # To be able to write to a file, the second
13 | # argument should be w.
14 | even_file = open("even.txt", "w")
15 | odd_file = open("odd.txt","w")
16 |
17 | # Opening file in write mode
18 | # Creates a file if it isn't present.
19 | # If a file is present, it gets overwritten and data is lost.
20 | # write mode doesn't allow the file to be read.
21 |
22 | for i in range(100):
23 | if i % 2 == 0:
24 | # All IO operations happen via strings.
25 | # so argument of write should be passed a string.
26 | even_file.write(str(i))
27 | even_file.write("\n")
28 | else:
29 | odd_file.write(str(i))
30 | odd_file.write("\n")
31 |
32 | # A file should always be closed
33 | # to free system resources.
34 | even_file.close()
35 | odd_file.close()
36 | ```
37 |
38 | **Why close a file?**
39 |
40 | When we write anything to a file, it gets written to a buffer and not directly to the underlying file. `flush()` method can be used to immediately write to the file. The `close()` method internally calls the `flush()` method, thus, in most of the cases, it is enough to just call the `close()` method.
41 |
42 | ## Reading files
43 |
44 | Read all the content from the file "even.txt" and print it to the terminal
45 |
46 | ```python
47 | # To be able to read a file, the second argument
48 | # should be r.
49 | input_file = open("even.txt", "r")
50 |
51 | # Files which are already existing can be read.
52 | # An exception is thrown if the file doesn't exist.
53 | # Writing or appending the file is not allowed.
54 |
55 | # readlines reads the complete file and returns a list
56 | # of all lines.
57 | lines = input_file.readlines()
58 | for line in lines:
59 | print(line)
60 | ```
61 |
62 | You will see that each number is printed on a different line. This is because of the new line ("\n") character which we wrote.
63 |
64 | ### The case of the new line.
65 | Whenever we read or write to a text file, we are responsible for the new line character "\n". When a file's content is "python\nis a good language.", it is displayed as
66 |
67 | ```
68 | python
69 | is a good language
70 | ```
71 |
72 | on any text editor, because the "\n" gets converted into an actual new line. But, the content of the text file is still
73 | "python\nis a good language."
74 |
75 | ```python
76 | file = open("file.txt", "w")
77 | for i in range(5):
78 | file.write(str(i))
79 | file.close()
80 |
81 | file = open("file.txt", "r")
82 | lines = file.readlines()
83 | print(lines)
84 | ```
85 |
86 | Output:
87 | ['01234']
88 |
89 | We can see that the file contains only one line. This is because, the `write` method doesn't add a new line character at the end of each operation. To understand it better, open this file in a text editor.
90 |
91 | Now, consider this block.
92 |
93 | ```python
94 | file = open("file.txt", "w")
95 | for i in range(5):
96 | file.write(str(i) + "\n")
97 | file.close()
98 |
99 | file = open("file.txt", "r")
100 | lines = file.readlines()
101 | print(lines)
102 | ```
103 |
104 | Output:
105 |
106 | ['0\n', '1\n', '2\n', '3\n', '4\n']
107 |
108 | By adding a "\n" in each write call, we ensure that the new number gets written to a new line, that's why, when we run the above code, we will get four lines in the text file. Verify this by opening the file in a text editor.
109 |
110 | While reading a file, we need to deal with the "\n" present at the end of each line. There is a shortcut to remove the "\n".
111 |
112 | ```python
113 | f = open("even.txt")
114 | lines = f.readlines()
115 | print(lines)
116 | lines = [line.strip() for line in lines] # list comprehension
117 | print(lines)
118 | ```
119 |
120 | #### List comprehension
121 | It is a shortcut of working with lists, to perform filter or some other operation on the entire list.
122 |
123 | lines = [line.strip() for line in lines]
124 |
125 | List comprehension replaces the following block:
126 |
127 | ```python
128 | for i in range(len(lines)):
129 | lines[i] = lines[i].strip()
130 | ```
131 | ##### Syntax
132 |
133 | [ condition for i in if ]
134 |
135 | List comprehension returns a new list based on the current list, the first argument `list.strip()` would be the elements of the list. The second argument is the for loop, the third argument is optional, you can have an `if` block there.
136 |
137 | ```python
138 | a = ["a.txt", "b.txt", "c.tct", "j.txt"]
139 | # list comprehension to remove *.tct
140 | b = [i for i in a if not a.endswith(".tct")]
141 | # write another list comprehension to remove all .tct files
142 | ```
143 |
144 | ## Examples:
145 |
146 | 1. Convert each element to upper case (works only when each element is a string).
147 | ```python
148 | a = ["a.txt", "b.txt", "c.tct", "j.txt"]
149 | b = [i.upper() for i in a]
150 | print(b)
151 | ```
152 |
153 | 1. Convert each element to lower case (works only when each element is a string).
154 | ```python
155 | a = ['A.TXT', 'B.TXT', 'C.TCT', 'J.TXT']
156 | b = [i.lower() for i in a]
157 | print(b)
158 | ```
159 |
160 | 1. Give all the values of list a which are greater than 3.
161 |
162 | ```python
163 | a = [1, 3, 4, 5, 5]
164 | b = [i for i in a if i > 3]
165 | print(b)
166 | ```
167 |
168 | 1. Give all the values of list a which are greater than 3.
169 | ```python
170 | a = ["Haskell", "Ruby", "Python"]
171 | b = [i for i in a if len(i) > 3]
172 | print(b)
173 | ```
174 |
175 | 1. Give all values in a which are even.
176 |
177 | ```python
178 | a = [1, 3, 4, 5, 5]
179 | b = [i for i in a if i % 2 == 0]
180 | print(b)
181 | ```
182 |
183 |
184 | ## Appending files
185 | Write even numbers from 100 to 200 in a file "even.txt" which already contains even numbers from 0 to 100.
186 |
187 | ```python
188 | # To append to a file, the second argument should be a.
189 | # if we open in write mode, we will lose the data present
190 | # in the file before we open it.
191 | file = open("even.txt", "a")
192 |
193 | # Does not overwrite the file like the write mode.
194 | # It will create a file if it isn't present.
195 | # Adds content to the end of the file.
196 | # Doesn't allow file to be read.
197 |
198 | for i in range(100, 200):
199 | if i % 2 == 0:
200 | file.write(str(i)+"\n")
201 |
202 | file.close()
203 | ```
204 |
205 | ### Binary Mode
206 |
207 | ```python
208 | f = open("file.txt", "rb")
209 | ```
210 |
211 | Python allows us to manipulate binary files, we have to club the modes, `b` stands for binary, along with `b`, we can use any of r/w/a.
212 |
213 | * Read a binary file: "rb".
214 | * Write a binary file: "wb".
215 |
216 | > Note: One essential part of working with files is removing the `\n` or adding it when it is required.
217 |
218 |
219 | ## Other methods
220 |
221 | 1. `read()`
222 | Takes an argument as number of bytes to be read.
223 |
224 | When you open a file for reading, the pointer is at the 0'th position. if you do `f.read(1)`, the pointer moves to 1. If you do `f.read(1)` again, the pointer would return the 2nd character of the file and not the first one.
225 |
226 | All the read functions returns characters based from the current pointer, you can know where the pointer is located currently by using `f.tell()`.
227 |
228 | > Note: This is a session for the Interpreter.
229 |
230 | ```python
231 | >>> f = open("lines.txt")
232 | >>> f.tell() # pointer is at 0th position
233 | 0
234 | >>> f.read(1) # returns the first character
235 | 'f'
236 | >>> f.tell() # pointer shifted to 1st character
237 | 1
238 | >>> f.read(20) # reads 20 characters after 1 ('\n' is considered as single character)
239 | 'irst line\n second li'
240 | >>> f.tell()
241 | 21
242 | >>> f.read(10000) # reads 17 char after 21
243 | 'ne \n third line \n'
244 | >>> f.tell() # pointer on 38
245 | 38
246 | >>> f.read(10) # read 10 more char
247 | ''
248 | >>> f.tell() # this is the last position!
249 | 38
250 | >>> f.seek(0) # pointer is now at start of file
251 | 0
252 | >>> f.read(1)
253 | 'f'
254 | ```
255 |
256 | In this example, you hit the end of the file, there are only 38 characters in it, "\n" also is a character. If you read beyond the max characters of a line, it will return you blank strings. but there might be cases in which you would want to start reading the file again from any other position.
257 |
258 | You can use `seek` function to reset the pointer at any position of your choice. Let's say that you want to re-read the file again
259 |
260 | ```python
261 | >>> f.seek(0)
262 | ```
263 |
264 | This will reset the pointer and you should be able to read it from the first character of the file!
265 |
266 | 2. `readline()`
267 | Returns the current line that the pointer is located.
268 |
269 | ```python
270 | >>> f.seek(0)
271 | 0
272 | >>> f.readline()
273 | 'first line\n'
274 | >>> f.readline()
275 | ' second line \n'
276 | >>> f.readline()
277 | ' third line \n'
278 | ```
279 |
280 | You can try doing `f.seek(0)` and reading the lines again, you'll get the same output as above.
281 |
282 | 3. `readlines()`
283 | Returns all the lines of the file as a list.
284 |
285 | If the pointer is present at the end of file, then it returns an empty list. In that case, do a `f.seek(0)` to reset the pointer.
286 |
287 | ```python
288 | >>> f.seek(13)
289 | 13
290 | >>> f.readlines()
291 | ['econd line \n', ' third line \n']
292 | >>> f.seek(0)
293 | 0
294 | >>> f.readlines()
295 | ['first line\n', ' second line \n', ' third line \n']
296 | ```
297 |
298 | 4. `write()`
299 | Writes the **string** argument which you pass on the pointer. We need to be careful of the pointer, otherwise writing to the file can be dangerous. You are responsible for adding the "\n" character if you want to a new line, by default it'll write at the position the pointer is currentl `f.tell()`.
300 |
301 | 5. `writelines()`
302 | If you want to write a list to a file, you'll use writelines. Even here you are responsible for adding \n wherever you feel necessary.
303 |
304 | ```python
305 | j = ["\nthis is something\n", "another line\n"]
306 | f.writelines(j)
307 | f.close()
308 | ```
309 |
310 | We encourage you to try out file IO on your own, please refer to help() for any details regarding file, do not search "how to open a file in Python" on the internet.
311 |
312 | ## Exercise
313 |
314 | 1. Take the user's name, age and height as input and write them to a file using this format. name,age,height.
315 | 1. Read a file "input.txt" and print all the lines which are present multiple times. Please create the input.txt file in such a way that it has many lines and few of them are present multiple times.
316 | 1. Read a file "input.txt" and print how many times each line is present.
317 | 1. There are two files, "file1.txt" and "file2.txt"
318 | 1. swap the content of both files.
319 | 1. append the content of file1.txt to file2.txt.
320 | 1. append content of file2.txt to file1.txt.
321 | 1. take unique content of both files and write them to file3.txt
322 | 1. Use any file created above. Take a positive number as input from the user and read those many characters from the text file.
323 | 1. Prepare a csv file like this: first field = name, second onwards marks/100.
324 |
325 | ```
326 | tom,10,10,10
327 | tim,20,20,20
328 | ```
329 |
330 | 1. Print the name of the student with highest marks.
331 | 1. Print the name of the student with highest marks in upper case.
332 | 1. Print the highest score.
333 | 1. calculate the total score of each student, add the total at the end of the line and write everything to result.csv
334 |
335 | sample output:
336 |
337 | ```
338 | tom,10,10,10,30
339 | tim,20,20,20,60
340 | ```
341 |
342 | 1. Read the result.csv file and create a new file named result.txt like the following sample output.
343 |
344 | ```
345 | tom-10-10-10-30
346 | tim-20-20-20-60
347 | ```
348 | 1. read the result.txt file. Print every other character from the file.
349 |
350 |
351 | ##### Links
352 |
353 | |[Next](08-exception.md) | [Previous](05-constructs.md) | [Index](../SUMMARY.md)
354 | | ----| ----| ----|
355 |
--------------------------------------------------------------------------------
/manuscript/08-exception.md:
--------------------------------------------------------------------------------
1 | # Exception handling
2 |
3 | When something goes wrong, Python throws an an exception object. `Exception` is a class from which other exceptions are derived. The name of the child classes usually end with Error like FileNotFoundError.
4 |
5 | Read the [docs](https://docs.python.org/3/tutorial/errors.html#errors-and-exceptions)
6 |
7 | #### file: exception.py
8 | ```python
9 | i = 0
10 | j = 100/i
11 | print("This is the print statement")
12 | ```
13 |
14 | This code won't run, it would throw the ZeroDivisionError exception.
15 |
16 | The problem with exceptions is that your program is killed the moment it throws an exception. When writing large scale software in Python, this becomes an issue. This is where exception handling comes into picture. We want our programs to be resilient about errors that might happen during the runtime and we do not want our code to exit for any such reasons.
17 |
18 | #### file: exception2.py
19 |
20 | ```python
21 | i = 0
22 | try:
23 | j = 100/i
24 | except:
25 | print("Can't divide by 0!!")
26 | ```
27 |
28 | When you run this program, you'll see that it doesn't kill the program.
29 |
30 | A try catch block is to be used for lines which we suspect that something might go wrong, for instance if you are trying to open a file, there are many things which could go wrong, for instance, the disk space would go full, the file might not exist or a million other things, thus, we wrap the `open` function call in a try catch block.
31 |
32 | The `try` block contains all the lines where we suspect that something might go wrong, the `except` block is where the damage control lines are present. What we do for handling exceptions is upto us, we can just print on the terminal or we can send emails to the respective teams, or just log that there was an exception.
33 |
34 | ```python
35 | i = 0
36 | try:
37 | j = 100/i
38 | except ZeroDivisionError as e:
39 | print(e)
40 | except Exception as e:
41 | print(e)
42 | finally:
43 | print("this block always gets executed")
44 | ```
45 |
46 | The try-catch block allows you to handle multiple exceptions, they must be in the reverse order of generality. For instance, if you want to handle every kind of exception, just use ` except Exception`, the smallest exception statement should be at the top.
47 |
48 | #### Finally
49 |
50 | The finally block gets executed every time a try block gets executed. You can put the statements in this block which you want to be executed every time.
51 |
52 | You'd be doing this when you do handle errors for file handling programs.
53 |
54 | ```python
55 | try:
56 | f = open("lines.txt", "r")
57 | except Exception as e:
58 | print(e)
59 | ```
60 |
61 | Of course, you can pick up something other than the Exception class. If you want to handle some specific scenario like FileNotFoundError, use it instead of the Exception as e class. When you use `Exception as e`, you get the exception thrown by the code into an object `e`, you can print the object or write it to a file. If you don't care for that, just use `except Exception:`, skip the `as e`.
62 |
63 | ##### Links
64 |
65 | |[Next](09-functions.md) | [Previous](07-examples.md) | [Index](../SUMMARY.md)
66 | | ----| ----| ----|
67 |
--------------------------------------------------------------------------------
/manuscript/09-functions.md:
--------------------------------------------------------------------------------
1 | # Functions
2 |
3 | Functions are used to save code duplication. When we want a block of code duplicated across multiple locations, rather than physically copy pasting the code, it is better to declare a function and use it wherever we require it.By doing this, we write easy to edit code, because when our logic changes, we have to make changes only to the function definition and not everywhere the block is present.
4 |
5 | ###### file: func.py
6 |
7 | The following is the typical function definition on Python, def is the keyword. 'function\_name' is the name to be given to the function.
8 |
9 | Functions support zero or more arguments.
10 |
11 | ```python
12 | def function_name(argument1, argument2):
13 |
14 | ```
15 |
16 | Let's write a simple program to print the square of a number passed to it as an argument.
17 |
18 | ### Invoking functions.
19 |
20 | ```python
21 | def square(number1):
22 | print(number1**2)
23 | ```
24 |
25 | Save the file and run it.
26 |
27 | You will notice that the program didn't give any output, and that is because we just defined a function. When the interpreter comes across the def block, it will create a function of that name, taking some arguments and performing some action.
28 |
29 | It will not execute the function, if we want the function to be used, we need to invoke it.
30 |
31 | Add `square(2)` to the end of the above file. Save and run the program again. This time, you'll see the output. This is called function invocation.
32 |
33 | Here, 2 is an argument which is stored in number1 during the function invocation. Just because an argument is defined doesn't mean that we have to use it, we can ignore it altogether if we want.
34 |
35 | ### Default arguments
36 |
37 | Now that we wrote the square function, we want to generalize it to calculate power. This function will take two arguments, number and the power, and return number \*\* exponential.
38 |
39 | ###### file: defaultargs.py
40 |
41 | ```python
42 | def power(number, exp=2):
43 | print(number ** exp)
44 |
45 | power(2, 3) # value of exp is 3.
46 | power(2) # since no value of exp
47 | # is given, defaults to 2.
48 | ```
49 |
50 | Some or all arguments in Python can be optional. When an argument is optional, the default value of the argument is used.
51 |
52 | The rule with default arguments is that they need to be at the right most side of the argument listing, after all the mandatory arguments.
53 |
54 | The following block of code will result in a SyntaxError.
55 | ```python
56 | def do(var1=2,var2):
57 | print("hi")
58 |
59 | do(1)
60 | ```
61 |
62 | ## Return
63 | In the above examples, we saw function which prints the output. A function can also return the its output to the caller. This is helpful when processing data which we do not want to print.
64 |
65 | There is no restriction on the number of values that can be returned. Values are returned using the return statement and it is not a part of the function signature, a return statement should be directly added in the function definition.
66 |
67 | ```python
68 | def add(name, mode):
69 | return name+mode, name-mode
70 |
71 | one, two = add('this', 'that')
72 | print(one, two)
73 | ```
74 |
75 | Here, we have a function which returns two values. The two values are then printed after the function call.
76 |
77 | ##### Links
78 |
79 | |[Next](10-task.md) | [Previous](08-exception.md) | [Index](../SUMMARY.md)
80 | | ----| ----| ----|
81 |
--------------------------------------------------------------------------------
/manuscript/10-task.md:
--------------------------------------------------------------------------------
1 | # Building a todo list manager
2 |
3 | From this chapter on, we will start building an application. The end goal is going to write a command line todo list manager.
4 |
5 | The functionality is going to be something like this:
6 |
7 | ```bash
8 | $ python tasks.py add "title of the task" "content of the task"
9 | new task added
10 |
11 | $ python task.py remove "title of the task"
12 | task deleted
13 |
14 | $ python task.py list
15 | task_one content_of_1
16 | task_two content_of_2
17 | ```
18 |
19 | The software design phase is the most critical phase of software development, writing software is a cakewalk when the design is done properly.
20 |
21 | Before we can write the code, we have to:
22 |
23 | 1. Identify the input source.
24 | Our input source will be command line arguments.
25 | 1. Define the functionality of the program.
26 | Program will support adding/removing/listing todo items.
27 | 1. Identify where to store data.
28 | Program will store content in a flat file.
29 | 1. Identify what will be the output.
30 | Program will print data on the terminal.
31 |
32 | ## Input
33 |
34 | The user is going to give input in the command line arguments.
35 |
36 | The 'sys' package has the command line arguments stored into a variable called 'argv'.
37 |
38 | ###### file: tasks1.py
39 |
40 | ```python
41 | import sys
42 | print(sys.argv)
43 | ```
44 |
45 | Try running the code, you will see something like this
46 |
47 | ```
48 | ch10 $ python3 tasks.py
49 | ['tasks.py']
50 |
51 | ch10 $ python3 tasks.py "title" "content"
52 | ['tasks.py', 'title', 'content']
53 | ```
54 |
55 | For the interpreter, tasks.py, title and content are all command line arguments, this is what you see as the output of the above script.
56 |
57 | ## Output
58 |
59 | The output of the program is going to be on the command line.
60 |
61 | ## Formatting output
62 |
63 | #### file: tasks2.py
64 |
65 | ```python
66 | import sys
67 | for i, item in enumerate(sys.argv):
68 | print("{0} {1}".format(i, item))
69 | ```
70 |
71 | Enumerate takes a sequence and returns (index,value) for each value.
72 |
73 | ## Formatting.
74 | Starting from Python3.6, we can do this:
75 |
76 | ```python
77 | print(f"{i} {sys.argv[i]}")
78 | ```
79 | Where, `i` and `sys.argv[i]` are variables. Read the [docs](https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals)
80 |
81 | Try running tasks2.py with various command line arguments.
82 |
83 | ch10 $ python tasks2.py
84 | 0 tasks2.py
85 |
86 | We didn't give any parameter, since we know that the 0'th argument is going to be the file name itself, there are no suprises here.
87 |
88 | ch10 $ python tasks2.py title content
89 | 0 tasks2.py
90 | 1 title
91 | 2 content
92 |
93 | We passed title and content, and the index 1 is title, index 2 is content.
94 |
95 | ch10 $ python tasks2.py add title content
96 | 0 tasks2.py
97 | 1 add
98 | 2 title
99 | 3 content
100 |
101 | We passed "add title content" as the command line argument, and we get the expected output.
102 |
103 | ## Adding commands
104 |
105 | ##### file: tasks3.py
106 |
107 | ```python
108 | import sys
109 | args = sys.argv
110 |
111 | command = args[1]
112 |
113 | if command not in ("add","remove","list"):
114 | print("Invalid command, Use add/remove/list")
115 |
116 | if command == "add":
117 | print("adding")
118 | elif command == "remove":
119 | print("removing")
120 | elif command == "list":
121 | print("listing")
122 | else:
123 | print("invalid command!")
124 | ```
125 |
126 | You'll get this output when you run the code, this is an `exception`.
127 |
128 | ch10 $ python3 tasks3.py
129 | Traceback (most recent call last):
130 | File "tasks3.py", line 5, in
131 | command = args[1]
132 | IndexError: list index out of range
133 |
134 | What went wrong?
135 |
136 | We encourage you to try to figure out what went wrong, before moving ahead.
137 |
138 | ## Handling errors
139 |
140 | In the earlier file, we tried to access an list index which didn't exist. This raised an exception, we saw in the chapter about exceptions that a try-catch block is used to handle exceptions.
141 |
142 | Update the `command = args[1]` line in the file to this block:
143 | ```python
144 | try:
145 | command = args[1]
146 | except IndexError:
147 | print("Invalid arguments!")
148 | sys.exit(1)
149 | ```
150 |
151 | ### Exit
152 | `exit` kills the program execution with the ID of what we pass in as an argument, 0 is successful exit, anything greater than 0 is unsuccessful exit
153 |
154 | We catch IndexError exception. If there is an IndexError exception that means that the user has not given the appropriate arguments.
155 |
156 | Save and run the file. The output should be this:
157 |
158 | ch10 $ python tasks3.py
159 | Invalid arguments!
160 |
161 | We have handled the scenario where the user gives less input than what is required. Now let's move ahead and type an invalid command.
162 |
163 | ch10 $ python tasks3.py random
164 | Invalid command
165 | Use add/remove/list
166 | invalid command!
167 |
168 | We can see that the "invalid command" message is being repeated twice, we have to do something about that.
169 |
170 | We add another exit call after printing Invalid command. The reason being there is no need to go any further when we have established that the user has given us the invalid command.
171 |
172 | ```python
173 | if command not in ("add","remove","list"):
174 | print("Invalid command\n Use add/remove/list")
175 | sys.exit(1)
176 | ```
177 |
178 | ch10 $ python tasks3.py random
179 | Invalid command
180 | Use add/remove/list
181 |
182 | Now, let's test the `list` command.
183 |
184 | ch10 $ python tasks3.py list
185 | listing
186 |
187 | ## Storing user data
188 |
189 | Now that we have finished getting started with our menu driven program, let's go ahead and create a list. We need a variable to store the task list. When the program would be used the additions and deletions would be done on this list object, which would be written to the file when the output is required.
190 |
191 | Add this line after `args = sys.argv`
192 |
193 | ```python
194 | tasks = []
195 | ```
196 |
197 | This will create a variable by the name `tasks` which is visible in this file to all functions.
198 |
199 | In the `list` block, we want to now print the values stored inside `tasks` variable. If the values aren't present, we should print "No tasks present", if there are tasks, then we should print the elements inside `tasks`.
200 |
201 | We have to use the `len()` function to check if there is nothing in the variable.
202 |
203 | Update this block.
204 |
205 | ## Listing tasks
206 |
207 | ```python
208 | # This is a snippet
209 | # can't have elif without parent if
210 | elif command == "list":
211 | if len(tasks) == 0:
212 | print("there are no tasks!")
213 | else:
214 | for task in tasks:
215 | print(task)
216 | ```
217 |
218 |
219 | We now simulate data, before we let the user have the ability to add a task, we will populate the task variable by ourselves.
220 |
221 | For simplicity, we choose this format, the title and content would be concatenated by a | character.
222 |
223 | update the `tasks = []` to this line, `tasks = ["title|content"]`.
224 |
225 | And the else block of len(tasks) to this
226 |
227 | ```python
228 | for task in tasks:
229 | title, content = task.split('|')
230 | print("{0} {1}".format(title, content))
231 | ```
232 |
233 | ## Adding a task
234 |
235 | We will now work on adding a new task. The input would be taken from the command line argument.
236 |
237 | ```python
238 | if command == "add":
239 | print("adding")
240 | ```
241 |
242 | This block is changed to:
243 |
244 | ```python
245 | if command == "add":
246 | title = args[2]
247 | content = args[3]
248 | task = title + content
249 | tasks.append(task)
250 | ```
251 |
252 | But changing this does nothing, this is because the `tasks` variable is stored during the runtime. It gets reset to the default variable when the program quits. We need to add file handling feature to store the task list.
253 |
254 | Replace the `tasks` line to this to store an empty variable.
255 |
256 | ```python
257 | tasks = []
258 | ```
259 |
260 | The if-else block should look like this:
261 |
262 | ```python
263 | if command == "add":
264 | title = args[2]
265 | content = args[3]
266 | task = title + content
267 | file = open("tasks.txt", "a")
268 | file.write(task+"\n")
269 | file.close()
270 | elif command == "remove":
271 | print("removing")
272 | elif command == "list":
273 | file = open("tasks.txt", "r")
274 | tasks = file.readlines()
275 | if len(tasks) == 0:
276 | print("there are no tasks!")
277 | else:
278 | for task in tasks:
279 | title, content = task.split('|')
280 | print("{0} {1}".format(title, content))
281 | file.close()
282 | ```
283 |
284 | ## Our first bug!
285 |
286 | If you run this file, you'll get an IOError saying that tasks.txt doesn't exist. This is because we have not handled this scenario in the `open` function. We need to wrap that in a try-except block.
287 |
288 | ch10 $ python tasks3.py list
289 | Traceback (most recent call last):
290 | File "tasks3.py", line 28, in
291 | file = open("tasks.txt", "r")
292 | IOError: [Errno 2] No such file or directory: 'tasks.txt'
293 |
294 | In the elif block of list, we make the following modifications:
295 |
296 | ```python
297 | try:
298 | file = open("tasks.txt", "r")
299 | except IOError as e:
300 | print(str(e))
301 | sys.exit(1)
302 | tasks = file.readlines()
303 | ```
304 |
305 | Now when we run the code,
306 |
307 | ch10 $ python tasks3.py list
308 | [Errno 2] No such file or directory: 'tasks.txt'
309 |
310 | This is a graceful handling of the scenario where we aren't able to access the file due to an I/O (Input/Output) operation error.
311 |
312 | ch10 $ python tasks3.py add "new task" "new content"
313 |
314 | Now, let's list the tasks.
315 |
316 | ch10 $ python tasks3.py list
317 | Traceback (most recent call last):
318 | File "tasks3.py", line 38, in
319 | title, content = task.split('|')
320 | ValueError: need more than 1 value to unpack
321 |
322 | Now, we run the add command and try to list the values. We get an error, we can't add a try-except block to everything, so it is necessary to figure out what the issue is. Here, when we do `cat tasks.txt`, we come to know that the content of the file is this.
323 |
324 | ch10 $ cat tasks.txt
325 | new tasknew content
326 |
327 | We don't have a | character between the title and content! We did a mistake when we concatenated title and content. Remove the file by doing `rm tasks.txt`, or, delete the file manually if you are on windows.
328 |
329 | Instead of `task = title + content`, we need this, `task = title + "|" + content`.
330 |
331 | This is the output now
332 |
333 | ch10 $ python tasks3.py add "new title" "new content"
334 | ch10 $ python tasks3.py list
335 | new title new content
336 |
337 | This is great! We now are able to add and list the tasks.
338 |
339 | #### Note:
340 | When giving input over the command line, if you want to give multi word input, please enclose them in either single or double quote. For instance, we gave the input "new title", because our title contained a space. If we had given tasks2.py add new title, "new" would be considered the title because space is the delimiting character for any command line input, hence the "new title" enclosed in quotes.
341 |
342 | ch10 $ python tasks3.py add "Finish Python book" "Working on 10'th chapter"
343 | ch10 $ python tasks3.py list
344 | new title new content
345 |
346 | Finish Python book Working on 10'th chapter
347 |
348 | You can see that the output of the list command isn't particularly good, so let's use the advanced features of the print function for this.
349 |
350 | Replace the else block of `if len(tasks)==0` by this.
351 |
352 | ```python
353 | print("|-----{0}----{1}----|".format("title", "content"))
354 | tasks = [task.strip() for task in tasks]
355 | for task in tasks:
356 | title, content = task.split('|')
357 | print("|-{0}----{1}-|".format(title, content))
358 | ```
359 |
360 | Format specifiers enable us to control the layout of the print, we encourage you to try various things out.
361 |
362 | The final code should look like this.
363 |
364 | ```python
365 | import sys
366 |
367 | args = sys.argv
368 |
369 | tasks = []
370 |
371 | try:
372 | command = args[1]
373 | except IndexError:
374 | print("Invalid arguments!")
375 | sys.exit(1)
376 |
377 | if command not in ("add","remove","list"):
378 | print("Invalid command\n Use add/remove/list")
379 | sys.exit(1)
380 |
381 |
382 | if command == "add":
383 | title = args[2]
384 | content = args[3]
385 | task = title + "|" + content
386 | file = open("tasks.txt", "a")
387 | file.write(task+"\n")
388 | file.close()
389 | elif command == "remove":
390 | print("removing")
391 | elif command == "list":
392 | try:
393 | file = open("tasks.txt", "r")
394 | except IOError as e:
395 | print(str(e))
396 | sys.exit(1)
397 | tasks = file.readlines()
398 | if len(tasks) == 0:
399 | print("there are no tasks!")
400 | else:
401 | print("|-----{0}----{1}----|".format("title", "content"))
402 | tasks = [task.strip() for task in tasks]
403 | for task in tasks:
404 | title, content = task.split('|')
405 | print("|-{0}----{1}-|".format(title, content))
406 | file.close()
407 | else:
408 | print("invalid command!")
409 | ```
410 |
411 | ## Removing tasks
412 |
413 | To remove tasks, we have to change the way we structure our data. We either can accept deletion on the basis of the title of the task, or we can render index for each task, since deletion from the title is not exactly scalable (two tasks can have the same title but different content), we choose to modify our program to show index for each task, that way, the user can just give the index of the task which they want to delete.
414 |
415 | #### file: tasks4.py
416 |
417 | We first need to modify the way we represent our tasks to the user, instead of showing just the title and content, we will show the index too. For this, we need to make the following changes.
418 |
419 | We can't loop like `for task in tasks`, we need to loop using `range`, `for i in range(len(tasks))` is the way to go. The only difference is that we have to then fetch the task as `tasks[i]` rather than just `task`, because now, there is no such variable as `task`.
420 |
421 | ```python
422 | ## Snippet, else can't exist without parent if
423 | else:
424 | print("|-{0}----{1}----{2}----|"%("index", "title", "content"))
425 | tasks = [task.strip() for task in tasks]
426 | for i in range(len(tasks)):
427 | title, content = tasks[i].split('|')
428 | print("|-{0}--{1}----{2}-|" %(i, title, content))
429 | ```
430 |
431 | In the actual delete block, we will use the del keyword which will simplify our task greatly.
432 |
433 | ```python
434 | # Snippet
435 | elif command == "remove":
436 | task_id = args[2]
437 | del tasks[task_id]
438 | ```
439 |
440 | ch10 python3 tasks4.py remove 0
441 | Traceback (most recent call last):
442 | File "tasks4.py", line 27, in
443 | del tasks[task_id]
444 | TypeError: list indices must be integers or slices, not str
445 |
446 | ###### Note:
447 | We are not validating if the user has given appropriate input, let's say the user gives `python tasks4.py remove` instead of `python tasks4.py remove 0`, then our program should complain about an error, the same is the case with add, if the user doesn't give both title and content, that's an error and it should be handled appropriately.
448 |
449 | We can see that "list indices must be integers" is the error we got for the del statement, the reason for that is that as we said, all shell operations are string based, so when the user gave us the input 0, it was '0', thus a string. We will typecast the `task_id` variable to an integer. Change it to this below statement.
450 |
451 | We also need to read the file, for each instance, we read the file or appended it as required.
452 |
453 | ```python
454 | del tasks[int(task_id)]
455 | ```
456 |
457 | We also need to write the updated `tasks` variable to our file, we add a "\n" to each element using the list comprehension mechanism.
458 |
459 | Now try running the code.
460 | ```python
461 | ## snippet
462 | elif command == "remove":
463 | try:
464 | file = open("tasks.txt", "r")
465 | except IOError as e:
466 | print(str(e))
467 | sys.exit(1)
468 |
469 | file.close()
470 | tasks = file.readlines()
471 | tasks = [task.strip() for task in tasks]
472 | task_id = args[2]
473 | del tasks[int(task_id)]
474 |
475 | file = open("tasks.txt", "w")
476 | tasks = [task + "\n" for task in tasks]
477 | file.writelines(tasks)
478 |
479 | ```
480 |
481 | Output:
482 |
483 | ch10 $ python3 tasks4.py remove 0
484 | ch10 $ python3 tasks4.py remove 1
485 |
486 | ###### Note:
487 | We do not print confirmation like "task deleted", "task added", but you can add them if you want.
488 |
489 | We have a fully working todo list manager as of now, what we need to do, is to reduce the redundancy. That'll be undertaken in the next chapter.
490 |
491 | ## Homework
492 | Translate this todo list app to use sqlite3 database which comes inbuilt with Python. Please do not use the Internet, use the sqlite3 documentation.
493 |
494 | ##### Links
495 |
496 | |[Next](11-function-tasks.md) | [Previous](09-functions.md) | [Index](../SUMMARY.md)
497 | | ----| ----| ----|
498 |
--------------------------------------------------------------------------------
/manuscript/11-function-tasks.md:
--------------------------------------------------------------------------------
1 | # Adding functions
2 |
3 | > Note: Please see the accompanying code. https://github.com/thewhitetulip/code-build-app-with-python-antitextbook
4 |
5 | In the earlier chapter we saw how to take input, delete a task, but if you see the code, `task4.py`, there is a lot of redundant code, what we need to do is write functions to save repeated code.
6 |
7 | We first start by defining the `main` function. There is no special significance to the main function, just that we chose to call it as `main`, we can very well choose to call it 'somerandomfunctionasfasdf'.
8 |
9 | We push everything _except_ the import statement into the main function.
10 |
11 | If you try to run the file at this point, there would not be any output, the reason for that is that you have declared a function but not **called** it. The interpreter runs the script and it creates a function named "main" and it does nothing. If you want to **run** the main, you have to call it. At the bottom, add `main()` and then try running the file, this time, it'll give _some_ output.
12 |
13 | Now, we create three functions, `add_task`, `remove_task`, and `list_task`. These three would do the respective functions.
14 |
15 | The logic of our program should be split between modules. There should be one "controller" module which handles the IO and a supporting library which does something with the data, in that way, we can enable different input sources for the same app. Currently, the input source, which is the command line arguments is deeply coupled with our todo list manager, so if tomorrow, we want to take input from some other source, we have to rewrite the complete application.
16 |
17 | We manage the functions in this way:
18 |
19 | main: handles the IO
20 |
21 | add_task(title,content): adds a new task with title and content
22 |
23 | list_task(): lists the tasks
24 |
25 | remove_task(index): deletes the task of index.
26 |
27 | By doing this, the main if-else ladder looks like this
28 |
29 | ```python
30 | if command == "add":
31 | title = args[2]
32 | content = args[3]
33 | add_task(title, content)
34 | elif command == "remove":
35 | task_id = args[2]
36 | remove_task(task_id)
37 | elif command == "list":
38 | list_task()
39 | else:
40 | print("invalid command!")
41 | ```
42 |
43 | Now, if we change the input from command line to say FTP, all we have to do is change the main function, write the FTP input function and call add_task, with the newly fetched title and content. Modularity is really important in programming.
44 |
45 | We have no need of declaring the `tasks` variable in the main function, so we remove it.
46 |
47 | We also do not want to write "add" every time we refer to the add command, so we define three variables.
48 |
49 | ADD,REMOVE,LIST = "add","remove","list"
50 |
51 | So, the next time we want to refer to "add", we will refer to ADD.
52 |
53 | This block also changes.
54 |
55 | ```python
56 | if command not in (ADD,REMOVE,LIST):
57 | print("Invalid command\n Use {0}/{1}/{2}".format(ADD,REMOVE,LIST))
58 | sys.exit(1)
59 | ```
60 |
61 | We now try and run the code, and it works!
62 |
63 | ch10 $ python3 tasks4.py
64 | Invalid arguments!
65 | ch10 $ python3 tasks4.py list
66 | |-index----title----content----|
67 | |-0--new title----new content-|
68 | |-1--Finish Python book----Working on 10'th chapter-|
69 |
70 | The code looks cleaner than tasks4.py, but there is work to do! We can create a module for these three functions and reuse the file object instead of redefining the object in each function.
71 |
72 | A parting glance at the design of the functions. Each function should do _one_ thing and do it well. That way, our program is split into multiple functions which do one thing well, just like the UNIX philosophy.
73 |
74 | ##### Links
75 |
76 | |[Next](12-modules-tasks.md) | [Previous](10-task.md) | [Index](../SUMMARY.md)
77 | | ----| ----| ----|
78 |
--------------------------------------------------------------------------------
/manuscript/12-modules-tasks.md:
--------------------------------------------------------------------------------
1 | # Using modules
2 |
3 | > Note: Please see the accompanying code. https://github.com/thewhitetulip/code-build-app-with-python-antitextbook
4 |
5 | In the last chapter, we left off by creating three functions for our core functionality. In this chapter, we'd split the functions into two packages,
6 |
7 | 1. the main package
8 | 1. the todo package (which we'll create)
9 |
10 | The `todo` package is going to contain everything related to our todo manager and the main package is just going to be the executable program.
11 |
12 | The first thing we do, is create a `main.py` file, and cut paste our main function inside it and remove the invocation at the bottom of the `tasks.py` file.
13 |
14 | So now our code is split into two files, in Python3 a file can be imported as a package directly, it should just be present in the same directory.
15 |
16 | import tasks as t
17 |
18 | By doing this, we can access all the members of the `tasks.py` file by appending 't.', like `t.list_task()`.
19 |
20 | Replace the three functions according to this rule. If we had not given the alias t to the library, as is the keyword used to give alias, then we'd have to write `tasks.list_task()`, but since we are lazy, we prefer to give it an alias to call it like `t.list_task()`.
21 |
22 | Modules are one of the most important aspects of Python. When we import a module, the interpreter **executes** the file which points to module.py (if we import a module named module).
23 |
24 | This is the way any module is imported:
25 |
26 | 1. The interpreter first goes to the stdlib folder and tries to find the .py file
27 | 1. If found, it executes it
28 | 1. If not found, it looks in the current directory
29 | 1. If found, it executes it
30 | 1. If not found, it complains as ModuleNotFoundError: No module named ""
31 |
32 | Special care needs to be taken so that we don't create a file with the same file name as a stdlib package, the humans reading the code would surely get confused, even if Python won't!
33 |
34 | As an example, try creating a file `sys.py` in the current folder. Add one line to that file, `print("something")`. Add an import statement `import sys` and later run `python3 tasks.py`, you'll see that it doesn't print "something", it refers to the stdlib package called 'sys'.
35 |
36 | ## Make Code Great Again!
37 |
38 | There are many ways that we can make our code great again (ahem), there are lots of features we can add, a partial list can be as below:
39 |
40 | 1. add a "task status" field
41 | 1. change the formatting to show a checkbox like
42 |
43 | [ ] Do this and that (for incomplete)
44 |
45 | [x] Do this and that (for complete)
46 | 1. ability to search
47 | 1. ability to set deadline
48 | 1. log the time of operations
49 | 1. show graphs based on task completion.
50 |
51 | But since this is not a perfect world, we'd not be doing all that, in this tutorial we hoped to teach you the way to develop an app, so you can build everything any feature you want, make sure that you ping me if you upload it to Github!
52 |
53 | Now, we will make a few changes to our tasks library. We do not want the open() call three times, so we will wrap it in an function of our own, that'll save us multiple open calls.
54 |
55 | ```python
56 | def open_file(name, mode):
57 | try:
58 | file = open(name, mode)
59 | except IOError as e:
60 | print(str(e))
61 | sys.exit(1)
62 | return file
63 | ```
64 |
65 | This will be our function which wraps the file open statement for now.
66 |
67 | Why would we need such a thing? Why would we bother to wrap the open in an abstract function? The reason behind this is that by doing so, we have migrated the entire try-catch block inside one function. Now, if we were to change something there, we just have to change one block. Hence, the UNIX philosophy, one program does one thing well.
68 |
69 | ### The case of the `__name__`
70 |
71 | Since packages are executed as just another python program when they are imported, there is this case that we need to handle.
72 |
73 | At the end of tasks.py, add a print statement.
74 |
75 | print("this is some print statement")
76 |
77 | Save the file and run the main file.
78 |
79 | ch12 $ python3 main.py
80 | this is some print statement
81 | Invalid arguments!
82 |
83 | You can see that the print statement got executed, as we said, a module when imported is executed like just another python program. The solution to this problem is to add an if block.
84 |
85 | if __name__ == "__main__":
86 | print("this is some print statement")
87 |
88 | ch12 $ python3 main.py
89 | Invalid arguments!
90 |
91 | Now we can see that the output is the way we want it. The `__name__` is the variable which stores the way the file was executed, if we run it like `python3 file.py` then `__name__` stores the value '__main__', otherwise, it stores how it was invoked, in this case, it was invoked as "import tasks", thus `__name__` stores the value tasks.
92 |
93 | This example of course was basic, but when we write test cases for the functions of that module, they need to be inside this if block, so that we don't accidentally run the entire suite of test cases whenever we import the package.
94 |
95 | To check the value of `__name__`, add
96 |
97 |
98 | print(__name__)
99 |
100 | if __name__ == "__main__":
101 | print("this is some print statement")
102 |
103 | At the bottom of `tasks.py` NOT in the if block, if you add it to the if block then it won't be executed unless the file was executed.
104 |
105 | ##### Links
106 |
107 | |[Next](13-examples.md) | [Previous](11-function-tasks.md) | [Index](../SUMMARY.md)
108 | | ----| ----| ----|
109 |
--------------------------------------------------------------------------------
/manuscript/13-examples.md:
--------------------------------------------------------------------------------
1 | ## Some examples
2 |
3 | 1. Merge two files
4 | 1. Student Marks manager
5 | 1. CSV to SQL generator
6 |
7 | ## Merge two files
8 |
9 | Let's say you have two files, "file.txt" and "file2.txt" and you want to merge them. One can try sorting the file and then copy pasting and running some duplicate removal program, or one can use Python.
10 |
11 | First read both the files and create a dictionary. In that dictionary, we create an integer entry about each line, if it is not present in the dictionary keys, we add a value, otherwise we increment the value, that way, we can find out the duplicate values if needed.
12 |
13 |
14 | #### file name: ch13/merge.py
15 |
16 | ```python
17 |
18 | first_file = open("file.txt")
19 | second_file = open("file2.txt")
20 |
21 | first_lines = first_file.readlines()
22 | second_lines = second_file.readlines()
23 |
24 | first_lines = [line.strip() for line in first_lines]
25 | second_lines = [line.strip() for line in second_lines]
26 |
27 | final_lines = {}
28 |
29 | for line in first_lines:
30 | if line not in final_lines.keys():
31 | final_lines[line] = 0
32 | else:
33 | final_lines[line]+=1
34 |
35 | for line in second_lines:
36 | if line not in final_lines.keys():
37 | final_lines[line] = 0
38 | else:
39 | final_lines[line]+=1
40 |
41 | lines = "\n".join(list(final_lines.keys()))
42 |
43 | file = open("output.txt", "w")
44 | file.write(lines+"\n")
45 | file.close()
46 | ```
47 |
48 | ## Student Marks Manager
49 |
50 | Say that you want to build some analytics software for a school for some reason, you have the following data in a csv file:
51 |
52 | ```
53 | name,science,math,history
54 | tony,12,12,12
55 | antony,13,13,13
56 | bantony,14,14,14
57 | ```
58 |
59 | ### file name: ch13/student_scores.py
60 |
61 | ```python
62 |
63 | input_file = open("data.csv", "r")
64 | score = input_file.readlines()
65 | score = [line.strip() for line in score]
66 |
67 | heading = score[0].split(",")
68 | score = score[1:]
69 | total_subjects = len(heading)
70 |
71 | marks = {}
72 |
73 | for i in range(len(score)):
74 | sc = score[i].split(",")
75 | marks[sc[0]] = sum([int(j) for j in sc[1:]])
76 |
77 | for name in marks.keys():
78 | print("%s: %d"%( name, marks[name]))
79 |
80 | #TODO print the name of the student who got the maximum aggregare marks
81 | # This part is intentionally kept as homework for the readers.
82 |
83 | ```
84 |
85 |
86 | ## CSV to SQL generator
87 |
88 | Let's say that you have a csv file which you want to import into a database and for some reason your db client doesn't support direct import, so you have the task to convert the data in csv file into insert statements.
89 |
90 | This is a crude way to convert data, if you are having access to the database client in python, you can write your own importer without having to generate SQL statements.
91 |
92 | ### file name: ch13/csv_to_db.py
93 |
94 | ```python
95 |
96 | file_name = "data.csv"
97 | input_file = open(file_name, "r")
98 | output_file = open("data.sql", "w")
99 |
100 | csv_lines = input_file.readlines()
101 | csv_lines = [line.strip() for line in csv_lines]
102 |
103 | INSRT_STMT = 'INSERT INTO STUDENT(NAME, SCIENCE, MATH, HISTORY) VALUES('
104 |
105 | inserts = []
106 |
107 | for line in csv_lines[1:]:
108 | iline = line.split(",")
109 | insert = INSRT_STMT + '"' + iline[0] + '"'
110 | for i in iline[1:]:
111 | insert += ","
112 | insert += i
113 | insert+=");\n"
114 | inserts.append(insert)
115 |
116 | output_file.writelines(inserts)
117 | output_file.close()
118 | ```
119 |
120 | ##### Links
121 |
122 | | [Previous](12-modules-tasks.md) | [Index](../SUMMARY.md)
123 | | ----| ----|
124 |
--------------------------------------------------------------------------------
/manuscript/14-object-oriented-programming.md:
--------------------------------------------------------------------------------
1 | # Object oriented programming
2 |
3 | The code we wrote till now was split into functions, this chapter is going to be about object oriented programming. It is a widely used programming paradigm.
4 |
5 | We won't be covering OOP extensively, what we will be covering is the absolute basics so that you can then explore OOP in your own if you are interested in it.
6 |
7 | When we write programs using OOP, we split them into `objects`. Objects are instances of classes. Till now, we used various classes without being aware of OOP, every data type which we used, right from integer to dictionary was an object of a class.
8 |
9 | ## Class
10 | Look around you, you might be sitting in a chair on a desk, the chair is the _object_ and _furniture_ is the class that the chair belongs to. You might be holding a _laptop_ or a _mobile_ with you, both of them are _objects_ of class _utilities_. You might be a child or an adult, _you_ are an object belonging to the _human_ class, the _human_ class is a subset of the _animal_ class.
11 |
12 | As a class, we share certain characteristics, like walking, talking, drinking, we all have a name, height, address, hobbies. The actual details might be different, but we do have those _attributes_. Thus, we all are objects of some or the other class. Now, a class in itself can either be the absolute Global class, or it can be a _subclass_ of some class. For instance, our _class_ is human, a kitten belongs to the class _animal_, we humans are a subclass of Animal class.
13 |
14 | Animal is the highest class. (Animal class has abstract things like "should have a name", "should either walk, run or crawl", "should eat by mouth")
15 | Humans are a subclass of Animals. (we "inherit" things from our Parent class and we have our own attributes like greed, lust)
16 | Felines are a subclass of Animals (they have things like "love of milk").
17 |
18 | #### Define a class
19 |
20 | ```python
21 | class Human:
22 | def __init__(self,name, age):
23 | self.name = name
24 | self.age = age
25 |
26 | def getname(self):
27 | return self.name
28 |
29 | def getage(self):
30 | return self.age
31 |
32 | me = Human("Suraj", 99)
33 | name = me.getname()
34 | age = me.getage()
35 | print("%s:%d"%(name, age))
36 | ```
37 |
38 | ###### Methods
39 | Every function defined inside a class is called a _method_. Each method takes `self` as the first argument. The _self_ points to the object which calls the method during runtime. When we do a `me.getname()`, `self` is the `me` object.
40 |
41 | ###### Constructor
42 | the `__init__` function is the constructor. It defines how many arguments are passed to the `me = Human()` function call. The `init` is an optional method, if we don't have an init method, then by default, there are no arguments to the class's initialization call.
43 |
44 | If you have done OOP before, you'd notice the difference in Python that you do not have to define the variable properties of the class, for instance, it was in the init method that we defined the name and age variable and nowhere at the top of the class definition.
45 |
46 | The methods which start and end with `__` are to be used _strictly_ inside the class, they are syntactically internal methods, albeit they can be used by objects outside of the class declaration, we strongly advice against usage of such _internal_ methods outside of the class declaration.
47 |
48 | ##### Operators as methods
49 |
50 | ```python
51 | a = Human()
52 | b = Human()
53 | c = a+b
54 | ```
55 |
56 | This code will result in a syntax error, for operators to work on our class declaration, we need to define the following methods.
57 |
58 | There is one method for each operator, let's glance at few methods.
59 |
60 | ```python
61 | class Human:
62 | def __init__(self,name, age):
63 | self.name = name
64 | self.age = age
65 |
66 | def __add__(self, b):
67 | return self.age + b.age
68 |
69 | def __sub__(self, b):
70 | return self.age - b.age
71 |
72 | def __mul__(self, b):
73 | return self.age - b.age
74 |
75 | me = Human("Suraj", 99)
76 | you = Human("Batman", 100)
77 |
78 | print(me + you)
79 | print(me - you)
80 | print(me * you)
81 |
82 | ```
83 |
84 | Output:
85 |
86 | ```
87 | book $ python3 ../code/ch14/class-2.py
88 | 199
89 | -1
90 | -1
91 | ```
92 |
93 | If you do not implement `__add__` and you try adding up `me` and `you`, then it won't work as it wouldn't be able to add both of them. For operations like that, the `__` method is invoked on the two objects.
94 |
95 | ## Printing
96 |
97 | Whenever we use the print statement, print(object), where object is a list or a map, then the `__str__` method of that object is called. For this reason, it is essential for declaring an `__str__` method for our class, if we want a human friendly format of the print.
98 |
99 | ```
100 | def __str__(self):
101 | return "This is a human of name "+ self.name + " and age "+ str(self.age)
102 |
103 | print(me)
104 | ```
105 |
106 | book $ python3 ../code/ch14/class-2.py
107 | This is a human of name Suraj and age 99
108 |
109 | ### When to use OOP
110 |
111 | It is a matter of taste, but the ideal condition in which we can use OOP is when we are encapsulating data related to objects which we can encapsulate as classes, for instance, if we have three lists, one containint 100 names and other two containing marks of those 100 students in two subjects, then we can create a `Student` class and perform operations on it by creating a list of `Student` objects.
112 |
113 | We encourage you to write that program.
114 |
115 | #### Docstring Comments
116 |
117 | Read the [docs](https://docs.python.org/3/library/doctest.html)
118 |
119 | Python does not support multiple line comments. Triple quotes can be used as 'docstrings', for documentation purposes of functions and classes.
120 |
121 | Triple quotes can either be made up of three single quote or three double quotes. They need to be closed appropriately, otherwise they result in an error. Unlike comments, which are ignored, docstrings are evaluated, **not ignored**.
122 |
123 | Below is an example:
124 |
125 | ```python
126 | >>> def function():
127 | ... """ this is a function which does something"""
128 | ... print("hello world")
129 | ...
130 | >>> function.__doc__
131 | ' this is a function which does something'
132 | ```
133 | > From the official docs:
134 | A string literal which appears as the first expression in a class, function or module. While ignored when the suite is executed, it is recognized by the compiler and put into the `__doc__` attribute of the enclosing class, function or module. Since it is available via introspection, it is the canonical place for documentation of the object.
135 |
136 | This is a very high level overview of Object Oriented Programming. We encourage you to read more about OOP and try to write programs using OOP.
137 |
138 | ##### Links
139 |
140 | |[Previous](13-examples.md) | [Index](../SUMMARY.md)
141 | | ----| ----|
142 |
--------------------------------------------------------------------------------
/manuscript/Book.txt:
--------------------------------------------------------------------------------
1 | 01-intro-to-python.md
2 | 02-more-about-language.md
3 | 03-01-understanding-variables.md
4 | 03-02-operators.md
5 | 04-list-set-dict.md
6 | 05-constructs.md
7 | 06-file-handling.md
8 | 08-exception.md
9 | 09-functions.md
10 | 10-task.md
11 | 11-function-tasks.md
12 | 12-modules-tasks.md
13 | 13-examples.md
14 | Book.txt
15 |
--------------------------------------------------------------------------------