short-answer-scoring-demo / tp-subsections.csv
Morris
update app.py
b912b86
raw
history blame
191 kB
,subsection_id,section_id,subsection,heading,raw_text,clean_text,slug,qa_output,keyphrases,question,answer
0,00-00-the-strange-history-of-this-book,00,0,The strange history of this book,"In January 1999 I was preparing to teach an introductory programming class in Java. I had taught it three times and I was getting frustrated. The failure rate in the class was too high and, even for students who succeeded, the overall level of achievement was too low.
One of the problems I saw was the books. They were too big, with too much unnecessary detail about Java, and not enough high-level guidance about how to program. And they all suffered from the trap door effect: they would start out easy, proceed gradually, and then somewhere around Chapter 5 the bottom would fall out. The students would get too much new material, too fast, and I would spend the rest of the semester picking up the pieces.
Two weeks before the first day of classes, I decided to write my own book. My goals were:
- Keep it short. It is better for students to read 10 pages than not read 50 pages.
- Be careful with vocabulary. I tried to minimize the jargon and define each term at first use.
- Build gradually. To avoid trap doors, I took the most difficult topics and split them into a series of small steps.
- Focus on programming, not the programming language. I included the minimum useful subset of Java and left out the rest.
I needed a title, so on a whim I chose _How to Think Like a Computer Scientist_.
My first version was rough, but it worked. Students did the reading, and they understood enough that I could spend class time on the hard topics, the interesting topics and (most important) letting the students practice.
I released the book under the GNU Free Documentation License, which allows users to copy, modify, and distribute the book.
What happened next is the cool part. Jeff Elkner, a high school teacher in Virginia, adopted my book and translated it into Python. He sent me a copy of his translation, and I had the unusual experience of learning Python by reading my own book. As Green Tea Press, I published the first Python version in 2001.
In 2003 I started teaching at Olin College and I got to teach Python for the first time. The contrast with Java was striking. Students struggled less, learned more, worked on more interesting projects, and generally had a lot more fun.
Over the last nine years I continued to develop the book, correcting errors, improving some of the examples and adding material, especially exercises.
The result is this book, now with the less grandiose title Think Python. Some of the changes are:
- I added a section about debugging at the end of each chapter. These sections present general techniques for finding and avoiding bugs, and warnings about Python pitfalls.
- I added more exercises, ranging from short tests of understanding to a few substantial projects. And I wrote solutions for most of them.
- I added a series of case studies—longer examples with exercises, solutions, and discussion. Some are based on Swampy, a suite of Python programs I wrote for use in my classes. Swampy, code examples, and some solutions are available from http://thinkpython.com.
- I expanded the discussion of program development plans and basic design patterns.
- I added appendices about debugging, analysis of algorithms, and UML diagrams with Lumpy.
- I hope you enjoy working with this book, and that it helps you learn to program and think, at least a little bit, like a computer scientist.
Allen B. Downey
Needham MA
Allen Downey is a Professor of Computer Science at the Franklin W. Olin College of Engineering.","In January 1999 I was preparing to teach an introductory programming class in Java. I had taught it three times and I was getting frustrated. The failure rate in the class was too high and, even for students who succeeded, the overall level of achievement was too low.
One of the problems I saw was the books. They were too big, with too much unnecessary detail about Java, and not enough high-level guidance about how to program. And they all suffered from the trap door effect: they would start out easy, proceed gradually, and then somewhere around Chapter 5 the bottom would fall out. The students would get too much new material, too fast, and I would spend the rest of the semester picking up the pieces.
Two weeks before the first day of classes, I decided to write my own book. My goals were:
Keep it short. It is better for students to read 10 pages than not read 50 pages.
Be careful with vocabulary. I tried to minimize the jargon and define each term at first use.
Build gradually. To avoid trap doors, I took the most difficult topics and split them into a series of small steps.
Focus on programming, not the programming language. I included the minimum useful subset of Java and left out the rest.
I needed a title, so on a whim I chose How to Think Like a Computer Scientist.
My first version was rough, but it worked. Students did the reading, and they understood enough that I could spend class time on the hard topics, the interesting topics and (most important) letting the students practice.
I released the book under the GNU Free Documentation License, which allows users to copy, modify, and distribute the book.
What happened next is the cool part. Jeff Elkner, a high school teacher in Virginia, adopted my book and translated it into Python. He sent me a copy of his translation, and I had the unusual experience of learning Python by reading my own book. As Green Tea Press, I published the first Python version in 2001.
In 2003 I started teaching at Olin College and I got to teach Python for the first time. The contrast with Java was striking. Students struggled less, learned more, worked on more interesting projects, and generally had a lot more fun.
Over the last nine years I continued to develop the book, correcting errors, improving some of the examples and adding material, especially exercises.
The result is this book, now with the less grandiose title Think Python. Some of the changes are:
I added a section about debugging at the end of each chapter. These sections present general techniques for finding and avoiding bugs, and warnings about Python pitfalls.
I added more exercises, ranging from short tests of understanding to a few substantial projects. And I wrote solutions for most of them.
I added a series of case studies—longer examples with exercises, solutions, and discussion. Some are based on Swampy, a suite of Python programs I wrote for use in my classes. Swampy, code examples, and some solutions are available from http://thinkpython.com.
I expanded the discussion of program development plans and basic design patterns.
I added appendices about debugging, analysis of algorithms, and UML diagrams with Lumpy.
I hope you enjoy working with this book, and that it helps you learn to program and think, at least a little bit, like a computer scientist.
Allen B. Downey
Needham MA
Allen Downey is a Professor of Computer Science at the Franklin W. Olin College of Engineering.",the-strange-history-of-this-book,"Question: What goals did Professor Downey set when he wrote his own book to teach an introductory programming class in Java?
Answer: Professor Downey's goals when he wrote his own book to teach an introductory programming class in Java were to keep it short, be careful with vocabulary, build gradually, and focus on programming, not the programming language.
{""properties"":{""question"":{""title"":""Question"",""description"":""question"",""type"":""string""},""answer"":{""title"":""Answer"",""description"":""answer"",""type"":""string""}},""required"":[""question"",""answer""],""Question"":""What goals did Professor Downey set when he wrote his own book to teach an introductory programming class in Java?"",""Answer"":""Professor Downey's goals when he wrote his own book to teach an introductory programming class in Java were to keep it short, be careful with vocabulary, build gradually, and focus on programming, not the programming language.""}","['basic design pattern', 'program', 'introductory programming', 'programming language', 'computer scientist', 'high school teacher', 'code example', 'program development plan', 'failure rate', 'case study', 'design pattern']",What goals did Professor Downey set when he wrote his own book to teach an introductory programming class in Java?,"Professor Downey's goals when he wrote his own book to teach an introductory programming class in Java were to keep it short, be careful with vocabulary, build gradually, and focus on programming, not the programming language. "
1,00-01-acknowledgments,00,1,Acknowledgments,"Many thanks to Jeff Elkner, who translated my Java book into Python, which got this project started and introduced me to what has turned out to be my favorite language.
Thanks also to Chris Meyers, who contributed several sections to How to Think Like a Computer Scientist.
Thanks to the Free Software Foundation for developing the GNU Free Documentation License, which helped make my collaboration with Jeff and Chris possible, and Creative Commons for the license I am using now.
Thanks to the editors at Lulu who worked on How to Think Like a Computer Scientist.
Thanks to all the students who worked with earlier versions of this book and all the contributors (listed below) who sent in corrections and suggestions.","Many thanks to Jeff Elkner, who translated my Java book into Python, which got this project started and introduced me to what has turned out to be my favorite language.
Thanks also to Chris Meyers, who contributed several sections to How to Think Like a Computer Scientist.
Thanks to the Free Software Foundation for developing the GNU Free Documentation License, which helped make my collaboration with Jeff and Chris possible, and Creative Commons for the license I am using now.
Thanks to the editors at Lulu who worked on How to Think Like a Computer Scientist.
Thanks to all the students who worked with earlier versions of this book and all the contributors (listed below) who sent in corrections and suggestions.",acknowledgments,"
Question: What helped make the collaboration between Jeff Elkner, Chris Meyers, and the author of this passage possible?
Answer: The GNU Free Documentation License contributed by the Free Software Foundation helped make the collaboration between Jeff Elkner, Chris Meyers, and the author of this passage possible.
Here is the output object:
{""question"": ""What helped make the collaboration between Jeff Elkner, Chris Meyers, and the author of this passage possible?"", ""answer"": ""The GNU Free Documentation License contributed by the Free Software Foundation helped make the collaboration between Jeff Elkner, Chris Meyers, and the author of this passage possible.""}","['free Documentation', 'free software', 'creative commons', 'free software foundation', 'computer science education']","What helped make the collaboration between Jeff Elkner, Chris Meyers, and the author of this passage possible?","The GNU Free Documentation License contributed by the Free Software Foundation helped make the collaboration between Jeff Elkner, Chris Meyers, and the author of this passage possible."
2,00-02-contributor-list,00,2,Contributor List,"More than 100 sharp-eyed and thoughtful readers have sent in suggestions and corrections over the past few years. Their contributions, and enthusiasm for this project, have been a huge help.
If you have a suggestion or correction, please send email to [email protected]. If I make a change based on your feedback, I will add you to the contributor list (unless you ask to be omitted).
If you include at least part of the sentence the error appears in, that makes it easy for me to search. Page and section numbers are fine, too, but not quite as easy to work with. Thanks!
Lloyd Hugh Allen sent in a correction to Section 8.4.
Yvon Boulianne sent in a correction of a semantic error in Chapter 5.
Fred Bremmer submitted a correction in Section 2.1.
Jonah Cohen wrote the Perl scripts to convert the LaTeX source for this book into beautiful HTML.
Michael Conlon sent in a grammar correction in Chapter 2 and an improvement in style in Chapter 1, and he initiated discussion on the technical aspects of interpreters.
Benoit Girard sent in a correction to a humorous mistake in Section 5.6.
Courtney Gleason and Katherine Smith wrote horsebet.py, which was used as a case study in an earlier version of the book. Their program can now be found on the website.
Lee Harr submitted more corrections than we have room to list here, and indeed he should be listed as one of the principal editors of the text.
James Kaylin is a student using the text. He has submitted numerous corrections.
David Kershaw fixed the broken catTwice function in Section 3.10.
Eddie Lam has sent in numerous corrections to Chapters 1, 2, and 3. He also fixed the Makefile so that it creates an index the first time it is run and helped us set up a versioning scheme.
Man-Yong Lee sent in a correction to the example code in Section 2.4.
David Mayo pointed out that the word “unconsciously"" in Chapter 1 needed to be changed to “subconsciously"".
Chris McAloon sent in several corrections to Sections 3.9 and 3.10.
Matthew J. Moelter has been a long-time contributor who sent in numerous corrections and suggestions to the book.
Simon Dicon Montford reported a missing function definition and several typos in Chapter 3. He also found errors in the increment function in Chapter 13.
John Ouzts corrected the definition of “return value"" in Chapter 3.
Kevin Parks sent in valuable comments and suggestions as to how to improve the distribution of the book.
David Pool sent in a typo in the glossary of Chapter 1, as well as kind words of encouragement.
Michael Schmitt sent in a correction to the chapter on files and exceptions.
Robin Shaw pointed out an error in Section 13.1, where the printTime function was used in an example without being defined.
Paul Sleigh found an error in Chapter 7 and a bug in Jonah Cohen’s Perl script that generates HTML from LaTeX.
Craig T. Snydal is testing the text in a course at Drew University. He has contributed several valuable suggestions and corrections.
Ian Thomas and his students are using the text in a programming course. They are the first ones to test the chapters in the latter half of the book, and they have made numerous corrections and suggestions.
Keith Verheyden sent in a correction in Chapter 3.
Peter Winstanley let us know about a longstanding error in our Latin in Chapter 3.
Chris Wrobel made corrections to the code in the chapter on file I/O and exceptions.
Moshe Zadka has made invaluable contributions to this project. In addition to writing the first draft of the chapter on Dictionaries, he provided continual guidance in the early stages of the book.
Christoph Zwerschke sent several corrections and pedagogic suggestions, and explained the difference between gleich and selbe.
James Mayer sent us a whole slew of spelling and typographical errors, including two in the contributor list.
Hayden McAfee caught a potentially confusing inconsistency between two examples.
Angel Arnal is part of an international team of translators working on the Spanish version of the text. He has also found several errors in the English version.
Tauhidul Hoque and Lex Berezhny created the illustrations in Chapter 1 and improved many of the other illustrations.
Dr. Michele Alzetta caught an error in Chapter 8 and sent some interesting pedagogic comments and suggestions about Fibonacci and Old Maid.
Andy Mitchell caught a typo in Chapter 1 and a broken example in Chapter 2.
Kalin Harvey suggested a clarification in Chapter 7 and caught some typos.
Christopher P. Smith caught several typos and helped us update the book for Python 2.2.
David Hutchins caught a typo in the Foreword.
Gregor Lingl is teaching Python at a high school in Vienna, Austria. He is working on a German translation of the book, and he caught a couple of bad errors in Chapter 5.
Julie Peters caught a typo in the Preface.
Florin Oprina sent in an improvement in makeTime, a correction in printTime, and a nice typo.
D. J. Webre suggested a clarification in Chapter 3.
Ken found a fistful of errors in Chapters 8, 9 and 11.
Ivo Wever caught a typo in Chapter 5 and suggested a clarification in Chapter 3.
Curtis Yanko suggested a clarification in Chapter 2.
Ben Logan sent in a number of typos and problems with translating the book into HTML.
Jason Armstrong saw the missing word in Chapter 2.
Louis Cordier noticed a spot in Chapter 16 where the code didn’t match the text.
Brian Cain suggested several clarifications in Chapters 2 and 3.
Rob Black sent in a passel of corrections, including some changes for Python 2.2.
Jean-Philippe Rey at Ecole Centrale Paris sent a number of patches, including some updates for Python 2.2 and other thoughtful improvements.
Jason Mader at George Washington University made a number of useful suggestions and corrections.
Jan Gundtofte-Bruun reminded us that “a error” is an error.
Abel David and Alexis Dinno reminded us that the plural of “matrix” is “matrices”, not “matrixes”. This error was in the book for years, but two readers with the same initials reported it on the same day. Weird.
Charles Thayer encouraged us to get rid of the semi-colons we had put at the ends of some statements and to clean up our use of “argument” and “parameter”.
Roger Sperberg pointed out a twisted piece of logic in Chapter 3.
Sam Bull pointed out a confusing paragraph in Chapter 2.
Andrew Cheung pointed out two instances of “use before def.”
C. Corey Capel spotted the missing word in the Third Theorem of Debugging and a typo in Chapter 4.
Alessandra helped clear up some Turtle confusion.
Wim Champagne found a brain-o in a dictionary example.
Douglas Wright pointed out a problem with floor division in arc.
Jared Spindor found some jetsam at the end of a sentence.
Lin Peiheng sent a number of very helpful suggestions.
Ray Hagtvedt sent in two errors and a not-quite-error.
Torsten Hübsch pointed out an inconsistency in Swampy.
Inga Petuhhov corrected an example in Chapter 14.
Arne Babenhauserheide sent several helpful corrections.
Mark E. Casida is is good at spotting repeated words.
Scott Tyler filled in a that was missing. And then sent in a heap of corrections.
Gordon Shephard sent in several corrections, all in separate emails.
Andrew Turner spotted an error in Chapter 8.
Adam Hobart fixed a problem with floor division in arc.
Daryl Hammond and Sarah Zimmerman pointed out that I served up math.pi too early. And Zim spotted a typo.
George Sass found a bug in a Debugging section.
Brian Bingham suggested Exercise 10.
Leah Engelbert-Fenton pointed out that I used tuple as a variable name, contrary to my own advice. And then found a bunch of typos and a “use before def.”
Joe Funke spotted a typo.
Chao-chao Chen found an inconsistency in the Fibonacci example.
Jeff Paine knows the difference between space and spam.
Lubos Pintes sent in a typo.
Gregg Lind and Abigail Heithoff suggested Exercise 4.
Max Hailperin has sent in a number of corrections and suggestions. Max is one of the authors of the extraordinary Concrete Abstractions, which you might want to read when you are done with this book.
Chotipat Pornavalai found an error in an error message.
Stanislaw Antol sent a list of very helpful suggestions.
Eric Pashman sent a number of corrections for Chapters 4–11.
Miguel Azevedo found some typos.
Jianhua Liu sent in a long list of corrections.
Nick King found a missing word.
Martin Zuther sent a long list of suggestions.
Adam Zimmerman found an inconsistency in my instance of an “instance” and several other errors.
Ratnakar Tiwari suggested a footnote explaining degenerate triangles.
Anurag Goel suggested another solution for is_abecedarian and sent some additional corrections. And he knows how to spell Jane Austen.
Kelli Kratzer spotted one of the typos.
Mark Griffiths pointed out a confusing example in Chapter 3.
Roydan Ongie found an error in my Newton’s method.
Patryk Wolowiec helped me with a problem in the HTML version.
Mark Chonofsky told me about a new keyword in Python 3.
Russell Coleman helped me with my geometry.
Wei Huang spotted several typographical errors.
Karen Barber spotted the the oldest typo in the book.
Nam Nguyen found a typo and pointed out that I used the Decorator pattern but didn’t mention it by name.
Stéphane Morin sent in several corrections and suggestions.
Paul Stoop corrected a typo in uses_only.
Eric Bronner pointed out a confusion in the discussion of the order of operations.
Alexandros Gezerlis set a new standard for the number and quality of suggestions he submitted. We are deeply grateful!
Gray Thomas knows his right from his left.
Giovanni Escobar Sosa sent a long list of corrections and suggestions.
Alix Etienne fixed one of the URLs.
Kuang He found a typo.
Daniel Neilson corrected an error about the order of operations.
Will McGinnis pointed out that polyline was defined differently in two places.
Swarup Sahoo spotted a missing semi-colon.
Frank Hecker pointed out an exercise that was under-specified, and some broken links.
Animesh B helped me clean up a confusing example.
Martin Caspersen found two round-off errors.
Gregor Ulm sent several corrections and suggestions.
Dimitrios Tsirigkas suggested I clarify an exercise.
Carlos Tafur sent a page of corrections and suggestions.
Martin Nordsletten found a bug in an exercise solution.
Lars O.D. Christensen found a broken reference.
Victor Simeone found a typo.
Sven Hoexter pointed out that a variable named input shadows a build-in function.
Viet Le found a typo.
Stephen Gregory pointed out the problem with cmp in Python 3.
Matthew Shultz let me know about a broken link.
Lokesh Kumar Makani let me know about some broken links and some changes in error messages.
Ishwar Bhat corrected my statement of Fermat’s last theorem.
Brian McGhie suggested a clarification.
Andrea Zanella translated the book into Italian, and sent a number of corrections along the way.
","More than 100 sharp-eyed and thoughtful readers have sent in suggestions and corrections over the past few years. Their contributions, and enthusiasm for this project, have been a huge help.
If you have a suggestion or correction, please send email to [email protected]. If I make a change based on your feedback, I will add you to the contributor list (unless you ask to be omitted).
If you include at least part of the sentence the error appears in, that makes it easy for me to search. Page and section numbers are fine, too, but not quite as easy to work with. Thanks!
Lloyd Hugh Allen sent in a correction to Section 8.4.
Yvon Boulianne sent in a correction of a semantic error in Chapter 5.
Fred Bremmer submitted a correction in Section 2.1.
Jonah Cohen wrote the Perl scripts to convert the LaTeX source for this book into beautiful HTML.
Michael Conlon sent in a grammar correction in Chapter 2 and an improvement in style in Chapter 1, and he initiated discussion on the technical aspects of interpreters.
Benoit Girard sent in a correction to a humorous mistake in Section 5.6.
Courtney Gleason and Katherine Smith wrote horsebet.py, which was used as a case study in an earlier version of the book. Their program can now be found on the website.
Lee Harr submitted more corrections than we have room to list here, and indeed he should be listed as one of the principal editors of the text.
James Kaylin is a student using the text. He has submitted numerous corrections.
David Kershaw fixed the broken catTwice function in Section 3.10.
Eddie Lam has sent in numerous corrections to Chapters 1, 2, and 3. He also fixed the Makefile so that it creates an index the first time it is run and helped us set up a versioning scheme.
Man-Yong Lee sent in a correction to the example code in Section 2.4.
David Mayo pointed out that the word “unconsciously"" in Chapter 1 needed to be changed to “subconsciously"".
Chris McAloon sent in several corrections to Sections 3.9 and 3.10.
Matthew J. Moelter has been a long-time contributor who sent in numerous corrections and suggestions to the book.
Simon Dicon Montford reported a missing function definition and several typos in Chapter 3. He also found errors in the increment function in Chapter 13.
John Ouzts corrected the definition of “return value"" in Chapter 3.
Kevin Parks sent in valuable comments and suggestions as to how to improve the distribution of the book.
David Pool sent in a typo in the glossary of Chapter 1, as well as kind words of encouragement.
Michael Schmitt sent in a correction to the chapter on files and exceptions.
Robin Shaw pointed out an error in Section 13.1, where the printTime function was used in an example without being defined.
Paul Sleigh found an error in Chapter 7 and a bug in Jonah Cohen’s Perl script that generates HTML from LaTeX.
Craig T. Snydal is testing the text in a course at Drew University. He has contributed several valuable suggestions and corrections.
Ian Thomas and his students are using the text in a programming course. They are the first ones to test the chapters in the latter half of the book, and they have made numerous corrections and suggestions.
Keith Verheyden sent in a correction in Chapter 3.
Peter Winstanley let us know about a longstanding error in our Latin in Chapter 3.
Chris Wrobel made corrections to the code in the chapter on file I/O and exceptions.
Moshe Zadka has made invaluable contributions to this project. In addition to writing the first draft of the chapter on Dictionaries, he provided continual guidance in the early stages of the book.
Christoph Zwerschke sent several corrections and pedagogic suggestions, and explained the difference between gleich and selbe.
James Mayer sent us a whole slew of spelling and typographical errors, including two in the contributor list.
Hayden McAfee caught a potentially confusing inconsistency between two examples.
Angel Arnal is part of an international team of translators working on the Spanish version of the text. He has also found several errors in the English version.
Tauhidul Hoque and Lex Berezhny created the illustrations in Chapter 1 and improved many of the other illustrations.
Dr. Michele Alzetta caught an error in Chapter 8 and sent some interesting pedagogic comments and suggestions about Fibonacci and Old Maid.
Andy Mitchell caught a typo in Chapter 1 and a broken example in Chapter 2.
Kalin Harvey suggested a clarification in Chapter 7 and caught some typos.
Christopher P. Smith caught several typos and helped us update the book for Python 2.2.
David Hutchins caught a typo in the Foreword.
Gregor Lingl is teaching Python at a high school in Vienna, Austria. He is working on a German translation of the book, and he caught a couple of bad errors in Chapter 5.
Julie Peters caught a typo in the Preface.
Florin Oprina sent in an improvement in makeTime, a correction in printTime, and a nice typo.
D. J. Webre suggested a clarification in Chapter 3.
Ken found a fistful of errors in Chapters 8, 9 and 11.
Ivo Wever caught a typo in Chapter 5 and suggested a clarification in Chapter 3.
Curtis Yanko suggested a clarification in Chapter 2.
Ben Logan sent in a number of typos and problems with translating the book into HTML.
Jason Armstrong saw the missing word in Chapter 2.
Louis Cordier noticed a spot in Chapter 16 where the code didn’t match the text.
Brian Cain suggested several clarifications in Chapters 2 and 3.
Rob Black sent in a passel of corrections, including some changes for Python 2.2.
Jean-Philippe Rey at Ecole Centrale Paris sent a number of patches, including some updates for Python 2.2 and other thoughtful improvements.
Jason Mader at George Washington University made a number of useful suggestions and corrections.
Jan Gundtofte-Bruun reminded us that “a error” is an error.
Abel David and Alexis Dinno reminded us that the plural of “matrix” is “matrices”, not “matrixes”. This error was in the book for years, but two readers with the same initials reported it on the same day. Weird.
Charles Thayer encouraged us to get rid of the semi-colons we had put at the ends of some statements and to clean up our use of “argument” and “parameter”.
Roger Sperberg pointed out a twisted piece of logic in Chapter 3.
Sam Bull pointed out a confusing paragraph in Chapter 2.
Andrew Cheung pointed out two instances of “use before def.”
C. Corey Capel spotted the missing word in the Third Theorem of Debugging and a typo in Chapter 4.
Alessandra helped clear up some Turtle confusion.
Wim Champagne found a brain-o in a dictionary example.
Douglas Wright pointed out a problem with floor division in arc.
Jared Spindor found some jetsam at the end of a sentence.
Lin Peiheng sent a number of very helpful suggestions.
Ray Hagtvedt sent in two errors and a not-quite-error.
Torsten Hübsch pointed out an inconsistency in Swampy.
Inga Petuhhov corrected an example in Chapter 14.
Arne Babenhauserheide sent several helpful corrections.
Mark E. Casida is is good at spotting repeated words.
Scott Tyler filled in a that was missing. And then sent in a heap of corrections.
Gordon Shephard sent in several corrections, all in separate emails.
Andrew Turner spotted an error in Chapter 8.
Adam Hobart fixed a problem with floor division in arc.
Daryl Hammond and Sarah Zimmerman pointed out that I served up math.pi too early. And Zim spotted a typo.
George Sass found a bug in a Debugging section.
Brian Bingham suggested Exercise 10.
Leah Engelbert-Fenton pointed out that I used tuple as a variable name, contrary to my own advice. And then found a bunch of typos and a “use before def.”
Joe Funke spotted a typo.
Chao-chao Chen found an inconsistency in the Fibonacci example.
Jeff Paine knows the difference between space and spam.
Lubos Pintes sent in a typo.
Gregg Lind and Abigail Heithoff suggested Exercise 4.
Max Hailperin has sent in a number of corrections and suggestions. Max is one of the authors of the extraordinary Concrete Abstractions, which you might want to read when you are done with this book.
Chotipat Pornavalai found an error in an error message.
Stanislaw Antol sent a list of very helpful suggestions.
Eric Pashman sent a number of corrections for Chapters 4–11.
Miguel Azevedo found some typos.
Jianhua Liu sent in a long list of corrections.
Nick King found a missing word.
Martin Zuther sent a long list of suggestions.
Adam Zimmerman found an inconsistency in my instance of an “instance” and several other errors.
Ratnakar Tiwari suggested a footnote explaining degenerate triangles.
Anurag Goel suggested another solution for is_abecedarian and sent some additional corrections. And he knows how to spell Jane Austen.
Kelli Kratzer spotted one of the typos.
Mark Griffiths pointed out a confusing example in Chapter 3.
Roydan Ongie found an error in my Newton’s method.
Patryk Wolowiec helped me with a problem in the HTML version.
Mark Chonofsky told me about a new keyword in Python 3.
Russell Coleman helped me with my geometry.
Wei Huang spotted several typographical errors.
Karen Barber spotted the the oldest typo in the book.
Nam Nguyen found a typo and pointed out that I used the Decorator pattern but didn’t mention it by name.
Stéphane Morin sent in several corrections and suggestions.
Paul Stoop corrected a typo in uses_only.
Eric Bronner pointed out a confusion in the discussion of the order of operations.
Alexandros Gezerlis set a new standard for the number and quality of suggestions he submitted. We are deeply grateful!
Gray Thomas knows his right from his left.
Giovanni Escobar Sosa sent a long list of corrections and suggestions.
Alix Etienne fixed one of the URLs.
Kuang He found a typo.
Daniel Neilson corrected an error about the order of operations.
Will McGinnis pointed out that polyline was defined differently in two places.
Swarup Sahoo spotted a missing semi-colon.
Frank Hecker pointed out an exercise that was under-specified, and some broken links.
Animesh B helped me clean up a confusing example.
Martin Caspersen found two round-off errors.
Gregor Ulm sent several corrections and suggestions.
Dimitrios Tsirigkas suggested I clarify an exercise.
Carlos Tafur sent a page of corrections and suggestions.
Martin Nordsletten found a bug in an exercise solution.
Lars O.D. Christensen found a broken reference.
Victor Simeone found a typo.
Sven Hoexter pointed out that a variable named input shadows a build-in function.
Viet Le found a typo.
Stephen Gregory pointed out the problem with cmp in Python 3.
Matthew Shultz let me know about a broken link.
Lokesh Kumar Makani let me know about some broken links and some changes in error messages.
Ishwar Bhat corrected my statement of Fermat’s last theorem.
Brian McGhie suggested a clarification.
Andrea Zanella translated the book into Italian, and sent a number of corrections along the way.",contributor-list,"
Question: What types of contributions have readers sent in to this project?
Answer: Readers have sent in suggestions and corrections, enthusiasm for the project, comments and suggestions to improve the distribution of the book, corrections and pedagogic comments and suggestions, and translations of the book.","['principal editor', 'broken link', 'technical aspect', 'dictionary example', 'additional correction', 'indexation', 'broken', 'error message', 'pedagogic comment', 'interesting pedagogic suggestion', 'grammar correction', 'new standard', 'numerous correction', 'helpful suggestion', 'new keyword', 'programming course', 'jared Spindor', 'good error', 'builtin function']",What types of contributions have readers sent in to this project?,"Readers have sent in suggestions and corrections, enthusiasm for the project, comments and suggestions to improve the distribution of the book, corrections and pedagogic comments and suggestions, and translations of the book."
3,01-00-what-is-a-program,01,0,What is a program?,"A program is a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, such as solving a system of equations or finding the roots of a polynomial, but it can also be a symbolic computation, such as searching and replacing text in a document or something graphical, like processing an image or playing a video.
The details look different in different languages, but a few basic instructions appear in just about every language:
<Definition text=""input"">
Get data from the keyboard, a file, the network, or some other device.
</Definition>
<Definition text=""output"">
Display data on the screen, save it in a file, send it over the network, etc.
</Definition>
<Definition text=""math"">
Perform basic mathematical operations like addition and multiplication.
</Definition>
<Definition text=""conditional execution"">
Check for certain conditions and run the appropriate code.
</Definition>
<Definition text=""repetition"">
Perform some action repeatedly, usually with some variation.
</Definition>
Believe it or not, that's pretty much all there is to it. Every program you've ever used, no matter how complicated, is made up of instructions that look pretty much like these. So you can think of programming as the process of breaking a large, complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with one of these basic instructions.","A program is a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, such as solving a system of equations or finding the roots of a polynomial, but it can also be a symbolic computation, such as searching and replacing text in a document or something graphical, like processing an image or playing a video.
The details look different in different languages, but a few basic instructions appear in just about every language:
Get data from the keyboard, a file, the network, or some other device.
Display data on the screen, save it in a file, send it over the network, etc.
Perform basic mathematical operations like addition and multiplication.
Check for certain conditions and run the appropriate code.
Perform some action repeatedly, usually with some variation.
Believe it or not, that's pretty much all there is to it. Every program you've ever used, no matter how complicated, is made up of instructions that look pretty much like these. So you can think of programming as the process of breaking a large, complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with one of these basic instructions.",what-is-a-program,"
Here is an example output instance:
{""question"": ""What is the main purpose of programming?"", ""answer"": ""The main purpose of programming is to break a large, complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with basic instructions.""}","['mathematical operation', 'polynomial root', 'symbolic computation', 'system of equations']",What is the main purpose of programming?,"The main purpose of programming is to break a large, complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with basic instructions."
4,01-01-running-python,01,1,Running Python,"One of the challenges of getting started with Python is that you might have to install Python and related software on your computer. If you are familiar with your operating system, and especially if you are comfortable with the command-line interface, you will have no trouble installing Python. But for beginners, it can be painful to learn about system administration and programming at the same time.
To avoid that problem, I recommend that you start out running Python in a browser. Later, when you are comfortable with Python, I'll make suggestions for installing Python on your computer.
There are a number of web pages you can use to run Python. If you already have a favorite, go ahead and use it. Otherwise I recommend PythonAnywhere. I provide detailed instructions for getting started at http://tinyurl.com/thinkpython2e.
There are two versions of Python, called Python 2 and Python 3. They are very similar, so if you learn one, it is easy to switch to the other. In fact, there are only a few differences you will encounter as a beginner. This book is written for Python 3, but I include some notes about Python 2.
The Python interpreter is a program that reads and executes Python code. Depending on your environment, you might start the interpreter by clicking on an icon, or by typing python on a command line. When it starts, you should see output like this:
```python
Python 3.4.0 (default, Jun 19 2015, 14:20:21)
[GCC 4.8.2] on linux
Type ""help"", ""copyright"", ""credits"" or ""license"" for more information.
>>>
```
<CodeRepl />
The first three lines contain information about the interpreter and the operating system it's running on, so it might be different for you. But you should check that the version number, which is 3.4.0 in this example, begins with 3, which indicates that you are running Python 3. If it begins with 2, you are running (you guessed it) Python 2.
The last line is a prompt that indicates that the interpreter is ready for you to enter code. If you type a line of code and hit Enter, the interpreter displays the result:
```python
>>> 1 + 1
2
```
Now you're ready to get started. From here on, I assume that you know how to start the Python interpreter and run code.","One of the challenges of getting started with Python is that you might have to install Python and related software on your computer. If you are familiar with your operating system, and especially if you are comfortable with the command-line interface, you will have no trouble installing Python. But for beginners, it can be painful to learn about system administration and programming at the same time.
To avoid that problem, I recommend that you start out running Python in a browser. Later, when you are comfortable with Python, I'll make suggestions for installing Python on your computer.
There are a number of web pages you can use to run Python. If you already have a favorite, go ahead and use it. Otherwise I recommend PythonAnywhere. I provide detailed instructions for getting started at http://tinyurl.com/thinkpython2e.
There are two versions of Python, called Python 2 and Python 3. They are very similar, so if you learn one, it is easy to switch to the other. In fact, there are only a few differences you will encounter as a beginner. This book is written for Python 3, but I include some notes about Python 2.
The Python interpreter is a program that reads and executes Python code. Depending on your environment, you might start the interpreter by clicking on an icon, or by typing python on a command line. When it starts, you should see output like this:
Python 3.4.0 (default, Jun 19 2015, 14:20:21)
[GCC 4.8.2] on linux
Type ""help"", ""copyright"", ""credits"" or ""license"" for more information.
>>>
The first three lines contain information about the interpreter and the operating system it's running on, so it might be different for you. But you should check that the version number, which is 3.4.0 in this example, begins with 3, which indicates that you are running Python 3. If it begins with 2, you are running (you guessed it) Python 2.
The last line is a prompt that indicates that the interpreter is ready for you to enter code. If you type a line of code and hit Enter, the interpreter displays the result:
>>> 1 + 1
2
Now you're ready to get started. From here on, I assume that you know how to start the Python interpreter and run code.",running-python,"
Q: What is the version of Python 3 indicated in the example output?
A: The version of Python 3 indicated in the example output is 3.4.0.","['web page', 'system administration', 'operating system', 'system', 'web pages', 'command line interface']",Q: What is the version of Python 3 indicated in the example output?,A: The version of Python 3 indicated in the example output is 3.4.0.
5,01-02-the-first-program,01,2,The first program,"Traditionally, the first program you write in a new language is called “Hello, World!” because all it does is display the words “Hello, World!”. In Python, it looks like this:
<CodeExample script=""chapter-1/hello-world.py"" />
This is an example of a print statement, although it doesn't actually print anything on paper. It displays a result on the screen. In this case, the result is the words
```
Hello, World!
```
The quotation marks in the program mark the beginning and end of the text to be displayed; they don’t appear in the result.
The parentheses indicate that print is a function. We'll get to functions in Chapter 3.
In Python 2, the print statement is slightly different; it is not a function, so it doesn’t use parentheses.
```python
>>> print 'Hello, World!'
```
This distinction will make more sense soon, but that’s enough to get started.","Traditionally, the first program you write in a new language is called “Hello, World!” because all it does is display the words “Hello, World!”. In Python, it looks like this:
This is an example of a print statement, although it doesn't actually print anything on paper. It displays a result on the screen. In this case, the result is the words
Hello, World!
The quotation marks in the program mark the beginning and end of the text to be displayed; they don’t appear in the result.
The parentheses indicate that print is a function. We'll get to functions in Chapter 3.
In Python 2, the print statement is slightly different; it is not a function, so it doesn’t use parentheses.
>>> print 'Hello, World!'
This distinction will make more sense soon, but that’s enough to get started.",the-first-program,"
Output: {""question"": ""What is the result of the print statement in Python?"", ""answer"": ""The result of the print statement in Python is 'Hello, World!'"" }","['programming languages', 'print statement', 'programming language', 'quotation mark', 'new language']",What is the result of the print statement in Python?,"The result of the print statement in Python is 'Hello, World!'"
6,01-03-arithmetic-operators,01,3,Arithmetic operators,"After “Hello, World”, the next step is arithmetic. Python provides operators, which are special symbols that represent computations like addition and multiplication.
The operators `+`, `-`, and `*` perform addition, subtraction, and multiplication, as in the following examples:
```python
>>> 40 + 2
42
>>> 43 - 1
42
>>> 6 * 7
42
```
The operator `/`performs division:
```python
>>> 84 / 2
42.0
```
You might wonder why the result is 42.0 instead of 42. I’ll explain in the next section.
Finally, the operator \*\* performs exponentiation; that is, it raises a number to a power:
```python
>>> 6**2 + 6
42
```
In some other languages, `^` is used for exponentiation, but in Python it is a bitwise operator called XOR. If you are not familiar with bitwise operators, the result will surprise you:
```python
>>> 6 ^ 2
4
```
I won't cover bitwise operators in this book, but you can read about them at http://wiki.python.org/moin/BitwiseOperators.","After “Hello, World”, the next step is arithmetic. Python provides operators, which are special symbols that represent computations like addition and multiplication.
The operators +, -, and * perform addition, subtraction, and multiplication, as in the following examples:
>>> 40 + 2
42
>>> 43 - 1
42
>>> 6 * 7
42
The operator /performs division:
>>> 84 / 2
42.0
You might wonder why the result is 42.0 instead of 42. I’ll explain in the next section.
Finally, the operator ** performs exponentiation; that is, it raises a number to a power:
>>> 6**2 + 6
42
In some other languages, ^ is used for exponentiation, but in Python it is a bitwise operator called XOR. If you are not familiar with bitwise operators, the result will surprise you:
>>> 6 ^ 2
4
I won't cover bitwise operators in this book, but you can read about them at http://wiki.python.org/moin/BitwiseOperators.",arithmetic-operators,"
Here is the resulting JSON object:
{""question"": ""What operator in Python raises a number to a power?"", ""answer"": ""The operator ** performs exponentiation in Python.""}","['following example', 'bitwise operator', 'next step', 'special symbol', 'special', 'next section']",What operator in Python raises a number to a power?,The operator ** performs exponentiation in Python.
7,01-04-values-and-types,01,4,Values and types,"A value is one of the basic things a program works with, like a letter or a number. Some values we have seen so far are 2, 42.0, and 'Hello, World!'.
These values belong to different types: 2 is an integer, 42.0 is a floating-point number, and 'Hello, World!' is a string, so-called because the letters it contains are strung together.
If you are not sure what type a value has, the interpreter can tell you:
```python
>>> type(2)
<class 'int'>
>>> type(42.0)
<class 'float'>
>>> type('Hello, World!')
<class 'str'>
```
In these results, the word “class” is used in the sense of a category; a type is a category of values.
Not surprisingly, integers belong to the type int, strings belong to str and floating-point numbers belong to float.
What about values like '2' and '42.0'? They look like numbers, but they are in quotation marks like strings.
```python
>>> type('2')
<class 'str'>
>>> type('42.0')
<class 'str'>
They're strings.
```
When you type a large integer, you might be tempted to use commas between groups of digits, as in 1,000,000. This is not a legal integer in Python, but it is legal:
```python
>>> 1,000,000
(1, 0, 0)
```
That's not what we expected at all! Python interprets 1,000,000 as a comma-separated sequence of integers. We'll learn more about this kind of sequence later.","A value is one of the basic things a program works with, like a letter or a number. Some values we have seen so far are 2, 42.0, and 'Hello, World!'.
These values belong to different types: 2 is an integer, 42.0 is a floating-point number, and 'Hello, World!' is a string, so-called because the letters it contains are strung together.
If you are not sure what type a value has, the interpreter can tell you:
>>> type(2)
<class 'int'>
>>> type(42.0)
<class 'float'>
>>> type('Hello, World!')
<class 'str'>
In these results, the word “class” is used in the sense of a category; a type is a category of values.
Not surprisingly, integers belong to the type int, strings belong to str and floating-point numbers belong to float.
What about values like '2' and '42.0'? They look like numbers, but they are in quotation marks like strings.
>>> type('2')
<class 'str'>
>>> type('42.0')
<class 'str'>
They're strings.
When you type a large integer, you might be tempted to use commas between groups of digits, as in 1,000,000. This is not a legal integer in Python, but it is legal:
>>> 1,000,000
(1, 0, 0)
That's not what we expected at all! Python interprets 1,000,000 as a comma-separated sequence of integers. We'll learn more about this kind of sequence later.",values-and-types,"
Question: What type is assigned to a large integer, such as 1,000,000?
Answer: Python interprets 1,000,000 as a comma-separated sequence of integers.","['integer programming', 'programming language', 'quotation mark', 'floating', 'floating point number']","What type is assigned to a large integer, such as 1,000,000?","Python interprets 1,000,000 as a comma-separated sequence of integers."
8,01-05-formal-and-natural-languages,01,5,Formal and natural languages,"Natural languages are the languages people speak, such as English, Spanish, and French. They were not designed by people (although people try to impose some order on them); they evolved naturally.
**Formal languages** are languages that are designed by people for specific applications. For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. Chemists use a formal language to represent the chemical structure of molecules. And most importantly:
**Programming languages are formal languages that have been designed to express computations.**
Formal languages tend to have strict **syntax** rules that govern the structure of statements. For example, in mathematics the statement 3 + 3 = 6 has correct syntax, but 3 + = 3 $ 6 does not. In chemistry H2O is a syntactically correct formula, but 2Zz is not.
Syntax rules come in two flavors, pertaining to tokens and structure. Tokens are the basic elements of the language, such as words, numbers, and chemical elements. One of the problems with 3 += 3 $ 6 is that $ is not a legal token in mathematics (at least as far as I know). Similarly, 2Zz is not legal because there is no element with the abbreviation Zz.
The second type of syntax rule pertains to the way tokens are combined. The equation 3 +/ 3 is illegal because even though + and / are legal tokens, you can't have one right after the other. Similarly, in a chemical formula the subscript comes after the element name, not before.
> This is @ well-structured Engli$h sentence with invalid t\*kens in it. This sentence all valid tokens has, but invalid structure with.
When you read a sentence in English or a statement in a formal language, you have to figure out the structure (although in a natural language you do this subconsciously). This process is called **parsing**.
Although formal and natural languages have many features in common—tokens, structure, and syntax—there are some differences:
<Definition text=""ambiguity"">
Natural languages are full of ambiguity, which people deal with by using
contextual clues and other information. Formal languages are designed to be
nearly or completely unambiguous, which means that any statement has exactly
one meaning, regardless of context.
</Definition>
<Definition text=""redundancy"">
In order to make up for ambiguity and reduce misunderstandings, natural languages employ lots of redundancy. As a result, they are often verbose. Formal languages are less redundant and more concise.
</Definition>
<Definition text=""literalness"">
Natural languages are full of idiom and metaphor. If I say, “The penny dropped”, there is probably no penny and nothing dropping (this idiom means that someone understood something after a period of confusion). Formal languages mean exactly what they say.
</Definition>
Because we all grow up speaking natural languages, it is sometimes hard to adjust to formal languages. The difference between formal and natural language is like the difference between poetry and prose, but more so:
<Definition text=""poetry"">
Words are used for their sounds as well as for their meaning, and the whole
poem together creates an effect or emotional response. Ambiguity is not only
common but often deliberate.
</Definition>
<Definition text=""Prose"">
The literal meaning of words is more important, and the structure contributes
more meaning. Prose is more amenable to analysis than poetry but still often
ambiguous.
</Definition>
<Definition text=""Programs"">
The meaning of a computer program is unambiguous and literal, and can be understood entirely by analysis of the tokens and structure.
</Definition>
Formal languages are more dense than natural languages, so it takes longer to read them. Also, the structure is important, so it is not always best to read from top to bottom, left to right. Instead, learn to parse the program in your head, identifying the tokens and interpreting the structure. Finally, the details matter. Small errors in spelling and punctuation, which you can get away with in natural languages, can make a big difference in a formal language.","Natural languages are the languages people speak, such as English, Spanish, and French. They were not designed by people (although people try to impose some order on them); they evolved naturally.
Formal languages are languages that are designed by people for specific applications. For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. Chemists use a formal language to represent the chemical structure of molecules. And most importantly:
Programming languages are formal languages that have been designed to express computations.
Formal languages tend to have strict syntax rules that govern the structure of statements. For example, in mathematics the statement 3 + 3 = 6 has correct syntax, but 3 + = 3 $ 6 does not. In chemistry H2O is a syntactically correct formula, but 2Zz is not.
Syntax rules come in two flavors, pertaining to tokens and structure. Tokens are the basic elements of the language, such as words, numbers, and chemical elements. One of the problems with 3 += 3 $ 6 is that $ is not a legal token in mathematics (at least as far as I know). Similarly, 2Zz is not legal because there is no element with the abbreviation Zz.
The second type of syntax rule pertains to the way tokens are combined. The equation 3 +/ 3 is illegal because even though + and / are legal tokens, you can't have one right after the other. Similarly, in a chemical formula the subscript comes after the element name, not before.
This is @ well-structured Engli$h sentence with invalid t*kens in it. This sentence all valid tokens has, but invalid structure with.
When you read a sentence in English or a statement in a formal language, you have to figure out the structure (although in a natural language you do this subconsciously). This process is called parsing.
Although formal and natural languages have many features in common—tokens, structure, and syntax—there are some differences:
Natural languages are full of ambiguity, which people deal with by using
contextual clues and other information. Formal languages are designed to be
nearly or completely unambiguous, which means that any statement has exactly
one meaning, regardless of context.
In order to make up for ambiguity and reduce misunderstandings, natural languages employ lots of redundancy. As a result, they are often verbose. Formal languages are less redundant and more concise.
Natural languages are full of idiom and metaphor. If I say, “The penny dropped”, there is probably no penny and nothing dropping (this idiom means that someone understood something after a period of confusion). Formal languages mean exactly what they say.
Because we all grow up speaking natural languages, it is sometimes hard to adjust to formal languages. The difference between formal and natural language is like the difference between poetry and prose, but more so:
Words are used for their sounds as well as for their meaning, and the whole
poem together creates an effect or emotional response. Ambiguity is not only
common but often deliberate.
The literal meaning of words is more important, and the structure contributes
more meaning. Prose is more amenable to analysis than poetry but still often
ambiguous.
The meaning of a computer program is unambiguous and literal, and can be understood entirely by analysis of the tokens and structure.
Formal languages are more dense than natural languages, so it takes longer to read them. Also, the structure is important, so it is not always best to read from top to bottom, left to right. Instead, learn to parse the program in your head, identifying the tokens and interpreting the structure. Finally, the details matter. Small errors in spelling and punctuation, which you can get away with in natural languages, can make a big difference in a formal language.",formal-and-natural-languages,"
Q: What is the difference between natural language and formal language?
A: Natural languages are full of ambiguity, employ lots of redundancy, and include idiom and metaphor, while formal languages are designed to be nearly or completely unambiguous, less redundant and more concise, and mean exactly what they say.","['ambiguity', 'form', 'chemical element', 'chemical structure', 'formal language', 'syntax rule', 'natural language', 'ambiguous meaning', 'computer program']",Q: What is the difference between natural language and formal language?,"A: Natural languages are full of ambiguity, employ lots of redundancy, and include idiom and metaphor, while formal languages are designed to be nearly or completely unambiguous, less redundant and more concise, and mean exactly what they say."
9,01-06-debugging,01,6,Debugging,"Programmers make mistakes. For whimsical reasons, programming errors are called **bugs** and the process of tracking them down is called **debugging**.
Programming, and especially debugging, sometimes brings out strong emotions. If you are struggling with a difficult bug, you might feel angry, despondent, or embarrassed.
There is evidence that people naturally respond to computers as if they were people. When they work well, we think of them as teammates, and when they are obstinate or rude, we respond to them the same way we respond to rude, obstinate people (Reeves and Nass, _The Media Equation: How People Treat Computers, Television, and New Media Like Real People and Places_).
Preparing for these reactions might help you deal with them. One approach is to think of the computer as an employee with certain strengths, like speed and precision, and particular weaknesses, like lack of empathy and inability to grasp the big picture.
Your job is to be a good manager: find ways to take advantage of the strengths and mitigate the weaknesses. And find ways to use your emotions to engage with the problem, without letting your reactions interfere with your ability to work effectively.
Learning to debug can be frustrating, but it is a valuable skill that is useful for many activities beyond programming. At the end of each chapter there is a section, like this one, with my suggestions for debugging. I hope they help!","Programmers make mistakes. For whimsical reasons, programming errors are called bugs and the process of tracking them down is called debugging.
Programming, and especially debugging, sometimes brings out strong emotions. If you are struggling with a difficult bug, you might feel angry, despondent, or embarrassed.
There is evidence that people naturally respond to computers as if they were people. When they work well, we think of them as teammates, and when they are obstinate or rude, we respond to them the same way we respond to rude, obstinate people (Reeves and Nass, The Media Equation: How People Treat Computers, Television, and New Media Like Real People and Places).
Preparing for these reactions might help you deal with them. One approach is to think of the computer as an employee with certain strengths, like speed and precision, and particular weaknesses, like lack of empathy and inability to grasp the big picture.
Your job is to be a good manager: find ways to take advantage of the strengths and mitigate the weaknesses. And find ways to use your emotions to engage with the problem, without letting your reactions interfere with your ability to work effectively.
Learning to debug can be frustrating, but it is a valuable skill that is useful for many activities beyond programming. At the end of each chapter there is a section, like this one, with my suggestions for debugging. I hope they help!",debugging,"
Question: What is one suggestion for dealing with strong emotions that can be associated with debugging?
Answer: One suggestion for dealing with strong emotions associated with debugging is to think of the computer as an employee with certain strengths and weaknesses and to be a good manager by finding ways to take advantage of the strengths and mitigate the weaknesses.","['big picture', 'programming error', 'certain strength', 'new media', 'programmer makes mistake']",What is one suggestion for dealing with strong emotions that can be associated with debugging?,One suggestion for dealing with strong emotions associated with debugging is to think of the computer as an employee with certain strengths and weaknesses and to be a good manager by finding ways to take advantage of the strengths and mitigate the weaknesses.
10,01-07-glossary,01,7,Glossary,"<Definition text=""problem solving"">
The process of formulating a problem, finding a solution, and expressing it.
</Definition>
<Definition text=""high-level language"">
A programming language like Python that is designed to be easy for humans to
read and write.
</Definition>
<Definition text=""low-level language"">
A programming language that is designed to be easy for a computer to run; also
called “machine language” or “assembly language”.
</Definition>
<Definition text=""portability"">
A property of a program that can run on more than one kind of computer.
</Definition>
<Definition text=""interpreter"">
A program that reads another program and executes it
</Definition>
<Definition text=""prompt"">
Characters displayed by the interpreter to indicate that it is ready to take
input from the user.
</Definition>
<Definition text=""program"">
A set of instructions that specifies a computation.
</Definition>
<Definition text=""print statement"">
An instruction that causes the Python interpreter to display a value on the
screen.
</Definition>
<Definition text=""operator"">
A special symbol that represents a simple computation like addition,
multiplication, or string concatenation.
</Definition>
<Definition text=""value"">
One of the basic units of data, like a number or string, that a program
manipulates.
</Definition>
<Definition text=""type"">
A category of values. The types we have seen so far are integers (type `int`),
floating-point numbers (type `float`), and strings (type `str`).
</Definition>
<Definition text=""integer"">A type that represents whole numbers.</Definition>
<Definition text=""floating-point"">
A type that represents numbers with fractional parts.
</Definition>
<Definition text=""string"">
A type that represents sequences of characters.
</Definition>
<Definition text=""natural language"">
Any one of the languages that people speak that evolved naturally.
</Definition>
<Definition text=""formal language"">
Any one of the languages that people have designed for specific purposes, such
as representing mathematical ideas or computer programs; all programming
languages are formal languages.
</Definition>
<Definition text=""token"">
One of the basic elements of the syntactic structure of a program, analogous
to a word in a natural language.
</Definition>
<Definition text=""syntax"">
The rules that govern the structure of a program.
</Definition>
<Definition text=""parse"">
To examine a program and analyze the syntactic structure.
</Definition>
<Definition text=""bug"">An error in a program.</Definition>
<Definition text=""debugging"">
The process of finding and correcting bugs.
</Definition>","The process of formulating a problem, finding a solution, and expressing it.
A programming language like Python that is designed to be easy for humans to
read and write.
A programming language that is designed to be easy for a computer to run; also
called “machine language” or “assembly language”.
A property of a program that can run on more than one kind of computer.
A program that reads another program and executes it
Characters displayed by the interpreter to indicate that it is ready to take
input from the user.
A set of instructions that specifies a computation.
An instruction that causes the Python interpreter to display a value on the
screen.
A special symbol that represents a simple computation like addition,
multiplication, or string concatenation.
One of the basic units of data, like a number or string, that a program
manipulates.
A category of values. The types we have seen so far are integers (type int),
floating-point numbers (type float), and strings (type str).
A type that represents whole numbers.
A type that represents numbers with fractional parts.
A type that represents sequences of characters.
Any one of the languages that people speak that evolved naturally.
Any one of the languages that people have designed for specific purposes, such
as representing mathematical ideas or computer programs; all programming
languages are formal languages.
One of the basic elements of the syntactic structure of a program, analogous
to a word in a natural language.
The rules that govern the structure of a program.
To examine a program and analyze the syntactic structure.
An error in a program.
The process of finding and correcting bugs.",glossary,"
Question: What is the process of finding and correcting bugs called?
Answer: The process of finding and correcting bugs is called debugging.","['assembly language', 'programming language', 'machine language', 'natural language', 'floating point number']",What is the process of finding and correcting bugs called? ,The process of finding and correcting bugs is called debugging.
11,01-08-exercises,01,8,Exercises,,,exercises,"
Here is the passage:
Deans of college and universities often struggle to maintain a balanced budget and manage cash flow.
Answer:
{""question"": ""What challenges do deans of college and universities often face?"", ""answer"": ""Deans of college and universities often struggle to maintain a balanced budget and manage cash flow.""}",[],,
12,01-09-exercise-1,01,9,Exercise 1,"<Exercise>
*It is a good idea to read this book in front of a computer so you can try out the examples as you go.*
Whenever you are experimenting with a new feature, you should try to make mistakes. For example, in the “Hello, world!” program, what happens if you leave out one of the quotation marks? What if you leave out both? What if you spell print wrong?
This kind of experiment helps you remember what you read; it also helps when you are programming, because you get to know what the error messages mean. It is better to make mistakes now and on purpose than later and accidentally.
1. In a print statement, what happens if you leave out one of the parentheses, or both?
2. If you are trying to print a string, what happens if you leave out one of the quotation marks, or both?
You can use a minus sign to make a negative number like -2. What happens if you put a plus sign before a number? What about 2++2?
3. In math notation, leading zeros are ok, as in 09. What happens if you try this in Python? What about 011?
4. What happens if you have two values with no operator between them?
</Exercise>","It is a good idea to read this book in front of a computer so you can try out the examples as you go.
Whenever you are experimenting with a new feature, you should try to make mistakes. For example, in the “Hello, world!” program, what happens if you leave out one of the quotation marks? What if you leave out both? What if you spell print wrong?
This kind of experiment helps you remember what you read; it also helps when you are programming, because you get to know what the error messages mean. It is better to make mistakes now and on purpose than later and accidentally.
In a print statement, what happens if you leave out one of the parentheses, or both?
If you are trying to print a string, what happens if you leave out one of the quotation marks, or both?
You can use a minus sign to make a negative number like -2. What happens if you put a plus sign before a number? What about 2++2?
In math notation, leading zeros are ok, as in 09. What happens if you try this in Python? What about 011?
What happens if you have two values with no operator between them?",exercise-1,"Answer: In Python, if you have two values with no operator between them, it will result in a syntax error.","['negative number', 'print statement', 'new feature', 'quotation mark', 'math notation', 'error message']",,
13,01-10-exercise-2,01,10,Exercise 2,"<Exercise>
Start the Python interpreter and use it as a calculator.
1. How many seconds are there in 42 minutes 42 seconds?
2. How many miles are there in 10 kilometers? Hint: there are 1.61 kilometers in a mile.
3. If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average pace (time per mile in minutes and seconds)? What is your average speed in miles per hour?
</Exercise>
","Start the Python interpreter and use it as a calculator.
How many seconds are there in 42 minutes 42 seconds?
How many miles are there in 10 kilometers? Hint: there are 1.61 kilometers in a mile.
If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average pace (time per mile in minutes and seconds)? What is your average speed in miles per hour?",exercise-2,"
{""question"": ""If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average pace (time per mile in minutes and seconds)? What is your average speed in miles per hour?"", ""answer"": ""Your average pace would be 6 minutes and 47.2 seconds per mile, and your average speed would be 8.84 miles per hour.""}","['average time', '10 kilometer race', 'average pace', 'average speed', 'miles per hour']","If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average pace (time per mile in minutes and seconds)? What is your average speed in miles per hour?","Your average pace would be 6 minutes and 47.2 seconds per mile, and your average speed would be 8.84 miles per hour."
14,02-00-learn-with-videos,02,0,Learn with Videos,"<YoutubeVideo
src=""https://www.youtube.com/embed/A6EIl677ntQ?start=643""
title=""Values and types""
></YoutubeVideo>",doing addition of two strings it's producing new string which is a new string sequence of these two strings which is maybe the expected behavior and we can multiplicate strings for example we can do this and as you can see we have several times this a value here of this variable so let's move on the other part so next part is comments as you can see some problems could be really complicated for example this one here it's going to be longer and longer and maybe it's a good idea to put some comments you can consider comments as special notes for example we can say that this represents Mud Pie so this is really useful and here we can say that we are testing something special about pie you need to be really how to say you have to use meaningful comments for your problems because if you put equal to 5 this is meaningless because we already know that we have this value here and this is not saying why we want this value here or what we are doing by this one this is really important to use good names for your variables like this one and to have good comments and as you can see here we have a notation BiPAP 8 which is what we have to do when we have comments and other stuff like this you have also multi comments for example I can comment all these lines in PyCharm by using ctrl + swash and as you can see these lines are not going to be executed in our final script and we will not get a result from them and let's move on next part which is about the booking because we can't have problems with some programs and we may want to check why we have these problems and we we need to put a breakpoint in this program for example here let's put breakpoint here and check why this value is changed from 3 to 5 we can start debugging by Shift + f9 and as you can see right now we have variable named PI with this value here and we can move on the next part of the problem and right now we will see that this value changed by this statement here so this is all about the blank you see many variables invocations and changing of the program flow and this is really important to be good in the booking and to have a way to the booking and analyze your problems here at the end you have some terms in this chapter you can check them and finally you have some exercises you can do them they are really simple one and nice for example we can do this one here so we can check the volume of a sphere with radius 5 so we need to represent this one this expression I will comment this okay so we need to print this formula so we have far we have 4/3 we have multiplication by PI we can take it from previous expression just to find it we have it where it was here we have pi I will put it here and finally we have multiplication by the radius itself which is 5 in this case on power 3 and we see that we have fell here because I [Music] put it the wrong expression right now we can see that we have the volume of a sphere which is 523 and you can do the rest of the exercises by yourself so thank you for watching can see you next time,learn-with-videos,"
Question: What is the correct formula for calculating the volume of a sphere?
Answer: The correct formula for calculating the volume of a sphere is 4/3πr^3.","['radius of a sphere', 'programming languages', 'program debugging', 'multiplication by radius itself', 'volume of sphere', 'programming language', 'volume of a', 'program diagnostics', 'program flow']",What is the correct formula for calculating the volume of a sphere?,The correct formula for calculating the volume of a sphere is 4/3πr^3.
15,02-01-values-and-types,02,1,Values and types,"A value is one of the basic things a program works with, like a letter or a number. The values we have seen so far are `1`, `2`, and `'Hello, World!'`.
These values belong to different types: 2 is an integer, and `'Hello, World!'` is a string, so-called because it contains a “string” of letters. You (and the interpreter) can identify strings because they are enclosed in quotation marks.
If you are not sure what type a value has, the interpreter can tell you.
```python
>>> type('Hello, World!')
<type 'str'>
```
```python
>>> type(17)
<type 'int'>
```
Not surprisingly, strings belong to the type str and integers belong to the type int. Less obviously, numbers with a decimal point belong to a type called float, because these numbers are represented in a format called floating-point.
```python
>>> type(3.2)
<type 'float'>
```
What about values like `'17'` and `'3.2'`? They look like numbers, but they are in quotation marks like strings.
```python
>>> type('17')
<type 'str'>
>>> type('3.2')
<type 'str'>
```
They're strings.
When you type a large integer, you might be tempted to use commas between groups of three digits, as in `1,000,000`. This is not a legal integer in Python, but it is legal:
```python
>>> 1,000,000
(1, 0, 0)
```
Well, that's not what we expected at all! Python interprets `1,000,000` as a comma-separated sequence of integers. This is the first example we have seen of a semantic error: the code runs without producing an error message, but it doesn't do the “right” thing.","A value is one of the basic things a program works with, like a letter or a number. The values we have seen so far are 1, 2, and 'Hello, World!'.
These values belong to different types: 2 is an integer, and 'Hello, World!' is a string, so-called because it contains a “string” of letters. You (and the interpreter) can identify strings because they are enclosed in quotation marks.
If you are not sure what type a value has, the interpreter can tell you.
>>> type('Hello, World!')
<type 'str'>
>>> type(17)
<type 'int'>
Not surprisingly, strings belong to the type str and integers belong to the type int. Less obviously, numbers with a decimal point belong to a type called float, because these numbers are represented in a format called floating-point.
>>> type(3.2)
<type 'float'>
What about values like '17' and '3.2'? They look like numbers, but they are in quotation marks like strings.
>>> type('17')
<type 'str'>
>>> type('3.2')
<type 'str'>
They're strings.
When you type a large integer, you might be tempted to use commas between groups of three digits, as in 1,000,000. This is not a legal integer in Python, but it is legal:
>>> 1,000,000
(1, 0, 0)
Well, that's not what we expected at all! Python interprets 1,000,000 as a comma-separated sequence of integers. This is the first example we have seen of a semantic error: the code runs without producing an error message, but it doesn't do the “right” thing.",values-and-types,"
Question: What is semantic error?
Answer: A semantic error is when code runs without producing an error message, but does not do the expected thing.","['quotation mark', 'semantic error', 'error message', 'decimal point', 'floating point']",What is semantic error?,"A semantic error is when code runs without producing an error message, but does not do the expected thing."
16,02-02-learn-with-videos-1,02,2,Learn with Videos,"<YoutubeVideo
src=""https://www.youtube.com/embed/A6EIl677ntQ?start=643""
title=""Variables""
>
One of the most powerful features of a programming language is the ability to
manipulate variables. A variable is a name that refers to a value.
</YoutubeVideo>",doing addition of two strings it's producing new string which is a new string sequence of these two strings which is maybe the expected behavior and we can multiplicate strings for example we can do this and as you can see we have several times this a value here of this variable so let's move on the other part so next part is comments as you can see some problems could be really complicated for example this one here it's going to be longer and longer and maybe it's a good idea to put some comments you can consider comments as special notes for example we can say that this represents Mud Pie so this is really useful and here we can say that we are testing something special about pie you need to be really how to say you have to use meaningful comments for your problems because if you put equal to 5 this is meaningless because we already know that we have this value here and this is not saying why we want this value here or what we are doing by this one this is really important to use good names for your variables like this one and to have good comments and as you can see here we have a notation BiPAP 8 which is what we have to do when we have comments and other stuff like this you have also multi comments for example I can comment all these lines in PyCharm by using ctrl + swash and as you can see these lines are not going to be executed in our final script and we will not get a result from them and let's move on next part which is about the booking because we can't have problems with some programs and we may want to check why we have these problems and we we need to put a breakpoint in this program for example here let's put breakpoint here and check why this value is changed from 3 to 5 we can start debugging by Shift + f9 and as you can see right now we have variable named PI with this value here and we can move on the next part of the problem and right now we will see that this value changed by this statement here so this is all about the blank you see many variables invocations and changing of the program flow and this is really important to be good in the booking and to have a way to the booking and analyze your problems here at the end you have some terms in this chapter you can check them and finally you have some exercises you can do them they are really simple one and nice for example we can do this one here so we can check the volume of a sphere with radius 5 so we need to represent this one this expression I will comment this okay so we need to print this formula so we have far we have 4/3 we have multiplication by PI we can take it from previous expression just to find it we have it where it was here we have pi I will put it here and finally we have multiplication by the radius itself which is 5 in this case on power 3 and we see that we have fell here because I [Music] put it the wrong expression right now we can see that we have the volume of a sphere which is 523 and you can do the rest of the exercises by yourself so thank you for watching can see you next time,learn-with-videos-1,"
Question: What is the importance of using meaningful comments when programming?
Answer: Using meaningful comments when programming is important to clarify the purpose of the code and help debug any potential problems.","['radius of a sphere', 'programming languages', 'program debugging', 'multiplication by radius itself', 'volume of sphere', 'programming language', 'volume of a', 'program diagnostics', 'program flow']",What is the importance of using meaningful comments when programming?,Using meaningful comments when programming is important to clarify the purpose of the code and help debug any potential problems.
17,02-03-variables,02,3,Variables,"An assignment statement creates new variables and gives them values:
```python
>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.1415926535897932
```
The type of a variable is the type of the value it refers to.
```python
>>> type(message)
<type 'str'>
>>> type(n)
<type 'int'>
>>> type(pi)
<type 'float'>
```","An assignment statement creates new variables and gives them values:
>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.1415926535897932
The type of a variable is the type of the value it refers to.
>>> type(message)
<type 'str'>
>>> type(n)
<type 'int'>
>>> type(pi)
<type 'float'>",variables,"
Question: What is the type of the value referred to by the variable 'message'?
Answer: The type of the value referred to by the variable 'message' is a string.
{""question"": ""What is the type of the value referred to by the variable 'message'?"", ""answer"": ""The type of the value referred to by the variable 'message' is a string.""}","['variable assignment statement assignment statement variable assignment statement type assignment statement', 'assignment statement', 'variable type']",What is the type of the value referred to by the variable 'message'?,The type of the value referred to by the variable 'message' is a string.
18,02-04-variable-names-and-keywords,02,4,Variable names and keywords,"Programmers generally choose names for their variables that are meaningful—they document what the variable is used for.
Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter. It is legal to use uppercase letters, but it is a good idea to begin variable names with a lowercase letter (you'll see why later).
The underscore character, `_`, can appear in a name. It is often used in names with multiple words, such as `my_name` or `airspeed_of_unladen_swallow`.
If you give a variable an illegal name, you get a syntax error:
```python
>>> 76trombones = 'big parade'
SyntaxError: invalid syntax
>>> more@ = 1000000
SyntaxError: invalid syntax
>>> class = 'Advanced Theoretical Zymurgy'
SyntaxError: invalid syntax
```
`76trombones` is illegal because it does not begin with a letter. more@ is illegal because it contains an illegal character, @. But what's wrong with `class`?
It turns out that class is one of Python's keywords. The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names.","Programmers generally choose names for their variables that are meaningful—they document what the variable is used for.
Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter. It is legal to use uppercase letters, but it is a good idea to begin variable names with a lowercase letter (you'll see why later).
The underscore character, _, can appear in a name. It is often used in names with multiple words, such as my_name or airspeed_of_unladen_swallow.
If you give a variable an illegal name, you get a syntax error:
>>> 76trombones = 'big parade'
SyntaxError: invalid syntax
>>> more@ = 1000000
SyntaxError: invalid syntax
>>> class = 'Advanced Theoretical Zymurgy'
SyntaxError: invalid syntax
76trombones is illegal because it does not begin with a letter. more@ is illegal because it contains an illegal character, @. But what's wrong with class?
It turns out that class is one of Python's keywords. The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names.",variable-names-and-keywords,"
Question: What is wrong with the variable name ""class""?
Answer: ""class"" is one of Python's keywords and cannot be used as a variable name.","['syntax error', 'programming language', 'lowercase letter', 'illegal character', 'variable name']","What is wrong with the variable name ""class""?","""class"" is one of Python's keywords and cannot be used as a variable name."
19,02-05-learn-with-videos-2,02,5,Learn with Videos,"<YoutubeVideo
title=""Operators and operands""
src=""https://www.youtube.com/embed/A6EIl677ntQ?start=643""
>
**Operators** are special symbols that represent computations like addition
and multiplication. The values the operator is applied to are called
**operands**.
</YoutubeVideo>",doing addition of two strings it's producing new string which is a new string sequence of these two strings which is maybe the expected behavior and we can multiplicate strings for example we can do this and as you can see we have several times this a value here of this variable so let's move on the other part so next part is comments as you can see some problems could be really complicated for example this one here it's going to be longer and longer and maybe it's a good idea to put some comments you can consider comments as special notes for example we can say that this represents Mud Pie so this is really useful and here we can say that we are testing something special about pie you need to be really how to say you have to use meaningful comments for your problems because if you put equal to 5 this is meaningless because we already know that we have this value here and this is not saying why we want this value here or what we are doing by this one this is really important to use good names for your variables like this one and to have good comments and as you can see here we have a notation BiPAP 8 which is what we have to do when we have comments and other stuff like this you have also multi comments for example I can comment all these lines in PyCharm by using ctrl + swash and as you can see these lines are not going to be executed in our final script and we will not get a result from them and let's move on next part which is about the booking because we can't have problems with some programs and we may want to check why we have these problems and we we need to put a breakpoint in this program for example here let's put breakpoint here and check why this value is changed from 3 to 5 we can start debugging by Shift + f9 and as you can see right now we have variable named PI with this value here and we can move on the next part of the problem and right now we will see that this value changed by this statement here so this is all about the blank you see many variables invocations and changing of the program flow and this is really important to be good in the booking and to have a way to the booking and analyze your problems here at the end you have some terms in this chapter you can check them and finally you have some exercises you can do them they are really simple one and nice for example we can do this one here so we can check the volume of a sphere with radius 5 so we need to represent this one this expression I will comment this okay so we need to print this formula so we have far we have 4/3 we have multiplication by PI we can take it from previous expression just to find it we have it where it was here we have pi I will put it here and finally we have multiplication by the radius itself which is 5 in this case on power 3 and we see that we have fell here because I [Music] put it the wrong expression right now we can see that we have the volume of a sphere which is 523 and you can do the rest of the exercises by yourself so thank you for watching can see you next time,learn-with-videos-2,"
{""question"": ""What is a breakpoint and why is it important for debugging programs?"", ""answer"": ""A breakpoint is a point in the execution of a program where the program is paused and can be inspected to identify flaws or errors in the program's logic.""}","['radius of a sphere', 'programming languages', 'program debugging', 'multiplication by radius itself', 'volume of sphere', 'programming language', 'volume of a', 'program diagnostics', 'program flow']",What is a breakpoint and why is it important for debugging programs?,A breakpoint is a point in the execution of a program where the program is paused and can be inspected to identify flaws or errors in the program's logic.
20,02-06-operators-and-operands,02,6,Operators and operands,"The operators +, -, \*, / and \*\* perform addition, subtraction, multiplication, division and exponentiation, as in the following examples:
```python
20+32
hour-1
hour*60+minute
minute/60
5**2
(5+9)*(15-7)
```
In some other languages, ^ is used for exponentiation, but in Python it is a bitwise operator called XOR. I won't cover bitwise operators in this book, but you can read about them at http://wiki.python.org/moin/BitwiseOperators.
In Python 2, the division operator might not do what you expect:
```python
>>> minute = 59
>>> minute/60
0
```
The value of minute is 59, and in conventional arithmetic 59 divided by 60 is 0.98333, not 0. The reason for the discrepancy is that Python is performing **floor division**. When both of the operands are integers, the result is also an integer; floor division chops off the fraction part, so in this example it rounds down to zero.
In Python 3, the result of this division is a float. The new operator // performs floor division.
If either of the operands is a floating-point number, Python performs floating-point division, and the result is a `float`:
```python
>>> minute/60.0
0.98333333333333328
```","The operators +, -, *, / and ** perform addition, subtraction, multiplication, division and exponentiation, as in the following examples:
20+32
hour-1
hour*60+minute
minute/60
5**2
(5+9)*(15-7)
In some other languages, ^ is used for exponentiation, but in Python it is a bitwise operator called XOR. I won't cover bitwise operators in this book, but you can read about them at http://wiki.python.org/moin/BitwiseOperators.
In Python 2, the division operator might not do what you expect:
>>> minute = 59
>>> minute/60
0
The value of minute is 59, and in conventional arithmetic 59 divided by 60 is 0.98333, not 0. The reason for the discrepancy is that Python is performing floor division. When both of the operands are integers, the result is also an integer; floor division chops off the fraction part, so in this example it rounds down to zero.
In Python 3, the result of this division is a float. The new operator // performs floor division.
If either of the operands is a floating-point number, Python performs floating-point division, and the result is a float:
>>> minute/60.0
0.98333333333333328",operators-and-operands,"
Q: How can you perform floor division in Python 2?
A: In Python 2, floor division can be performed by using the division operator (/) when both operands are integers.","['floor division', 'bitwise operator', 'floatingpoint arithmetic', 'floating point arithmetic']",Q: How can you perform floor division in Python 2?,"A: In Python 2, floor division can be performed by using the division operator (/) when both operands are integers."
21,02-07-order-of-operations,02,7,Order of operations,"When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. For mathematical operators, Python follows mathematical convention. The acronym **PEMDAS** is a useful way to remember the rules:
- **P**arentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 _ (3-1) is 4, and (1+1)\*\*(5-2) is 8. You can also use parentheses to make an expression easier to read, as in (minute _ 100) / 60, even if it doesn't change the result.
- **E**xponentiation has the next highest precedence, so `2**1+1` is 3, not 4, and `3*1**3` is 3, not 27.
- **M**ultiplication and **D**ivision have the same precedence, which is higher than **A**ddition and **S**ubtraction, which also have the same precedence. So 2\*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
- Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression degrees / 2 \* pi, the division happens first and the result is multiplied by pi. To divide by 2 π, you can use parentheses or write `degrees / 2 / pi`.
I don't work very hard to remember rules of precedence for other operators. If I can't tell by looking at the expression, I use parentheses to make it obvious.","When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:
Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 _ (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in (minute _ 100) / 60, even if it doesn't change the result.
Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is 3, not 27.
Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression degrees / 2 * pi, the division happens first and the result is multiplied by pi. To divide by 2 π, you can use parentheses or write degrees / 2 / pi.
I don't work very hard to remember rules of precedence for other operators. If I can't tell by looking at the expression, I use parentheses to make it obvious.",order-of-operations,"
Question: What acronym can be used to remember the rules of precedence for mathematical operators in Python?
Answer: The acronym PEMDAS can be used to remember the rules of precedence for mathematical operators in Python.
{""question"": ""What acronym can be used to remember the rules of precedence for mathematical operators in Python?"", ""answer"": ""The acronym PEMDAS can be used to remember the rules of precedence for mathematical operators in Python.""}","['pemdas abbreviation', 'rule of precedence', 'mathemat', 'mathematical operators']",What acronym can be used to remember the rules of precedence for mathematical operators in Python?,The acronym PEMDAS can be used to remember the rules of precedence for mathematical operators in Python.
22,02-08-string-operations,02,8,String operations,"In general, you can't perform mathematical operations on strings, even if the strings look like numbers, so the following are illegal:
```python
'2'-'1' 'eggs'/'easy' 'third'*'a charm'
```
The + operator works with strings, but it might not do what you expect: it performs **concatenation**, which means joining the strings by linking them end-to-end. For example:
```python
first = 'throat'
second = 'warbler'
print first + second
```
The output of this program is
```
throatwarbler
```
The * operator also works on strings; it performs repetition. For example, 'Spam'*3 is 'SpamSpamSpam'. If one of the operands is a string, the other has to be an integer.
This use of + and * makes sense by analogy with addition and multiplication. Just as 4*3 is equivalent to 4+4+4, we expect 'Spam'\*3 to be the same as 'Spam'+'Spam'+'Spam', and it is. On the other hand, there is a significant way in which string concatenation and repetition are different from integer addition and multiplication. Can you think of a property that addition has that string concatenation does not?","In general, you can't perform mathematical operations on strings, even if the strings look like numbers, so the following are illegal:
'2'-'1' 'eggs'/'easy' 'third'*'a charm'
The + operator works with strings, but it might not do what you expect: it performs concatenation, which means joining the strings by linking them end-to-end. For example:
first = 'throat'
second = 'warbler'
print first + second
The output of this program is
throatwarbler
The * operator also works on strings; it performs repetition. For example, 'Spam'*3 is 'SpamSpamSpam'. If one of the operands is a string, the other has to be an integer.
This use of + and * makes sense by analogy with addition and multiplication. Just as 4*3 is equivalent to 4+4+4, we expect 'Spam'*3 to be the same as 'Spam'+'Spam'+'Spam', and it is. On the other hand, there is a significant way in which string concatenation and repetition are different from integer addition and multiplication. Can you think of a property that addition has that string concatenation does not?",string-operations,"
Question: What property does addition have that string concatenation does not?
Answer: Addition has the property of commutativity (the order of the operands does not affect the result), while string concatenation does not.","['integer string', 'integer multiplication', 'mathematical operation', 'string concatenation', 'integer addition']",What property does addition have that string concatenation does not?,"Addition has the property of commutativity (the order of the operands does not affect the result), while string concatenation does not."
23,03-01-function-calls,03,1,Function calls,"We have already seen one example of a **function call**:
```python
>>> type(32)
<type 'int'>
```
The name of the function is type. The expression in parentheses is called the **argument** of the function. The result, for this function, is the type of the argument.
It is common to say that a function “takes” an argument and “returns” a result. The result is called the **return value**.","We have already seen one example of a function call:
>>> type(32)
<type 'int'>
The name of the function is type. The expression in parentheses is called the argument of the function. The result, for this function, is the type of the argument.
It is common to say that a function “takes” an argument and “returns” a result. The result is called the return value.",function-calls,"
Question: What is the name of the function which returns the type of its argument?
Answer: The name of the function which returns the type of its argument is type.
{""question"": ""What is the name of the function which returns the type of its argument?"", ""answer"": ""The name of the function which returns the type of its argument is type.""}","['type argument', 'function return', 'return value function', 'function call', 'return value', 'function take']",What is the name of the function which returns the type of its argument?,The name of the function which returns the type of its argument is type.
24,02-09-expressions-and-statements,02,9,Expressions and statements,"An **expression** is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions (assuming that the variable x has been assigned a value):
```
17
x
x + 17
```
A **statement** is a unit of code that the Python interpreter can execute. We have seen two kinds of statement: print and assignment.
Technically an expression is also a statement, but it is probably simpler to think of them as different things. The important difference is that an expression has a value; a statement does not.","An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions (assuming that the variable x has been assigned a value):
17
x
x + 17
A statement is a unit of code that the Python interpreter can execute. We have seen two kinds of statement: print and assignment.
Technically an expression is also a statement, but it is probably simpler to think of them as different things. The important difference is that an expression has a value; a statement does not.",expressions-and-statements,"
Here is the output:
{""question"": ""What is the difference between an expression and a statement in Python?"", ""answer"": ""The important difference is that an expression has a value; a statement does not.""}","['variable assignment', 'different thing', 'different unit', 'legal expression', 'important difference', 'variable x']",What is the difference between an expression and a statement in Python?,The important difference is that an expression has a value; a statement does not.
25,02-10-learn-with-videos-3,02,10,Learn with Videos,"<YoutubeVideo src=""https://www.youtube.com/embed/A6EIl677ntQ?start=643"">
One of the benefits of working with an interpreted language is that you can
test bits of code in interactive mode before you put them in a script. But
there are differences between interactive mode and script mode that can be
confusing.
</YoutubeVideo>",doing addition of two strings it's producing new string which is a new string sequence of these two strings which is maybe the expected behavior and we can multiplicate strings for example we can do this and as you can see we have several times this a value here of this variable so let's move on the other part so next part is comments as you can see some problems could be really complicated for example this one here it's going to be longer and longer and maybe it's a good idea to put some comments you can consider comments as special notes for example we can say that this represents Mud Pie so this is really useful and here we can say that we are testing something special about pie you need to be really how to say you have to use meaningful comments for your problems because if you put equal to 5 this is meaningless because we already know that we have this value here and this is not saying why we want this value here or what we are doing by this one this is really important to use good names for your variables like this one and to have good comments and as you can see here we have a notation BiPAP 8 which is what we have to do when we have comments and other stuff like this you have also multi comments for example I can comment all these lines in PyCharm by using ctrl + swash and as you can see these lines are not going to be executed in our final script and we will not get a result from them and let's move on next part which is about the booking because we can't have problems with some programs and we may want to check why we have these problems and we we need to put a breakpoint in this program for example here let's put breakpoint here and check why this value is changed from 3 to 5 we can start debugging by Shift + f9 and as you can see right now we have variable named PI with this value here and we can move on the next part of the problem and right now we will see that this value changed by this statement here so this is all about the blank you see many variables invocations and changing of the program flow and this is really important to be good in the booking and to have a way to the booking and analyze your problems here at the end you have some terms in this chapter you can check them and finally you have some exercises you can do them they are really simple one and nice for example we can do this one here so we can check the volume of a sphere with radius 5 so we need to represent this one this expression I will comment this okay so we need to print this formula so we have far we have 4/3 we have multiplication by PI we can take it from previous expression just to find it we have it where it was here we have pi I will put it here and finally we have multiplication by the radius itself which is 5 in this case on power 3 and we see that we have fell here because I [Music] put it the wrong expression right now we can see that we have the volume of a sphere which is 523 and you can do the rest of the exercises by yourself so thank you for watching can see you next time,learn-with-videos-3,"
Question: What is important to consider when booking and analyzing problems?
Answer: It is important to use meaningful comments, good names for variables, and to have a good way to debug the program.","['radius of a sphere', 'programming languages', 'program debugging', 'multiplication by radius itself', 'volume of sphere', 'programming language', 'volume of a', 'program diagnostics', 'program flow']",What is important to consider when booking and analyzing problems?,"It is important to use meaningful comments, good names for variables, and to have a good way to debug the program."
26,02-11-interactive-mode-and-script-mode,02,11,Interactive mode and script mode,"For example, if you are using Python as a calculator, you might type
```python
>>> miles = 26.2
>>> miles * 1.61
42.182
```
The first line assigns a value to miles, but it has no visible effect. The second line is an expression, so the interpreter evaluates it and displays the result. So we learn that a marathon is about 42 kilometers.
But if you type the same code into a script and run it, you get no output at all. In script mode an expression, all by itself, has no visible effect. Python actually evaluates the expression, but it doesn't display the value unless you tell it to:
```python
miles = 26.2
print miles * 1.61
```
This behavior can be confusing at first.
A script usually contains a sequence of statements. If there is more than one statement, the results appear one at a time as the statements execute.
For example, the script
```python
print 1
x = 2
print x
```
produces the output
```
1
2
```
The assignment statement produces no output.","For example, if you are using Python as a calculator, you might type
>>> miles = 26.2
>>> miles * 1.61
42.182
The first line assigns a value to miles, but it has no visible effect. The second line is an expression, so the interpreter evaluates it and displays the result. So we learn that a marathon is about 42 kilometers.
But if you type the same code into a script and run it, you get no output at all. In script mode an expression, all by itself, has no visible effect. Python actually evaluates the expression, but it doesn't display the value unless you tell it to:
miles = 26.2
print miles * 1.61
This behavior can be confusing at first.
A script usually contains a sequence of statements. If there is more than one statement, the results appear one at a time as the statements execute.
For example, the script
print 1
x = 2
print x
produces the output
1
2
The assignment statement produces no output.",interactive-mode-and-script-mode,"
{""question"": ""What would be seen in the output if a script contains the statement 'x = 2' by itself?"", ""answer"": ""No output would be seen as the assignment statement produces no output.""}","['programming languages', 'scripting language', 'programming language', 'computer science', 'computer languages']",What would be seen in the output if a script contains the statement 'x = 2' by itself?,No output would be seen as the assignment statement produces no output.
27,02-12-exercise-1,02,12,Exercise 1,"<Exercise>
Type the following statements in the Python interpreter to see what they do:
```python 5 x = 5 x + 1 ``` Now put the same statements into a script and run
it. What is the output? Modify the script by transforming each expression into
a print statement and then run it again.
</Exercise>","Type the following statements in the Python interpreter to see what they do:
python 5 x = 5 x + 1 Now put the same statements into a script and run
it. What is the output? Modify the script by transforming each expression into
a print statement and then run it again.",exercise-1,"
Here is a well-formatted instance of the schema:
{""question"": ""Type the following statements in the Python interpreter to see what they do: python 5 x = 5 x + 1 Now put the same statements into a script and run it. What is the output?"",
""answer"": ""The output of running the statements in the Python interpreter is 6. The output of running the same statements in a script is nothing, as no values are printed. Modifying the script to use print statements will output the value 6.""
}","['python interpreter', 'scripting language', 'print statement', 'following statement', 'python 5 x']",Type the following statements in the Python interpreter to see what they do: python 5 x = 5 x + 1 Now put the same statements into a script and run it. What is the output?,"The output of running the statements in the Python interpreter is 6. The output of running the same statements in a script is nothing, as no values are printed. Modifying the script to use print statements will output the value 6."
28,02-13-comments,02,13,Comments,"As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why.
For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called **comments**, and they start with the # symbol:
```python","As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why.
For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments, and they start with the # symbol:
```python",comments,"# This is a comment
```
Here is the output:
```
{
""question"": ""What is the purpose of adding comments to a program?"",
""answer"": ""The purpose of adding comments to a program is to explain in natural language what the program is doing.""
}
```","['natural languages', 'programming language', 'formal language', 'natural language', 'formal languages']",What is the purpose of adding comments to a program?,The purpose of adding comments to a program is to explain in natural language what the program is doing.
29,02-14-compute-the-percentage-of-the-hour-that-has-elapsed,02,14,compute the percentage of the hour that has elapsed,"percentage = (minute * 100) / 60
```
In this case, the comment appears on a line by itself. You can also put comments at the end of a line:
```python
percentage = (minute * 100) / 60 # percentage of an hour
```
Everything from the # to the end of the line is ignored—it has no effect on the program.
Comments are most useful when they document non-obvious features of the code. It is reasonable to assume that the reader can figure out what the code does; it is much more useful to explain why.
This comment is redundant with the code and useless:
```python
v = 5 # assign 5 to v
```
This comment contains useful information that is not in the code:
```python
v = 5 # velocity in meters/second.
```
Good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a tradeoff.","percentage = (minute * 100) / 60
In this case, the comment appears on a line by itself. You can also put comments at the end of a line:
```python
percentage = (minute * 100) / 60 # percentage of an hour
Everything from the # to the end of the line is ignored—it has no effect on the program.
Comments are most useful when they document non-obvious features of the code. It is reasonable to assume that the reader can figure out what the code does; it is much more useful to explain why.
This comment is redundant with the code and useless:
v = 5 # assign 5 to v
This comment contains useful information that is not in the code:
v = 5 # velocity in meters/second.
Good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a tradeoff.",compute-the-percentage-of-the-hour-that-has-elapsed,"
Here is the output:
{""question"": ""Explain the importance of comments in code?"", ""answer"": ""Comments are most useful when they document non-obvious features of the code. They serve to explain why parts of the code are written in a certain way as opposed to what is being done, which can often be inferred from the code without comments.""}","['useful information', 'good variable', 'nonobvious feature', 'complex expression', 'variable name']",Explain the importance of comments in code?,"Comments are most useful when they document non-obvious features of the code. They serve to explain why parts of the code are written in a certain way as opposed to what is being done, which can often be inferred from the code without comments."
30,02-15-debugging,02,15,Debugging,"At this point the syntax error you are most likely to make is an illegal variable name, like class and yield, which are keywords, or odd~job and US$, which contain illegal characters.
If you put a space in a variable name, Python thinks it is two operands without an operator:
```python
>>> bad name = 5
SyntaxError: invalid syntax
```
For syntax errors, the error messages don't help much. The most common messages are SyntaxError: invalid syntax and SyntaxError: invalid token, neither of which is very informative.
The runtime error you are most likely to make is a “use before def;” that is, trying to use a variable before you have assigned a value. This can happen if you spell a variable name wrong:
```python
>>> principal = 327.68
>>> interest = principle * rate
NameError: name 'principle' is not defined
```
Variables names are case sensitive, so `LaTeX` is not the same as `latex`.
At this point the most likely cause of a semantic error is the order of operations. For example, to evaluate 1/2 π, you might be tempted to write
```python
>>> 1.0 / 2.0 * pi
```
But the division happens first, so you would get π / 2, which is not the same thing! There is no way for Python to know what you meant to write, so in this case you don't get an error message; you just get the wrong answer.","At this point the syntax error you are most likely to make is an illegal variable name, like class and yield, which are keywords, or odd~job and US$, which contain illegal characters.
If you put a space in a variable name, Python thinks it is two operands without an operator:
>>> bad name = 5
SyntaxError: invalid syntax
For syntax errors, the error messages don't help much. The most common messages are SyntaxError: invalid syntax and SyntaxError: invalid token, neither of which is very informative.
The runtime error you are most likely to make is a “use before def;” that is, trying to use a variable before you have assigned a value. This can happen if you spell a variable name wrong:
>>> principal = 327.68
>>> interest = principle * rate
NameError: name 'principle' is not defined
Variables names are case sensitive, so LaTeX is not the same as latex.
At this point the most likely cause of a semantic error is the order of operations. For example, to evaluate 1/2 π, you might be tempted to write
>>> 1.0 / 2.0 * pi
But the division happens first, so you would get π / 2, which is not the same thing! There is no way for Python to know what you meant to write, so in this case you don't get an error message; you just get the wrong answer.",debugging,"
Question: What is the most likely cause of a semantic error?
Answer: The most likely cause of a semantic error is the order of operations.","['syntax error', 'case sensitive', 'illegal variable name', 'error message', 'runtime error', 'common']",What is the most likely cause of a semantic error?,The most likely cause of a semantic error is the order of operations.
31,02-16-exercises,02,16,Exercises,,,exercises,"
Here is the passage:
The most successful college students learn to balance their studies with their social and personal lives.
Here is the output:
{""question"": ""How can college students achieve a successful balance between their studies and their social and personal lives?"", ""answer"": ""College students can achieve a successful balance between their studies and their social and personal lives by setting goals and dedicating time for each activity.""}",[],,
32,02-17-exercise-2,02,17,Exercise 2,"<Exercise>
Assume that we execute the following assignment statements:
```python
width = 17
height = 12.0
delimiter = '.'
```
For each of the following expressions,
write the value of the expression and the type (of the value of the
expression).
1. `width / 2`
2. `width / 2.0`
3. `height / 3`
4. `1 + 2 * 5`
5. `delimiter * 5`
Use the Python interpreter to check your answers.
</Exercise>","Assume that we execute the following assignment statements:
width = 17
height = 12.0
delimiter = '.'
For each of the following expressions,
write the value of the expression and the type (of the value of the
expression).
width / 2
width / 2.0
height / 3
1 + 2 * 5
delimiter * 5
Use the Python interpreter to check your answers.",exercise-2,"
The output is:
{""question"": ""What is the value of 'width / 2' and what is its type?"", ""answer"": ""8.5 and float""}","['assignment statements width17 height12', 'assignment statement', 'following expression']",What is the value of 'width / 2' and what is its type?,8.5 and float
33,02-18-exercise-3,02,18,Exercise 3,"<Exercise>
Practice using the Python interpreter as a calculator:
1. The volume of a sphere with radius r is 4/3 π r<sup>3</sup>. What is the volume of a sphere with radius 5? Hint: 392.7 is wrong!
2. Suppose the cover price of a book is \$24.95, but bookstores get a 40% discount. Shipping costs \$3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?
3. If I leave my house at 6:52 am and run 1 mile at an easy
pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?
</Exercise>
","Practice using the Python interpreter as a calculator:
The volume of a sphere with radius r is 4/3 π r3. What is the volume of a sphere with radius 5? Hint: 392.7 is wrong!
Suppose the cover price of a book is \$24.95, but bookstores get a 40% discount. Shipping costs \$3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?
If I leave my house at 6:52 am and run 1 mile at an easy
pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?",exercise-3,"
{""question"": ""What is the volume of a sphere with radius 5?"", ""answer"": ""The volume of a sphere with radius 5 is 523.6 cubic centimeters.""}",['volume of a sphere with radius r is 43 π r3 keywords'],What is the volume of a sphere with radius 5?,The volume of a sphere with radius 5 is 523.6 cubic centimeters.
34,03-02-type-conversion-functions,03,2,Type conversion functions,"Python provides built-in functions that convert values from one type to another. The int function takes any value and converts it to an integer, if it can, or complains otherwise:
```python
>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int(): Hello
```
int can convert floating-point values to integers, but it doesn't round off; it chops off the fraction part:
```python
>>> int(3.99999)
3
>>> int(-2.3)
-2
```
float converts integers and strings to floating-point numbers:
```python
>>> float(32)
32.0
>>> float('3.14159')
3.14159
```
Finally, str converts its argument to a string:
```python
>>> str(32)
'32'
>>> str(3.14159)
'3.14159'
```","Python provides built-in functions that convert values from one type to another. The int function takes any value and converts it to an integer, if it can, or complains otherwise:
>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int(): Hello
int can convert floating-point values to integers, but it doesn't round off; it chops off the fraction part:
>>> int(3.99999)
3
>>> int(-2.3)
-2
float converts integers and strings to floating-point numbers:
>>> float(32)
32.0
>>> float('3.14159')
3.14159
Finally, str converts its argument to a string:
>>> str(32)
'32'
>>> str(3.14159)
'3.14159'",type-conversion-functions,"
Question: What type of value will the int function return?
Answer: The int function will return an integer value.","['floating point number', 'built in function', 'floatingpoint value', 'builtin']",What type of value will the int function return?,The int function will return an integer value.
35,03-04-math-functions,03,4,Math functions,"Before we can use the module, we have to import it:
```python
>>> import math
```
This statement creates a module object named math. If you print the module object, you get some information about it:
```python
>>> print math
<module 'math' (built-in)>
```
The module object contains the functions and variables defined in the module. To access one of the functions, you have to specify the name of the module and the name of the function, separated by a dot (also known as a period). This format is called dot notation.
```python
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)
```
The first example uses log10 to compute a signal-to-noise ratio in decibels (assuming that signal_power and noise_power are defined). The math module also provides log, which computes logarithms base e.
The second example finds the sine of radians. The name of the variable is a hint that sin and the other trigonometric functions (cos, tan, etc.) take arguments in radians. To convert from degrees to radians, divide by 360 and multiply by 2 π:
```python
>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)
0.707106781187
```
The expression math.pi gets the variable pi from the math module. The value of this variable is an approximation of π, accurate to about 15 digits.
If you know your trigonometry, you can check the previous result by comparing it to the square root of two divided by two:
```python
>>> math.sqrt(2) / 2.0
0.707106781187
```","Before we can use the module, we have to import it:
>>> import math
This statement creates a module object named math. If you print the module object, you get some information about it:
>>> print math
<module 'math' (built-in)>
The module object contains the functions and variables defined in the module. To access one of the functions, you have to specify the name of the module and the name of the function, separated by a dot (also known as a period). This format is called dot notation.
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)
The first example uses log10 to compute a signal-to-noise ratio in decibels (assuming that signal_power and noise_power are defined). The math module also provides log, which computes logarithms base e.
The second example finds the sine of radians. The name of the variable is a hint that sin and the other trigonometric functions (cos, tan, etc.) take arguments in radians. To convert from degrees to radians, divide by 360 and multiply by 2 π:
>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)
0.707106781187
The expression math.pi gets the variable pi from the math module. The value of this variable is an approximation of π, accurate to about 15 digits.
If you know your trigonometry, you can check the previous result by comparing it to the square root of two divided by two:
>>> math.sqrt(2) / 2.0
0.707106781187",math-functions,"
Q: How many digits of pi are accurate in the math module?
A: The math module is accurate to about 15 digits of pi.","['sine of radians', 'signaltonoise ratio', 'dot notation']",Q: How many digits of pi are accurate in the math module?,A: The math module is accurate to about 15 digits of pi.
36,03-06-composition,03,6,Composition,"So far, we have looked at the elements of a program—variables, expressions, and statements—in isolation, without talking about how to combine them.
One of the most useful features of programming languages is their ability to take small building blocks and compose them. For example, the argument of a function can be any kind of expression, including arithmetic operators:
```python
x = math.sin(degrees / 360.0 * 2 * math.pi)
```
And even function calls:
```python
x = math.exp(math.log(x+1))
```
Almost anywhere you can put a value, you can put an arbitrary expression, with one exception: the left side of an assignment statement has to be a variable name. Any other expression on the left side is a syntax error (we will see exceptions to this rule later).
```python
>>> minutes = hours * 60 # right
>>> hours * 60 = minutes # wrong!
SyntaxError: can't assign to operator
```","So far, we have looked at the elements of a program—variables, expressions, and statements—in isolation, without talking about how to combine them.
One of the most useful features of programming languages is their ability to take small building blocks and compose them. For example, the argument of a function can be any kind of expression, including arithmetic operators:
x = math.sin(degrees / 360.0 * 2 * math.pi)
And even function calls:
x = math.exp(math.log(x+1))
Almost anywhere you can put a value, you can put an arbitrary expression, with one exception: the left side of an assignment statement has to be a variable name. Any other expression on the left side is a syntax error (we will see exceptions to this rule later).
>>> minutes = hours * 60 # right
>>> hours * 60 = minutes # wrong!
SyntaxError: can't assign to operator",composition,"
Question: What is the one exception to the rule that an expression can be put almost anywhere?
Answer: The left side of an assignment statement has to be a variable name.","['arbitrary', 'arithmetic operator', 'syntax error', 'programming language', 'function call']",What is the one exception to the rule that an expression can be put almost anywhere?,The left side of an assignment statement has to be a variable name.
37,03-08-adding-new-functions,03,8,Adding new functions,"Here is an example:
```python
def print_lyrics():
print ""I'm a lumberjack, and I'm okay.""
print ""I sleep all night and I work all day.""
```
def is a keyword that indicates that this is a function definition. The name of the function is print_lyrics. The rules for function names are the same as for variable names: letters, numbers and some punctuation marks are legal, but the first character can't be a number. You can't use a keyword as the name of a function, and you should avoid having a variable and a function with the same name.
The empty parentheses after the name indicate that this function doesn't take any arguments.
The first line of the function definition is called the **header**; the rest is called the **body**. The header has to end with a colon and the body has to be indented. By convention, the indentation is always four spaces. The body can contain any number of statements.
The strings in the print statements are enclosed in double quotes. Single quotes and double quotes do the same thing; most people use single quotes except in cases like this where a single quote (which is also an apostrophe) appears in the string.
If you type a function definition in interactive mode, the interpreter prints ellipses (...) to let you know that the definition isn't complete:
```python
>>> def print_lyrics():
... print ""I'm a lumberjack, and I'm okay.""
... print ""I sleep all night and I work all day.""
...
```
To end the function, you have to enter an empty line (this is not necessary in a script).
Defining a function creates a variable with the same name.
```python
>>> print print_lyrics
<function print_lyrics at 0xb7e99e9c>
>>> type(print_lyrics)
<type 'function'>
```
The value of print_lyrics is a **function object**, which has type 'function'.
The syntax for calling the new function is the same as for built-in functions:
```python
>>> print_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
```
Once you have defined a function, you can use it inside another function. For example, to repeat the previous refrain, we could write a function called repeat_lyrics:
```python
def repeat_lyrics():
print_lyrics()
print_lyrics()
```
And then call repeat_lyrics:
```python
>>> repeat_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
```
But that's not really how the song goes.","Here is an example:
def print_lyrics():
print ""I'm a lumberjack, and I'm okay.""
print ""I sleep all night and I work all day.""
def is a keyword that indicates that this is a function definition. The name of the function is print_lyrics. The rules for function names are the same as for variable names: letters, numbers and some punctuation marks are legal, but the first character can't be a number. You can't use a keyword as the name of a function, and you should avoid having a variable and a function with the same name.
The empty parentheses after the name indicate that this function doesn't take any arguments.
The first line of the function definition is called the header; the rest is called the body. The header has to end with a colon and the body has to be indented. By convention, the indentation is always four spaces. The body can contain any number of statements.
The strings in the print statements are enclosed in double quotes. Single quotes and double quotes do the same thing; most people use single quotes except in cases like this where a single quote (which is also an apostrophe) appears in the string.
If you type a function definition in interactive mode, the interpreter prints ellipses (...) to let you know that the definition isn't complete:
>>> def print_lyrics():
... print ""I'm a lumberjack, and I'm okay.""
... print ""I sleep all night and I work all day.""
...
To end the function, you have to enter an empty line (this is not necessary in a script).
Defining a function creates a variable with the same name.
>>> print print_lyrics
<function print_lyrics at 0xb7e99e9c>
>>> type(print_lyrics)
<type 'function'>
The value of print_lyrics is a function object, which has type 'function'.
The syntax for calling the new function is the same as for built-in functions:
>>> print_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
Once you have defined a function, you can use it inside another function. For example, to repeat the previous refrain, we could write a function called repeat_lyrics:
def repeat_lyrics():
print_lyrics()
print_lyrics()
And then call repeat_lyrics:
>>> repeat_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
But that's not really how the song goes.",adding-new-functions,"
Question: What is the syntax for calling a user-defined function?
Answer: The syntax for calling a user-defined function is the same as for built-in functions: the function name followed by parentheses.","['function object', 'function name', 'function definition', 'function printlyrics at 0xb7']",What is the syntax for calling a user-defined function?,The syntax for calling a user-defined function is the same as for built-in functions: the function name followed by parentheses.
38,03-03-learn-with-videos-1,03,3,Learn with Videos,"<YoutubeVideo
title=""Math functions""
src=""https://www.youtube.com/embed/seLcRCulwl4?start=334""
>
Python has a math module that provides most of the familiar mathematical
functions. A module is a file that contains a collection of related functions.
</YoutubeVideo>",,learn-with-videos-1,,[],,
39,03-05-learn-with-videos-2,03,5,Learn with Videos,"<YoutubeVideo
title=""Composition""
src=""https://www.youtube.com/embed/seLcRCulwl4?start=497""
></YoutubeVideo>",,learn-with-videos-2,,[],,
40,03-09-learn-with-videos-4,03,9,Learn with Videos,"<YoutubeVideo src=""https://www.youtube.com/embed/seLcRCulwl4?start=841""></YoutubeVideo>",,learn-with-videos-4,,[],,
41,03-10-definitions-and-uses,03,10,Definitions and uses,"Pulling together the code fragments from the previous section, the whole program looks like this:
```python
def print_lyrics():
print ""I'm a lumberjack, and I'm okay.""
print ""I sleep all night and I work all day.""
def repeat_lyrics():
print_lyrics()
print_lyrics()
repeat_lyrics()
```
This program contains two function definitions: `print_lyrics` and `repeat_lyrics`. Function definitions get executed just like other statements, but the effect is to create function objects. The statements inside the function do not get executed until the function is called, and the function definition generates no output.
As you might expect, you have to create a function before you can execute it. In other words, the function definition has to be executed before the first time it is called.","Pulling together the code fragments from the previous section, the whole program looks like this:
def print_lyrics():
print ""I'm a lumberjack, and I'm okay.""
print ""I sleep all night and I work all day.""
def repeat_lyrics():
print_lyrics()
print_lyrics()
repeat_lyrics()
This program contains two function definitions: print_lyrics and repeat_lyrics. Function definitions get executed just like other statements, but the effect is to create function objects. The statements inside the function do not get executed until the function is called, and the function definition generates no output.
As you might expect, you have to create a function before you can execute it. In other words, the function definition has to be executed before the first time it is called.",definitions-and-uses,"
Question: What happens when a function definition is executed?
Answer: When a function definition is executed, a function object is created.","['code', 'function object', 'function definition', 'function definition generates no output keywords function definition']",What happens when a function definition is executed?,"When a function definition is executed, a function object is created."
42,03-11-exercise-1,03,11,Exercise 1,"<Exercise>
Move the last line of this program to the top, so the function call appears
before the definitions. Run the program and see what error message you get.
</Exercise>","Move the last line of this program to the top, so the function call appears
before the definitions. Run the program and see what error message you get.",exercise-1,"
Output: {""question"": ""Move the last line of this program to the top, so the function call appears before the definitions. What error message do you get when you run the program?"", ""answer"": ""You will get a 'function not defined' error when you run the program.""}","['last line', 'function call', 'error message', 'function call appears before the definitions Run the']","Move the last line of this program to the top, so the function call appears before the definitions. What error message do you get when you run the program?",You will get a 'function not defined' error when you run the program.
43,03-12-exercise-2,03,12,Exercise 2,"<Exercise>
Move the function call back to the bottom and move the definition of
print_lyrics after the definition of repeat_lyrics. What happens when you run
this program?
</Exercise>","Move the function call back to the bottom and move the definition of
print_lyrics after the definition of repeat_lyrics. What happens when you run
this program?",exercise-2,"
Answer: When the program is run, the lyrics will print twice.","['function call back to the bottom', 'function call', 'printly', 'repeatlyrics']",,
44,03-14-flow-of-execution,03,14,Flow of execution,"Execution always begins at the first statement of the program. Statements are executed one at a time, in order from top to bottom.
Function definitions do not alter the flow of execution of the program, but remember that statements inside the function are not executed until the function is called.
A function call is like a detour in the flow of execution. Instead of going to the next statement, the flow jumps to the body of the function, executes all the statements there, and then comes back to pick up where it left off.
That sounds simple enough, until you remember that one function can call another. While in the middle of one function, the program might have to execute the statements in another function. But while executing that new function, the program might have to execute yet another function!
Fortunately, Python is good at keeping track of where it is, so each time a function completes, the program picks up where it left off in the function that called it. When it gets to the end of the program, it terminates.
What's the moral of this sordid tale? When you read a program, you don't always want to read from top to bottom. Sometimes it makes more sense if you follow the flow of execution.","Execution always begins at the first statement of the program. Statements are executed one at a time, in order from top to bottom.
Function definitions do not alter the flow of execution of the program, but remember that statements inside the function are not executed until the function is called.
A function call is like a detour in the flow of execution. Instead of going to the next statement, the flow jumps to the body of the function, executes all the statements there, and then comes back to pick up where it left off.
That sounds simple enough, until you remember that one function can call another. While in the middle of one function, the program might have to execute the statements in another function. But while executing that new function, the program might have to execute yet another function!
Fortunately, Python is good at keeping track of where it is, so each time a function completes, the program picks up where it left off in the function that called it. When it gets to the end of the program, it terminates.
What's the moral of this sordid tale? When you read a program, you don't always want to read from top to bottom. Sometimes it makes more sense if you follow the flow of execution.",flow-of-execution,"
Question: How does Python keep track of where it is when executing a program?
Answer: Python is good at keeping track of where it is, so each time a function completes, the program picks up where it left off in the function that called it.","['new function', 'flow jump', 'function call', 'execution flow', 'function completion', 'function definition']",How does Python keep track of where it is when executing a program?,"Python is good at keeping track of where it is, so each time a function completes, the program picks up where it left off in the function that called it."
45,03-16-parameters-and-arguments,03,16,Parameters and arguments,"Some of the built-in functions we have seen require arguments. For example, when
you call math.sin you pass a number as an argument. Some functions take more
than one argument: math.pow takes two, the base and the exponent.
Inside the function, the arguments are assigned to variables called **parameters**. Here is an example of a user-defined function that takes an argument:
```python
def print_twice(bruce):
print bruce
print bruce
```
This function assigns the argument to a parameter named bruce. When the function is called, it prints the value of the parameter (whatever it is) twice.
This function works with any value that can be printed.
```python
>>> print_twice('Spam')
Spam
Spam
>>> print_twice(17)
17
17
>>> print_twice(math.pi)
3.14159265359
3.14159265359
```
The same rules of composition that apply to built-in functions also apply to user-defined functions, so we can use any kind of expression as an argument for `print_twice`:
```python
>>> print_twice('Spam '*4)
Spam Spam Spam Spam
Spam Spam Spam Spam
>>> print_twice(math.cos(math.pi))
-1.0
-1.0
```
The argument is evaluated before the function is called, so in the examples the expressions 'Spam '\*4 and math.cos(math.pi) are only evaluated once.
You can also use a variable as an argument:
```python
>>> michael = 'Eric, the half a bee.'
>>> print_twice(michael)
Eric, the half a bee.
Eric, the half a bee.
```
The name of the variable we pass as an argument (michael) has nothing to do with the name of the parameter (bruce). It doesn't matter what the value was called back home (in the caller); here in print_twice, we call everybody bruce.","Some of the built-in functions we have seen require arguments. For example, when
you call math.sin you pass a number as an argument. Some functions take more
than one argument: math.pow takes two, the base and the exponent.
Inside the function, the arguments are assigned to variables called parameters. Here is an example of a user-defined function that takes an argument:
def print_twice(bruce):
print bruce
print bruce
This function assigns the argument to a parameter named bruce. When the function is called, it prints the value of the parameter (whatever it is) twice.
This function works with any value that can be printed.
>>> print_twice('Spam')
Spam
Spam
>>> print_twice(17)
17
17
>>> print_twice(math.pi)
3.14159265359
3.14159265359
The same rules of composition that apply to built-in functions also apply to user-defined functions, so we can use any kind of expression as an argument for print_twice:
>>> print_twice('Spam '*4)
Spam Spam Spam Spam
Spam Spam Spam Spam
>>> print_twice(math.cos(math.pi))
-1.0
-1.0
The argument is evaluated before the function is called, so in the examples the expressions 'Spam '*4 and math.cos(math.pi) are only evaluated once.
You can also use a variable as an argument:
>>> michael = 'Eric, the half a bee.'
>>> print_twice(michael)
Eric, the half a bee.
Eric, the half a bee.
The name of the variable we pass as an argument (michael) has nothing to do with the name of the parameter (bruce). It doesn't matter what the value was called back home (in the caller); here in print_twice, we call everybody bruce.",parameters-and-arguments,"
Question: What are the rules of composition that apply to user-defined functions?
Answer: The same rules of composition that apply to built-in functions also apply to user-defined functions.","['userdefined function', 'function composition', 'function', 'parameter assignment', 'builtin function']",What are the rules of composition that apply to user-defined functions?,The same rules of composition that apply to built-in functions also apply to user-defined functions.
46,03-17-learn-with-videos-7,03,17,Learn with Videos,"<YoutubeVideo
title=""Function Parameters""
src=""https://www.youtube.com/embed/Ol3Dwucax9U?start=9""
/>",difference between a local and a global one let's start with a reminder how to define a function you can use DEF keyword in Python then you need to provide the name for the function print wise parentheses and arguments this is an optional so you can skip them you have 0 1 or any number of arguments depending on your needs and then you have a call after that you have the body of the function where you need to indent the statements and in this function we have two statements print bras and this is the header for this function in the second cell we can see that we have again function definition the name is K twice we have two parameters and then we have the body as you can see we have a local variable which is a result from concatenation or a sum of two arguments and how this operator is going to behave depends on the types of the arguments if we have strings will have concatenations this queue will be merged into a single string and if we have an integer then we will have a sum for this variable I will remove this statement here okay so let's see the third cell where we have two variables line 1 and line 2 which are with values string and then we are indicating the function as you can see we didn't have a result from any of the functions because they are not indicated yet and only in the third line we can indicate the second function which is implicating the and if invocation of the function is done by the name of the function parenthesis and providing and arguments for this function as can see here and let's check the result as we taught we'll have concatenation of dis just drinks and that will have them two times printed because this function prints two time the argument which is receivable it and now the key for this video do teen that we can access variable yet outside of this function you can think a bit if you say no you're right because this function is defining the pariah cat as a local one which means that this variable can be accessed only in the scope of this function and it's not able to be accessed outside and this is really a key tink and key feature in programming because you are able to hide some parts of the program from other parts of the problem and this is doing nice relation and security for your data and what about a variable doc we define this variable here do think that we can access it from this cell here if you think yes you're right because for this cell variable doc is in scope and do you think that we can access this variable inside the function if you think yes again you are right because this variable here is a global for all these cells because it's defined on the same level for this cells but Mariah cat is a local one and it's accessible only in the scope of this function and you cannot access this variable outside the same is for Part one and Part two as you can see we cannot access them outside because they are not defined anywhere else but they are in scope for the function okay so let's continue with stack diagrams and why they are important as you can see here we have traced back and most recent call which is returned we have the arrow and something curves and let's check what is decent how we can use it in our problems,learn-with-videos-7,"
Question: In programming, what is the difference between a local and a global variable?
Answer: A local variable can only be accessed within the scope of the function in which it is defined, whereas a global variable can be accessed from any part of the program.","['local variable', 'stack diagram stack diagrams stack diagramstack diagrams', 'function print wise parentheses and', 'stack diagrams', 'stack diagram', 'global variable', 'function parenthesis', 'function definition']","In programming, what is the difference between a local and a global variable? ","A local variable can only be accessed within the scope of the function in which it is defined, whereas a global variable can be accessed from any part of the program."
47,03-15-learn-with-videos-6,03,15,Learn with Videos,"<YoutubeVideo src=""https://www.youtube.com/embed/seLcRCulwl4?start=1018""></YoutubeVideo>",,learn-with-videos-6,,[],,
48,03-18-variables-and-parameters-are-local,03,18,Variables and parameters are local,"When you create a variable inside a function, it is **local**, which means that
it only exists inside the function. For example:
```python
def cat_twice(part1, part2):
cat = part1 + part2
print_twice(cat)
```
This function takes two arguments, concatenates them, and prints the result twice. Here is an example that uses it:
```python
>>> line1 = 'Bing tiddle '
>>> line2 = 'tiddle bang.'
>>> cat_twice(line1, line2)
Bing tiddle tiddle bang. Bing tiddle tiddle bang.
```
When `cat_twice` terminates, the variable cat is destroyed. If we try to
print it, we get an exception:
```python
>>> print cat NameError: name 'cat' is not defined
```
Parameters are also local. For example, outside `print_twice`, there is no such thing as bruce.","When you create a variable inside a function, it is local, which means that
it only exists inside the function. For example:
def cat_twice(part1, part2):
cat = part1 + part2
print_twice(cat)
This function takes two arguments, concatenates them, and prints the result twice. Here is an example that uses it:
>>> line1 = 'Bing tiddle '
>>> line2 = 'tiddle bang.'
>>> cat_twice(line1, line2)
Bing tiddle tiddle bang. Bing tiddle tiddle bang.
When cat_twice terminates, the variable cat is destroyed. If we try to
print it, we get an exception:
>>> print cat NameError: name 'cat' is not defined
Parameters are also local. For example, outside print_twice, there is no such thing as bruce.",variables-and-parameters-are-local,"
Answer:
{
""question"": ""What is the scope of a variable defined inside a function?"",
""answer"": ""The scope of a variable defined inside a function is local, meaning that it only exists inside the function.""
}","['local variables', 'bruce keywords', 'concatenated function', 'local variable']",What is the scope of a variable defined inside a function?,"The scope of a variable defined inside a function is local, meaning that it only exists inside the function."
49,03-19-learn-with-videos-8,03,19,Learn with Videos,"<YoutubeVideo
title=""stack diagram""
src=""https://www.youtube.com/embed/Ol3Dwucax9U?start=298""
>
To keep track of which variables can be used where, it is sometimes useful to
draw a **stack diagram**.
</YoutubeVideo>",so this is a stack diagram which means how the execution flow goes we have main get twice and print wise we already saw prints twice and CAD wise which are the functions which we defined but we didn't seem a main main is a special name which is used as an entry point for problems Python you can see the variables which are in the scope of main line 1 and line 2 and their values then you can see the function get wise its arguments and variables and their values and finally you can see print twice and again it's argument so let's see here we have kept wise part 1 part 2 and cat we have print twice and bruised and finally this is the entry point where we indicate the function and you can see it here which is the main then we have the rest of the functions why this is important because when you run your problems you may see a trace back which is giving you information where a given never happened and you can see the entry points the functions and also the files where this happened and on which line and this is exactly how the program flow is going on and when you need to find a problem with much more and much complex and bigger problem problems you will need to understand how this is working and I will do a quick demonstration a bit later so we can continue with fruitful and avoid functions let's check fruitful and void function,learn-with-videos-8,"
Here is the output:
{""question"": ""What is the purpose of a main function?"", ""answer"": ""The main function is a special name used as an entry point for problems in Python, indicating the functions, variables, and values in the scope of the program.""}","['program debugging', 'programming language', 'program analysis', 'stack diagrams', 'stack diagram', 'program flow']",What is the purpose of a main function?,"The main function is a special name used as an entry point for problems in Python, indicating the functions, variables, and values in the scope of the program."
50,03-20-stack-diagrams,03,20,Stack diagrams,"Like state diagrams, stack diagrams show the value of each variable, but they
also show the function each variable belongs to.
Each function is represented by a frame. A frame is a box with the name of a function beside it and the parameters and variables of the function inside it. The stack diagram for the previous example is shown in Figure [3.1](#figure3.1)
<Image
alt=""Stack diagram.""
src=""https://www.greenteapress.com/thinkpython/html/thinkpython004.png""
>
Figure 3.1: Stack diagram.
</Image>
The frames are arranged in a stack that indicates which function called which, and
so on. In this example, `print_twice` was called by `cat_twice`, and `cat_twice`
was called by `__main__`, which is a special name for the topmost frame. When you
create a variable outside of any function, it belongs to `__main__`.
Each parameter refers to the same value as its corresponding argument. So, part1 has the same value as line1, part2 has the same value as line2, and bruce has the same value as cat.
If an error occurs during a function call, Python prints the name of the function, and the name of the function that called it, and the name of the function that called that, all the way back to `__main__`.
For example, if you try to access cat from within `print_twice`, you get a `NameError`:
```python
Traceback (innermost last):
File ""test.py"", line 13, in __main__
cat_twice(line1, line2)
File ""test.py"", line 5, in cat_twice
print_twice(cat)
File ""test.py"", line 9, in print_twice
print cat
NameError: name 'cat' is not defined
```
This list of functions is called a **traceback**. It tells you what program file the error occurred in, and what line, and what functions were executing at the time. It also shows the line of code that caused the error.
The order of the functions in the traceback is the same as the order of the frames in the stack diagram. The function that is currently running is at the bottom.","Like state diagrams, stack diagrams show the value of each variable, but they
also show the function each variable belongs to.
Each function is represented by a frame. A frame is a box with the name of a function beside it and the parameters and variables of the function inside it. The stack diagram for the previous example is shown in Figure 3.1
<Image
alt=""Stack diagram.""
src=""https://www.greenteapress.com/thinkpython/html/thinkpython004.png""
Figure 3.1: Stack diagram.
The frames are arranged in a stack that indicates which function called which, and
so on. In this example, print_twice was called by cat_twice, and cat_twice
was called by __main__, which is a special name for the topmost frame. When you
create a variable outside of any function, it belongs to __main__.
Each parameter refers to the same value as its corresponding argument. So, part1 has the same value as line1, part2 has the same value as line2, and bruce has the same value as cat.
If an error occurs during a function call, Python prints the name of the function, and the name of the function that called it, and the name of the function that called that, all the way back to __main__.
For example, if you try to access cat from within print_twice, you get a NameError:
Traceback (innermost last):
File ""test.py"", line 13, in __main__
cat_twice(line1, line2)
File ""test.py"", line 5, in cat_twice
print_twice(cat)
File ""test.py"", line 9, in print_twice
print cat
NameError: name 'cat' is not defined
This list of functions is called a traceback. It tells you what program file the error occurred in, and what line, and what functions were executing at the time. It also shows the line of code that caused the error.
The order of the functions in the traceback is the same as the order of the frames in the stack diagram. The function that is currently running is at the bottom.",stack-diagrams,"
Question: What is a traceback and what does it tell you?
Answer: A traceback is a list of functions that tells you what program file the error occurred in, and what line, and what functions were executing at the time, as well as the line of code that caused the error.","['state diagram key words', 'state diagram', 'stack diagram', 'function call', 'traceback']",What is a traceback and what does it tell you?,"A traceback is a list of functions that tells you what program file the error occurred in, and what line, and what functions were executing at the time, as well as the line of code that caused the error."
51,03-21-learn-with-videos-9,03,21,Learn with Videos,"<YoutubeVideo src=""https://www.youtube.com/embed/Ol3Dwucax9U?start=416"">
Some of the functions we are using, such as the math functions, yield results;
for lack of a better name, I call them **fruitful functions**. Other
functions, like print_twice, perform an action but don't return a value. They
are called **void functions**.
</YoutubeVideo>",according to the author of the book a fruitful function is a function which returns a result and a void function is a function which doesn't return a result so you can think for this in this way let's import but this is a model a model with collection of useful functions and you can import the model and then access any functions first from this model by using dot notation so we have the model named dot and the name of the function and we are giving some parameters for this function here we have radians which has a value 50 and this statement executes the function and assign the result to variable X in this statement here we have function mod square we have argument 5 we add 1 and Devine to 2 and let's check the result as you can see for X we have this value and for golden we have the golden ratio the famous one which is presented here and as you can see mod Square 5 returns to point 2 and some curves and these functions are fruitful because they returned variable or value from their executions and let's check print twice the function that we'd find already earlier and I will remove also this because we don't need it and let's execute the function with print twice and and assign the result from the function to variable which name is a result let's check what's going to happen with this result if we try to check the value we have noting let's print this result we have none and let's check the type of this a result we have non type so if you are confused don't worry I will try to make your confusion a bit less so we have this function in the function we have print another function which is producing output to the console or to the output cell but then we are trying to get something from this function and assign it to a variable result and this cannot happen because this function doesn't return anything it's just print to the console in order to return anything from this function we need to use a special keyword return and then provide what is going to be returned for example a string X and let's try the same again this time we have result X we don't have empty cell we have print result X and we have string as an output you can return even integers for example let's try to return one and as you can see again we have result you can return statements for example one plus four and as you can see this is working fine but if you remove the return statement from any function then you return norm which is a special type in Python it says that I don't know what is inside this variable it's not defined yet and I cannot produce it this is the meaning of none and we'll speak again for it in the future videos I want those who to mention that sometimes you may have a functions which returns our result sometimes and they don't return in some situations for example this function can return the result if our given condition is met for example let's say that if Bruce is equal to 1 we all return X and otherwise we will not return it so let's check what is going to happen we don't return any results of our and let's provide 1 here and check right now as you can see we return the result which is X so you have a fruitful functions you have avoid functions and you can have one mixed situation where you have a return result for some situations and known and without result for some situations in general I don't advise you for this because this can be misleading for some programmers I prefer to have simple and easier to read problems and let's move on the next chapter which is why to use,learn-with-videos-9,"
Question: What is the difference between fruitful and void functions?
Answer: Fruitful functions return a result, while void functions do not return a result.","['return statement', 'return function', 'return result', 'fruitful function', 'void function', 'return norm', 'mixed situation', 'avoid function', 'function mod square']",What is the difference between fruitful and void functions? ,"Fruitful functions return a result, while void functions do not return a result."
52,03-22-fruitful-functions-and-void-functions,03,22,Fruitful functions and void functions,"When you call a fruitful function, you almost always want to do something with the
result; for example, you might assign it to a variable or use it as part of an expression:
```python x = math.cos(radians) golden = (math.sqrt(5) + 1) / 2 ``` When you call
a function in interactive mode, Python displays the result: ```python >>> math.sqrt(5)
2.2360679774997898 ``` But in a script, if you call a fruitful function all by itself,
the return value is lost forever! ```python math.sqrt(5) ``` This script computes
the square root of 5, but since it doesn't store or display the result, it is not
very useful.
Void functions might display something on the screen or have some other effect, but they don't have a return value. If you try to assign the result to a variable, you get a special value called None.
```python
>>> result = print_twice('Bing')
Bing
Bing
>>> print result
None
```
The value None is not the same as the string 'None'. It is a special value that has its own type:
```python
>>> print type(None)
<type 'NoneType'>
```
The functions we have written so far are all void. We will start writing fruitful functions in a few chapters.","When you call a fruitful function, you almost always want to do something with the
result; for example, you might assign it to a variable or use it as part of an expression:
python x = math.cos(radians) golden = (math.sqrt(5) + 1) / 2 When you call
a function in interactive mode, Python displays the result: python >>> math.sqrt(5)
2.2360679774997898 But in a script, if you call a fruitful function all by itself,
the return value is lost forever! python math.sqrt(5) This script computes
the square root of 5, but since it doesn't store or display the result, it is not
very useful.
Void functions might display something on the screen or have some other effect, but they don't have a return value. If you try to assign the result to a variable, you get a special value called None.
>>> result = print_twice('Bing')
Bing
Bing
>>> print result
None
The value None is not the same as the string 'None'. It is a special value that has its own type:
>>> print type(None)
<type 'NoneType'>
The functions we have written so far are all void. We will start writing fruitful functions in a few chapters.",fruitful-functions-and-void-functions,"
Question: What is the type of the special value None?
Answer: The type of the special value None is NoneType.","['void function', 'special value', 'function call', 'interactive mode', 'fertile function']",What is the type of the special value None?,The type of the special value None is NoneType.
53,03-23-learn-with-videos-10,03,23,Learn with Videos,"<YoutubeVideo src=""https://www.youtube.com/embed/Ol3Dwucax9U?start=735""></YoutubeVideo>",functions so first of all functions allow you to group statements and this is going to make your programs easier to read and the book this is really important 110 you may write it somewhere and check it in the future after that your problems will become small and this is going to eliminate the repetitive code or there is one special how to say Roman programming which is dry and the idea of this is to avoid to repeat yourself which is saying do not repeat yourself and using a functions is a good way to avoid this bad practice I will share in the description below so you can again make your changes easier for example let's say that we have this function prints twice several times and this time we want to change this behavior and if we have a function we can change it very easily on one place but if instead of this function we have this behavior repeated many times for example let's say repeated sorry repeat several times then you need to go and repeat the same change on each place in the code where these changes need to be applied and if you have a function you do it only on one place and also as you can see this code is much more complex and it's taking much more lines instead of these free invocations and this is much more easier to be read ok let's remove this then you can iterate a logical parts and units for your program which means that you will have one function which is calculating the square another which is doing a print and third which is doing something else and you can follow them very easily and if you have thousands of lines of code this is not possible and finally I want to say that well-designed functions will do your program more useful easier to read and you spend less time if you need to do some maintenance and that's all why you need to use functions let's move from the bank why,learn-with-videos-10,"
Question: What are the benefits of using functions in programming?
Answer: Using functions in programming allows group statements to be read more easily, eliminates the need for repetitive code, and makes code easier to read and maintain.","['programming language', 'repetitive code', 'group statement', 'functional programming', 'function print']",What are the benefits of using functions in programming? ,"Using functions in programming allows group statements to be read more easily, eliminates the need for repetitive code, and makes code easier to read and maintain."
54,03-24-why-functions,03,24,Why functions?,"It may not be clear why it is worth the trouble to divide a program into
functions. There are several reasons:
- Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read and debug.
- Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place.
- Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole.
- Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it.","It may not be clear why it is worth the trouble to divide a program into
functions. There are several reasons:
Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read and debug.
Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place.
Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole.
Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it.",why-functions,"
Quesiton: What is the benefit of creating a new function when programming?
Answer: Creating a new function gives the opportunity to name a group of statements, which makes the program easier to read and debug.","['repet', 'new function', 'repetitive code', 'welldesigned function', 'long program']",Quesiton: What is the benefit of creating a new function when programming?,"Creating a new function gives the opportunity to name a group of statements, which makes the program easier to read and debug."
55,03-25-importing-with-from,03,25,Importing with `from`,"Python provides two ways to import modules; we have already seen one:
```python
>>> import math
>>> print math
&lt;module 'math' (built-in)&gt;
>>> print math.pi
3.14159265359
```
If you import math, you get a module object named math. The module object contains constants like pi and functions like sin and exp.
But if you try to access pi directly, you get an error.
```python
>>> print pi
Traceback (most recent call last):
File ""<stdin>"", line 1, in <module>
NameError: name 'pi' is not defined
```
As an alternative, you can import an object from a module like this:
```python
>>> from math import pi
```
Now you can access pi directly, without dot notation.
```python
>>> print pi
3.14159265359
```
Or you can use the star operator to import everything from the module:
```python
>>> from math import *
>>> cos(pi)
-1.0
```
The advantage of importing everything from the math module is that your code can be more concise. The disadvantage is that there might be conflicts between names defined in different modules, or between a name from a module and one of your variables.","Python provides two ways to import modules; we have already seen one:
>>> import math
>>> print math
&lt;module 'math' (built-in)&gt;
>>> print math.pi
3.14159265359
If you import math, you get a module object named math. The module object contains constants like pi and functions like sin and exp.
But if you try to access pi directly, you get an error.
>>> print pi
Traceback (most recent call last):
File ""<stdin>"", line 1, in <module>
NameError: name 'pi' is not defined
As an alternative, you can import an object from a module like this:
>>> from math import pi
Now you can access pi directly, without dot notation.
>>> print pi
3.14159265359
Or you can use the star operator to import everything from the module:
>>> from math import *
>>> cos(pi)
-1.0
The advantage of importing everything from the math module is that your code can be more concise. The disadvantage is that there might be conflicts between names defined in different modules, or between a name from a module and one of your variables.",importing-with-from,"
Question: What is the benefit of using the ""from math import *"" syntax?
Answer: The benefit of using the ""from math import *"" syntax is that it allows for more concise code, while potentially introducing the risk of conflicts between names defined in different modules or between a name from a module and one of your variables.
Output JSON instance: {""question"": ""What is the benefit of using the \""from math import *\"" syntax?"", ""answer"": ""The benefit of using the \""from math import *\"" syntax is that it allows for more concise code, while potentially introducing the risk of conflicts between names defined in different modules or between a name from a module and one of your variables.""}","['builtin module', 'different', 'import module', 'star operator', 'module object', 'different module']","What is the benefit of using the ""from math import *"" syntax?","The benefit of using the ""from math import *"" syntax is that it allows for more concise code, while potentially introducing the risk of conflicts between names defined in different modules or between a name from a module and one of your variables."
56,03-26-learn-with-videos-11,03,26,Learn with Videos,"<YoutubeVideo src=""https://www.youtube.com/embed/Ol3Dwucax9U?start=911""></YoutubeVideo>",the bugging it's important and what's actually being the author of the book said that it's like detective work you need to find to what and how happened for this piece of code so let's start with a simple problem we have repeat lyrics we have print lyrics one three and two and let's execute this program and for example you can see that we have one three and two we want to say why we have this result and why we don't have one two and three in order to understand this we can do a debugging we'll go with the entry point for this program in Python you can execute the program with shift f10 and you can debug it with shift f9 so we are starting at the book mode you can see the trace back here which is shown in Python and some special variables here we will step into this function in order to see the execution flow you can see here repeat lyrics the name of the file and the line then we'll go one level deeper you can see again that we have print lyrics one the filename and the line of the code and in this way you can see how the execution flow is going you can also skip a given function and get all the result with step out and as you can see you will skip the function and we just pass through it but we get the result for this function and again we can do the same for the last function in this way you can work with more complex problems and find where is the problem so as we can so here we have this result because we're indicating the function in this order and let's say that you have this situation here you expect to have 1 2 & 3 as an output and you have it but let's say that someone is doing something birth and he change the values inside these functions and as an output you have 1 3 in queue but you expect to have 1 2 and 3 so we need to the pokken point where is the problem and these functions are not always visible and easier to be understand let's check how we can debug this we can go in the main function then we can debug functions one by one we can see what we're going to happen when the first one and usually we have this function separated in different files folders models and so on and that's why it's really important to understand how you can debug it and see the trace back of the program here we have 1 which is the expected result we are going into the second one where the problem cap is going to happen and here we can see why the problem is wrong and why we have a bad result and this is the idea of the the book once we know that we have problem we can stop the debugging mode and we can run out from each of these functions and we can correct the problem okay so does being said we can move finally on the glossary and to say again some important parts for functions a function is named seconds of statement which is crucial for programming we saw what is a function definition we saw that if we don't execute the function we have only a function object which is created for us and we can execute it later we saw a header and a body so this is the header of the function this is the body of the function we saw an argument a local variable a fruitful and void function so this function is going to be a fruitful which if it is returning a result and what if it doesn't return a return our result this is an argument and finally the augmentation that you can access functions from different models by using dot notation which is shown here what is the model which is important outside and we have the function name and the trace back which is important finally you can see some exercises for homework you can try to look them they are really nice and you can train your programming skills with them finally I want to say thank you for your good words and the likes that you are giving me and I want to share with you some of the latest videos from this channel you can select some of them if you like them and check them I am trying to do interesting video material for all of you but if you have any ideas suggestions or topics please do share them and I will try to follow them and it should represent almost all my videos which are published so far you can see some work related to linux some are related peyten some are related by jerem and bundles I will share this link a bit later so you are able to access it and browse my videos in easier and nicer way for you if you click on any of these videos you can watch it and do something with it if you want to see more videos about programming books and some interesting topics about programming please do subscribe thank you for watching and see you next time,learn-with-videos-11,"
Question: What is the trace back feature in Python and how is it important for debugging?
Answer: The trace back in Python is a feature that shows the sequence of execution flow of a program and it is important for debugging because it helps to identify the source of the problem and why a certain result is being generated.","['the bugging its important and whats actually being the author of the book said that', 'interesting work', 'programming book', 'interesting topic', 'programming skill', 'interesting video material']",What is the trace back feature in Python and how is it important for debugging?,The trace back in Python is a feature that shows the sequence of execution flow of a program and it is important for debugging because it helps to identify the source of the problem and why a certain result is being generated.
57,03-27-debugging,03,27,Debugging,"If you are using a text editor to write your scripts, you might run into
problems with spaces and tabs. The best way to avoid these problems is to use
spaces exclusively (no tabs). Most text editors that know about Python do this
by default, but some don't.
Tabs and spaces are usually invisible, which makes them hard to debug, so try to find an editor that manages indentation for you.
Also, don't forget to save your program before you run it. Some development environments do this automatically, but some don't. In that case the program you are looking at in the text editor is not the same as the program you are running.
Debugging can take a long time if you keep running the same, incorrect, program over and over!
Make sure that the code you are looking at is the code you are running. If you're not sure, put something like `print 'hello'` at the beginning of the program and run it again. If you don't see `hello`, you're not running the right program!","If you are using a text editor to write your scripts, you might run into
problems with spaces and tabs. The best way to avoid these problems is to use
spaces exclusively (no tabs). Most text editors that know about Python do this
by default, but some don't.
Tabs and spaces are usually invisible, which makes them hard to debug, so try to find an editor that manages indentation for you.
Also, don't forget to save your program before you run it. Some development environments do this automatically, but some don't. In that case the program you are looking at in the text editor is not the same as the program you are running.
Debugging can take a long time if you keep running the same, incorrect, program over and over!
Make sure that the code you are looking at is the code you are running. If you're not sure, put something like print 'hello' at the beginning of the program and run it again. If you don't see hello, you're not running the right program!",debugging,"
Answer:
{""question"": ""What is the best way to avoid problems with spaces and tabs when writing a script?"", ""answer"": ""The best way to avoid these problems is to use spaces exclusively (no tabs).""}","['development environmentprogram debugging', 'program debugging', 'programming language', 'development environment', 'text editor']",What is the best way to avoid problems with spaces and tabs when writing a script?,The best way to avoid these problems is to use spaces exclusively (no tabs).
58,03-28-exercises,03,28,Exercises,,,exercises,"
Here is an example of the passage:
""The Civil War was fought in the United States from 1861 to 1865 and it pitted the Union forces against the Confederate forces.""
Answer:
{""question"": ""What years did the Civil War take place in the US?"", ""answer"": ""The Civil War took place in the US from 1861 to 1865.""}",[],,
59,03-29-exercise-3,03,29,Exercise 3,"<Exercise>
Python provides a built-in function called len that returns the length of a string, so the value of `len('allen')` is 5.
Write a function named `right_justify` that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.
```python
>>> right_justify('allen')
```
</Exercise>","Python provides a built-in function called len that returns the length of a string, so the value of len('allen') is 5.
Write a function named right_justify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.
>>> right_justify('allen')",exercise-3,"
Here is the well-formatted instance of the schema:
```
{""question"": ""What function would you use in Python to print a string with the last letter of the string in column 70 of the display?"", ""answer"": ""You would use the function right_justify.""}
```","['built in function', 'rightjustify', 'builtin functions', 'leading space', 'python']",What function would you use in Python to print a string with the last letter of the string in column 70 of the display?,You would use the function right_justify.
60,03-30-exercise-4,03,30,Exercise 4,"<Exercise>
A function object is a value you can assign to a variable or pass as an argument. For example, do_twice is a function that takes a function object as an argument and calls it twice:
```python
def do_twice(f):
f()
f()
```
Here's an example that uses `do_twice` to call a function named `print_spam` twice.
```python
def print_spam():
print 'spam'
do_twice(print_spam)
```
1. Type this example into a script and test it.
2. Modify do_twice so that it takes two arguments, a function object and a value, and calls the function twice, passing the value as an argument.
3. Write a more general version of print_spam, called print_twice, that takes a string as a parameter and prints it twice.
4. Use the modified version of do_twice to call print_twice twice, passing 'spam' as an argument.
5. Define a new function called do_four that takes a function object and a value and calls the function four times, passing the value as a parameter. There should be only two statements in the body of this function, not four.
Solution: http://thinkpython.com/code/do_four.py.
</Exercise>","A function object is a value you can assign to a variable or pass as an argument. For example, do_twice is a function that takes a function object as an argument and calls it twice:
def do_twice(f):
f()
f()
Here's an example that uses do_twice to call a function named print_spam twice.
def print_spam():
print 'spam'
do_twice(print_spam)
Type this example into a script and test it.
Modify do_twice so that it takes two arguments, a function object and a value, and calls the function twice, passing the value as an argument.
Write a more general version of print_spam, called print_twice, that takes a string as a parameter and prints it twice.
Use the modified version of do_twice to call print_twice twice, passing 'spam' as an argument.
Define a new function called do_four that takes a function object and a value and calls the function four times, passing the value as a parameter. There should be only two statements in the body of this function, not four.
Solution: http://thinkpython.com/code/do_four.py.",exercise-4,"
{""question"": ""What is the output of the code in the do_four.py file?"",
""answer"": ""The code in the do_four.py file will call the function print_twice twice, passing 'spam' as an argument, and then print 'spam' four times in total.""}","['new function', 'general version', 'function object is a value', 'function four times', 'function object']",What is the output of the code in the do_four.py file?,"The code in the do_four.py file will call the function print_twice twice, passing 'spam' as an argument, and then print 'spam' four times in total."
61,03-31-exercise-5,03,31,Exercise 5,"<Exercise>
This exercise can be done using only the statements and other features we have learned so far.
1. Write a function that draws a grid like the following:
```
+ - - - - + - - - - +
/ / /
/ / /
/ / /
/ / /
+ - - - - + - - - - +
/ / /
/ / /
/ / /
/ / /
+ - - - - + - - - - +
```
Hint: to print more than one value on a line, you can print a comma-separated sequence:
```python
print '+', '-'
```
If the sequence ends with a comma, Python leaves the line unfinished, so the value printed next appears on the same line.
```python
print '+',
print '-'
```
The output of these statements is '+ -'.
A print statement all by itself ends the current line and goes to the next line.
2. Write a function that draws a similar grid with four rows and four columns.
Solution: http://thinkpython.com/code/grid.py. Credit: This exercise is based on an exercise in Oualline, Practical C Programming, Third Edition, O'Reilly Media, 1997.
</Exercise>
","This exercise can be done using only the statements and other features we have learned so far.
Write a function that draws a grid like the following:
+ - - - - + - - - - +
/ / /
/ / /
/ / /
/ / /
+ - - - - + - - - - +
/ / /
/ / /
/ / /
/ / /
+ - - - - + - - - - +
Hint: to print more than one value on a line, you can print a comma-separated sequence:
python
print '+', '-'
If the sequence ends with a comma, Python leaves the line unfinished, so the value printed next appears on the same line.
python
print '+',
print '-'
The output of these statements is '+ -'.
A print statement all by itself ends the current line and goes to the next line.
Write a function that draws a similar grid with four rows and four columns.
Solution: http://thinkpython.com/code/grid.py. Credit: This exercise is based on an exercise in Oualline, Practical C Programming, Third Edition, O'Reilly Media, 1997.",exercise-5,"
{""properties"": {""question"": {""title"": ""Question"", ""description"": ""question"", ""type"": ""string""}, ""answer"": {""title"": ""Answer"", ""description"": ""answer"", ""type"": ""string""}}, ""required"": [""question"", ""answer""], ""question"": ""What is the output of the following Python statements?"", ""answer"": ""The output of these statements is '+ -'.""}","['c programming', 'practical c programming', 'programming language', 'computer science', 'code generation']",What is the output of the following Python statements?,The output of these statements is '+ -'.
62,03-00-learn-with-videos,03,0,Learn with Videos,"<YoutubeVideo
title=""Functions""
src=""https://www.youtube.com/embed/seLcRCulwl4?start=643""
>
In the context of programming, a **function** is a named sequence of
statements that performs a computation. When you define a function, you
specify the name and the sequence of statements. Later, you can ""call"" the
function by name.
</YoutubeVideo>",,learn-with-videos,,[],,
63,03-07-learn-with-videos-3,03,7,Learn with Videos,"So far, we have only been using the functions that come with Python, but it is also possible to add new functions.
<YoutubeVideo src=""https://www.youtube.com/embed/seLcRCulwl4?start=668"">
A function definition specifies the name of a new function and the sequence of
statements that execute when the function is called.
</YoutubeVideo>",,learn-with-videos-3,,[],,
64,03-13-learn-with-videos-5,03,13,Learn with Videos,"<YoutubeVideo
title=""Execution Flow""
src=""https://www.youtube.com/embed/seLcRCulwl4?start=931""
>
In order to ensure that a function is defined before its first use, you have
to know the order in which statements are executed, which is called the **flow
of execution**.
</YoutubeVideo>",,learn-with-videos-5,,[],,