- Books Never Written Math Beginning Your Exercise Program By Year
- Beginning Your Exercise Program By Math
- Books Never Written Math Beginning Your Exercise Program By Walking One Mile
Books Never Written Joke for All scouts Cub Scouts Webelos Boy Scouts My Blog. Activities Advancements Awards. 'Over the Mountaintop' by Hugo First 'The Numbers Game' by Cal Q. I tell them to my friends and family all the time. But the funniest part is when I tell them a book never written and they bust out laughing. Books never written math worksheet answers my long life in crime generated on lbartman.com show printable version!!! Hide the show to save images bellow, right click on shown image then save as.png. The 10 Best Self-Help Books You’ve (Probably) Never Heard Of. (deceptively) simple exercise of itemizing your desires in a list. If approached with maturity, Jarrett’s exercise amounts to a personal inventory-taking and a meaningful assessment of one’s true aims. — This pioneering work written by a Swedenborgian. Book publishers,top selling authors,top selling books,best book authors,best short story writers,essay topics,new book titles,source of new books,weird books,best selling books,discount book supply,librarian jobs. “How To Exercise” by Eileen and Ben Dover. Send your “Books Never Written.
Ian Stewart is an Emeritus Professor of Mathematics at Warwick University and a Fellow of the Royal Society. He has written over 80 books, mainly popular mathematics, and has won three gold medals for his work on the public understanding of science. In collaboration with Terry Pratchett and Jack Cohen he wrote the Science of Discworld series. His new book, 17 Equations That Changed the World, is published by Profile.
'Popular mathematics' may sound like a contradiction in terms. That's what makes the genre so important: we have to change that perception. Mathematics is the Cinderella science: undervalued, underestimated, and misunderstood. Yet it has been one of the main driving forces behind human society for at least three millennia, it powers all of today's technology, and it underpins almost every aspect of our daily lives.
'It's not really surprising that few outside the subject appreciate it, though. School mathematics is so focused on getting the right answer and passing the exam that there is seldom an opportunity to find out what it's all for. The hard core of real mathematics is extremely difficult, and it takes six or seven years to train a research mathematician after they leave school. Popular mathematics provides an entry route for non-specialists. It allows them to appreciate where mathematics came from, who created it, what it's good for, and where it's going, without getting tangled up in the technicalities. It's like listening to music instead of composing it.
'There are many ways to make real mathematics accessible. Its history reveals the subject as a human activity and gives a feel for the broad flow of ideas over the centuries. Biographies of great mathematicians tell us what it's like to work at the frontiers of human knowledge. The great problems, the ones that hit the news media when they are finally solved after centuries of effort, are always fascinating. So are the unsolved ones and the latest hot research areas. The myriad applications of mathematics, from medicine to the iPad, are an almost inexhaustible source of inspiration.'
1. The Man Who Knew Infinity by Robert Kanigel
The self-taught Indian genius Srinivasa Ramanujan had a flair for strange and beautiful formulas, so unusual that mathematicians are still coming to grips with their true meaning. He was born into a poor Brahmin family in 1887 and was pursuing original research in his teens. In 1912, he was brought to work at Cambridge. He died of malnutrition and other unknown causes in 1920, leaving a rich legacy that is still not fully understood. There has never been another mathematical life story like it: absolutely riveting.
2. Gödel, Escher, Bach by Douglas Hofstadter
One of the great cult books, a very original take on the logical paradoxes associated with self-reference, such as 'this statement is false'. Hofstadter combines the mathematical logic of Kurt Gödel, who proved that some questions in arithmetic can never be answered, with the etchings of Maurits Escher and the music of Bach. Frequent dramatic dialogues between Lewis Carroll's characters Achilles and the Tortoise motivate key topics in a highly original manner, along with their friend Crab who invents the tortoise-chomping record player. DNA and computers get extensive treatment too.
3. The Colossal Book of Mathematics by Martin Gardner
In his long-running Mathematical Games column in Scientific American, Gardner – a journalist with no mathematical training – created the field of recreational mathematics. On the surface his columns were about puzzles and games, but they all concealed mathematical principles, some simple, some surprisingly deep. He combined a playful and clear approach to his subject with a well-developed taste for what was mathematically significant. The book consists of numerous selections from his columns, classified according to the mathematical area involved. Learn how to make a hexaflexagon and why playing Brussels sprouts is a waste of time.
4. Euclid in the Rainforest by Joseph Mazur
A thoroughly readable account of the meaning of truth in mathematics, presented through a series of quirky adventures in the Greek Islands, the jungles around the Orinoco River, and elsewhere. Examines tricky concepts like infinity, topology, and probability through tall tales and anecdotes. Three different kinds of truth are examined: formal classical logic, the role of the infinite, and inference by plausible reasoning. The story of the student who believed nothing except his calculator is an object lesson for everyone who thinks mathematics is just 'sums'.
5. Four Colours Suffice by Robin Wilson
In 1852 Francis Guthrie, a young South African mathematician, was attempting to colour the counties in a map of England. Guthrie discovered that he needed only four different colours to ensure that any two adjacent counties had different colours. After some experimentation he convinced himself that the same goes for any map whatsoever. This is the remarkable story of how mathematicians eventually proved he was right, but only with the aid of computers, bringing into question the meaning of 'proof'. It contains enough detail to be satisfying, but remains accessible and informative throughout.
6. What is Mathematics Really? by Reuben Hersh
The classic text What is Mathematics? by Richard Courant and Herbert Robbins focused on the subject's nuts and bolts. It answered its title question by example. Hersh takes a more philosophical view, based on his experience as a professional mathematician. The common working philosophy of most mathematicians is a kind of vague Platonism: mathematical concepts have some sort of independent existence in some ideal world. Although this is what it feels like to insiders, Hersh argues that mathematics is a collective human construct – like money or the Supreme Court. However, it is a construct constrained by its own internal logic; it's not arbitrary. You choose the concepts that interest you, but you don't get to choose how they behave.
7. Magical Mathematics by Persi Diaconis and Ron Graham
Both authors are top-rank mathematicians with years of stage performances behind them, and their speciality is mathematical magic. They show how mathematics relates to juggling and reveal the secrets behind some amazing card tricks. Here's one. The magician mails a pack of cards to anyone, asking them to shuffle it and choose a card. Then he shuffles the cards again, and mails half of them to the magician—not saying whether the chosen card is included. By return mail, the magician names the selected card. No trickery: it all depends on the mathematics of shuffles.
8. Games of Life by Karl Sigmund
Biologists' understanding of many vital features of the living world, such as sex and survival, depends on the theory of evolution. One of the basic theoretical tools here is the mathematics of game theory, in which several players compete by choosing from a list of possible strategies. The children's game of rock-paper-scissors is a good example. The book illuminates such questions as how genes spread through a population and the evolution of cooperation, by finding the best strategies for games such as cat and mouse, the battle of the sexes, and the prisoner's dilemma. On the borderline between popular science and an academic text, but eminently readable without specialist knowledge.
9. Mathenauts: Tales of Mathematical Wonder edited by Rudy Rucker
A collection of 23 science fiction short stories, each of which centres on mathematics. Two are by Martin Gardner, and many of the great writers of SF are represented: Isaac Asimov, Gregory Benford, Larry Niven, Frederik Pohl. The high point is Norman Kagan's utterly hilarious 'The Mathenauts', in which only mathematicians can travel through space, because space is mathematical – and, conversely, anything mathematical can be reality. An isomorphomechanism is essential equipment. Between them, these tales cover most of the undergraduate mathematics syllabus, though not in examinable form.
10. The Mathematical Principles of Natural Philosophy by Isaac Newton
There ought to be a great classic in this top 10, and there is none greater. I've put it last because it's not popularisation in the strict sense. However, it slips in because it communicated to the world one of the very greatest ideas of all time: Nature has laws, and they can be expressed in the language of mathematics. Using nothing more complicated than Euclid's geometry, Newton developed his laws of motion and gravity, applying them to the motion of the planets and strange wobbles in the position of the Moon. He famously said that he 'stood on the shoulders of giants', and so he did, but this book set the scientific world alight. As John Maynard Keyes wrote, Newton was a transitional figure of immense stature: 'the last of the magicians … the last wonderchild to whom the Magi could do sincere and appropriate homage.' No mathematical book has had more impact.
- 1Preface
- 1.1Chapter 0: Preface
- 2The way of the program
- 2.3What is debugging?
- 2.8Exercises
- 3Variables, expressions and statements
- 3.2Variables
- 3.6Expressions
- 3.12Exercises
- 4Functions
- 4.6Definitions and uses
- 4.15Exercises
- 5Case study: interface design
- 6Conditional and recursion
- 7Fruitful functions
- 7.1Return values
- 7.2Incremental development
- 7.11Exercises
- 8Iteration
- 8.9Exercises
- 9Strings
- 9.3Traversal with a for loop
- 9.4String slices
- 9.6Searching
- 9.13Exercises
- 10Case study: word play
- 10.7Exercises
- 11Lists
- 11.7Map, filter and reduce
- 11.12List arguments
- 11.15Exercises
- 12Dictionaries
- 12.2Dictionary as a set of counters
- 12.3Looping and dictionaries
- 12.5Dictionaries and lists
- 12.6Memos
- 12.8Long integers
- 12.11Exercise-8
- 13Tuples
- 13.4Variable-length argument tuples
- 13.7Comparing tuples
- 13.11Exercises
- 13.12Word frequency analysis
- 13.13Random numbers
- 13.17Dictionary subtraction
- 13.18Random words
- 13.19Markov analysis
- 13.23Exercises
- 14Files
- 14.4Filenames and paths
- 15Classes and objects
- 15.2Attributes
- 15.5Objects are mutable
- 15.6Copying
- 15.9Exercises
- 16Classes and functions
- 16.1Time
- 16.7Exercises
- 17Classes and methods
- 17.2Printing objects
- 17.5The init method
- 17.6The __str__ method
- 17.7Operator overloading
- 17.8Type-based dispatch
- 17.12Exercises
- 18Inheritance
- 18.3Comparing cards
- 18.6Add, remove, shuffle and sort
- 18.8Class diagrams
- 18.11Exercises
- 19Debugging
- 19.1Syntax errors
- 19.2Runtime errors
- 19.2.2My program hangs
- 19.3Semantic errors
- 20Answers
- 20.1Chapter 1
- 20.2Chapter 2
- 20.3Chapter 3
- 20.4Chapter 4
- 20.5Chapter 5
- 20.6Chapter 9
- 20.7Chapter 10
- 20.8Chapter 11
- 20.9Chapter 12
- 20.10Chapter 13
- 20.11Chapter 14
- 20.12Chapter 15
- 20.13Chapter 16
- 20.14Chapter 17
- 20.15Chapter 3.5
- 20.16Appendix B
- 21Index
Chapter 0: Preface[edit]
The strange history of this book[edit]
(This section was written by Allen B. Downey[1])
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 'trapdoor 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 class, I decided to write my own book.
My goals were:
- Keep it short. It is better for students to read 10 pages than read 50 pages.
- Be careful with vocabulary. I tried to minimize the jargon and define each term at first use.
- Build gradually. To avoid trapdoors, 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.
Jeff and I revised the book, incorporated a case study by Chris Meyers, and in 2001 we released How to Think Like a Computer Scientist: Learning with Python, also under the GNU Free Documentation License. As Green Tea Press, I published the book and started selling hard copies through Amazon.com and college book stores. Other books from Green Tea Press are available at greenteapress.com.
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 five years I have continued to develop the book, correcting errors, improving some of the examples and adding material, especially exercises. In 2008 I started work on a major revision—at the same time, I was contacted by an editor at Cambridge University Press who was interested in publishing the next edition. Good timing!
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 removed the material in the last few chapters about the implementation of lists and trees. I still love those topics, but I thought they were incongruent with the rest of the book.
- I added more exercises, ranging from short tests of understanding to a few substantial projects.
- I added a series of case studies—longer examples with exercises, solutions, and discussion. Some of them 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 thinkpython.com.
- I expanded the discussion of programming development plans and basic design patterns.
- The use of Python is more idiomatic. The book is still about programming, not Python, but now I think the book gets more leverage from the language.
I hope you enjoy working with this book, and that it helps you learn to program and think, at least a little bit, likea computer scientist.
Allen B. Downey
Needham MA
Allen Downey is an Associate Professor of Computer Science at the Franklin W. Olin College of Engineering.
Acknowledgements[edit]
First and most importantly, I thank Jeff Elkner, whotranslated my Java book into Python, which got this projectstarted and introduced me to what has turned out to be myfavorite language.
I also thank Chris Meyers, who contributed several sectionsto How to Think Like a Computer Scientist.
And I thank the Free Software Foundation for developingthe GNU Free Documentation License, which helped makemy collaboration with Jeff and Chris possible.
I also thank the editors at Lulu who worked onHow to Think Like a Computer Scientist.
I thank all the students who worked with earlierversions of this book and all the contributors (listedbelow) who sent in corrections and suggestions.
And I thank my wife, Lisa, for her work on this book, and GreenTea Press, and everything else, too.
Contributor List[edit]
More than 100 sharp-eyed and thoughtful readers have sent insuggestions and corrections over the past few years. Theircontributions, and enthusiasm for this project, have been ahuge help.
If you have a suggestion or correction, please send email to feedback@thinkpython.com. If I make a change based on yourfeedback, I will add you to the contributor list(unless you ask to be omitted).
If you include at least part of the sentence theerror appears in, that makes it easy for me to search. Page andsection 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 is helping us prepare to 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 11.9.
- 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 14.6.
- Max Hailperin pointed out a change coming in Python 3.0. 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 they typos.
- Mark Griffiths pointed out a confusing example in Chapter 3.
- Roydan Ongie found an error in my Newton’s method.
The further strange adventures of this book[edit]
In September of 2008, Whiteknight converted the HTML version of 'Think Python' at Green Tea Press[2]to a Wikitext version at Wikibooks[3].Now anyone can improve the text.
- ↑'The strange history of this book'by Allen B. Downey
- ↑'Think Python' at Green Tea Press
- ↑Wikibooks: Think Python
The goal of this book is to teach you to think like acomputer scientist. This way of thinking combines some of the best featuresof mathematics, engineering, and natural science. Like mathematicians,computer scientists use formal languages to denote ideas (specificallycomputations). Like engineers, they design things, assembling componentsinto systems and evaluating tradeoffs among alternatives. Like scientists,they observe the behavior of complex systems, form hypotheses, and testpredictions.
The single most important skill for a computer scientist is problem solving. Problem solving means the ability to formulateproblems, think creatively about solutions, and express a solution clearlyand accurately. As it turns out, the process of learning to program is anexcellent opportunity to practice problem-solving skills. That’s whythis chapter is called, “The way of the program.”
On one level, you will be learning to program, a usefulskill by itself. On another level, you will use programming as a means toan end. As we go along, that end will become clearer.
The Python programming language[edit]
The programming language you will learn is Python. Python isan example of a high-level language; other high-level languagesyou might have heard of are C, C++, Perl, and Java.
There are also low-level languages, sometimes referred to as “machinelanguages” or “assembly languages.” Loosely speaking, computerscan only execute programs written in low-level languages. Soprograms written in a high-level language have to be processed beforethey can run. This extra processing takes some time, which is a smalldisadvantage of high-level languages.
The advantages are enormous. First, it is much easier to programin a high-level language. Programs written in a high-level languagetake less time to write, they are shorter and easier to read, and theyare more likely to be correct. Second, high-level languages are portable, meaning that they can run on different kinds of computerswith few or no modifications. Low-level programs can run on only onekind of computer and have to be rewritten to run on another.
Due to these advantages, almost all programs are written in high-levellanguages. Low-level languages are used only for a few specializedapplications.
Two kinds of programs process high-level languagesinto low-level languages: interpreters and compilers.An interpreter reads a high-level program and executes it, meaning that itdoes what the program says. It processes the program a little at a time,alternately reading lines and performing computations.
A compiler reads the program and translates it completely before theprogram starts running. In this context, the high-level program iscalled the source code, and the translated program is called theobject code or the executable. Once a program iscompiled, you can execute it repeatedly without further translation.
Python is considered an interpreted language because Python programsare executed by an interpreter. There are two ways to use theinterpreter: interactive mode and script mode. Ininteractive mode, you type Python programs and the interpreter printsthe result:
The chevron, >>>
, is theprompt the interpreter uses to indicate that it is ready. Ifyou type 1 + 1, and then press the Enter key,the interpreter replies 2.
Alternatively, you can store code in a file and use the interpreter toexecute the contents of the file, which is called a script. Byconvention, Python scripts have names that end with .py.
To execute the script, you have to tell the interpreter the name ofthe file. In a UNIX command window, you would type pythondinsdale.py. In other development environments, the details ofexecuting scripts are different. You can find instructions foryour environment at the Python Website python.org.
Working in interactive mode is convenient for testing small pieces ofcode because you can type and execute them immediately. But foranything more than a few lines, you should save your codeas a script so you can modify and execute it in the future.
What is a program?[edit]
A program is a sequence of instructions that specifies how toperform a computation. The computation might be somethingmathematical, such as solving a system of equations or finding theroots of a polynomial, but it can also be a symbolic computation, suchas searching and replacing text in a document or (strangely enough)compiling a program.
The details look different in different languages, but a few basicinstructions appear in just about every language:
- input:
- Get data from the keyboard, a file, or someother device.
- output:
- Display data on the screen or send data to afile or other device.
- math:
- Perform basic mathematical operations like addition andmultiplication.
- conditional execution:
- Check for certain conditions andexecute the appropriate sequence of statements.
- repetition:
- Perform some action repeatedly, usually withsome variation.
Believe it or not, that’s pretty much all there is to it. Everyprogram you’ve ever used, no matter how complicated, is made up ofinstructions that look pretty much like these. So you can think ofprogramming as the process of breaking a large, complex taskinto smaller and smaller subtasks until the subtasks aresimple enough to be performed with one of these basic instructions.
That may be a little vague, but we will come back to this topicwhen we talk about algorithms.
What is debugging?[edit]
Programming is error-prone. For whimsical reasons, programming errorsare called bugs and the process of tracking them down is calleddebugging.
Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors. It is usefulto distinguish between them in order to track them down more quickly.
Syntax errors[edit]
Python can only execute a program if the syntax iscorrect; otherwise, the interpreter displays an error message.Syntax refers to the structure of a program and the rules aboutthat structure. For example, parentheses have to come in matching pairs, so(1 + 2) is legal, but 8) is a syntax error.
In English readers can tolerate most syntax errors, which is why wecan read the poetry of E. E. Cummings without spewing error messages.Python is not so forgiving. If there is a single syntax erroranywhere in your program, Python will display an error message and quit,and you will not be able to run your program. During the first fewweeks of your programming career, you will probably spend a lot oftime tracking down syntax errors. As you gain experience, you willmake fewer errors and find them faster.
Runtime errors[edit]
The second type of error is a runtime error, so called because theerror does not appear until after the program has started running.These errors are also called exceptions because they usuallyindicate that something exceptional (and bad) has happened.
Runtime errors are rare in the simple programs you will see in thefirst few chapters, so it might be a while before you encounter one.
Semantic errors[edit]
The third type of error is the semantic error. If there is asemantic error in your program, it will run successfully in the sensethat the computer will not generate any error messages, but it willnot do the right thing. It will do something else. Specifically, itwill do what you told it to do.
The problem is that the program you wrote is not the program youwanted to write. The meaning of the program (its semantics) is wrong.Identifying semantic errors can be tricky because it requires you to workbackward by looking at the output of the program and trying to figureout what it is doing.
Experimental debugging[edit]
One of the most important skills you will acquire is debugging.Although it can be frustrating, debugging is one of the mostintellectually rich, challenging, and interesting parts ofprogramming.
In some ways, debugging is like detective work. You are confrontedwith clues, and you have to infer the processes and events that ledto the results you see.
Debugging is also like an experimental science. Once you have an ideaabout what is going wrong, you modify your program and try again. Ifyour hypothesis was correct, then you can predict the result of themodification, and you take a step closer to a working program. Ifyour hypothesis was wrong, you have to come up with a new one. AsSherlock Holmes pointed out, “When you have eliminated theimpossible, whatever remains, however improbable, must be the truth.”(A. Conan Doyle, The Sign of Four)
For some people, programming and debugging are the same thing. Thatis, programming is the process of gradually debugging a program untilit does what you want. The idea is that you should start with aprogram that does something and make small modifications,debugging them as you go, so that you always have a working program.
For example, Linux is an operating system that contains thousands oflines of code, but it started out as a simple program Linus Torvaldsused to explore the Intel 80386 chip. According to Larry Greenfield,“One of Linus’s earlier projects was a program that would switchbetween printing AAAA and BBBB. This later evolved to Linux.”(The Linux Users’ Guide Beta Version 1).
Later chapters will make more suggestions about debugging and otherprogramming practices.
Formal and natural languages[edit]
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 forspecific applications. For example, the notation that mathematiciansuse is a formal language that is particularly good at denotingrelationships among numbers and symbols. Chemists use a formallanguage to represent the chemical structure of molecules. Andmost importantly:
Programming languages are formal languages that have been designed to express computations.
Formal languages tend to have strict rules about syntax. For example,3 + 3 = 6 is a syntactically correct mathematical statement, but 3 + = 3 $ 6 is not. H2O is a syntactically correctchemical formula, but 2Zz is not.
Syntax rules come in two flavors, pertaining to tokens andstructure. Tokens are the basic elements of the language, such aswords, 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 becausethere is no element with the abbreviation Zz.
The second type of syntax error pertains to the structure of astatement; that is, the way the tokens are arranged. The statement 3+ = 3 $ 6 is illegal because even though + and = arelegal tokens, you can’t have one right after the other. Similarly,in a chemical formula the subscript comes after the element name, notbefore.
Exercise 1Write a well-structured Englishsentence with invalid tokens in it. Then write another sentencewith all valid tokens but with invalid structure.
When you read a sentence in English or a statement in a formallanguage, you have to figure out what the structure of the sentence is(although in a natural language you do this subconsciously). Thisprocess is called parsing.
For example, when you hear the sentence, “The penny dropped,” youunderstand that “the penny” is the subject and “dropped” is thepredicate. Once you have parsed a sentence, you can figure out what itmeans, or the semantics of the sentence. Assuming that you knowwhat a penny is and what it means to drop, you will understand thegeneral implication of this sentence.
Although formal and natural languages have many features incommon—tokens, structure, syntax, and semantics—there are somedifferences:
- ambiguity:
- Natural languages are full of ambiguity, whichpeople 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.
- redundancy:
- In order to make up for ambiguity and reducemisunderstandings, natural languages employ lots ofredundancy. As a result, they are often verbose. Formal languagesare less redundant and more concise.
- literalness:
- Natural languages are full of idiom and metaphor.If I say, “The penny dropped,” there is probably no penny andnothing dropping[1]. Formal languagesmean exactly what they say.
People who grow up speaking a natural language—everyone—often have ahard time adjusting to formal languages. In some ways, the differencebetween formal and natural language is like the difference betweenpoetry and prose, but more so:
- Poetry:
- Words are used for their sounds as well as fortheir meaning, and the whole poem together creates an effect oremotional response. Ambiguity is not only common but oftendeliberate.
- Prose:
- The literal meaning of words is more important,and the structure contributes more meaning. Prose is more amenable toanalysis than poetry but still often ambiguous.
- Programs:
- The meaning of a computer program is unambiguousand literal, and can be understood entirely by analysis of thetokens and structure.
Here are some suggestions for reading programs (and other formallanguages). First, remember that formal languages are much more densethan natural languages, so it takes longer to read them. Also, thestructure is very important, so it is usually not a good idea to readfrom top to bottom, left to right. Instead, learn to parse theprogram in your head, identifying the tokens and interpreting thestructure. Finally, the details matter. Small errors inspelling and punctuation, which you can get awaywith in natural languages, can make a big difference in a formallanguage.
The first program[edit]
Traditionally, the first program you write in a new languageis called “Hello, World!” because all it does is display thewords, “Hello, World!” In Python, it looks like this:
This is an example of a print statement[2], whichdoesn’t actually print anything on paper. It displays a value on thescreen. In this case, the result is the words
The quotation marks in the program mark the beginning and endof the text to be displayed; they don’t appear in the result.
Some people judge the quality of a programming language by thesimplicity of the “Hello, World!” program. By this standard, Pythondoes about as well as possible.
Debugging[edit]
It is a good idea to read this book in front of a computer so you cantry out the examples as you go. You can run most of the examples ininteractive mode, but if you put the code into a script, it is easierto try out variations.
Whenever you are experimenting with a new feature, you should tryto make mistakes. For example, in the “Hello, world!” program,what happens if you leave out one of the quotation marks? Whatif you leave out both? What if you spell print wrong?
This kind of experiment helps you remember what you read; it also helpswith debugging, because you get to know what the error messages mean.It is better to make mistakes now and on purpose than laterand accidentally.
Programming, and especially debugging, sometimes brings out strongemotions. 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 ifthey were people[3]. When they work well, we thinkof them as teammates, and when they are obstinate or rude, werespond to them the same way we respond to rude,obstinate people.
Preparing for these reactions might help you deal with them.One approach is to think of the computer as an employee withcertain strengths, like speed and precision, andparticular weaknesses, like lack of empathy and inabilityto grasp the big picture.
Your job is to be a good manager: find ways to take advantageof the strengths and mitigate the weaknesses. And find waysto use your emotions to engage with the problem,without letting your reactions interfere with your abilityto work effectively.
Learning to debug can be frustrating, but it is a valuable skillthat is useful for many activities beyond programming. At theend of each chapter there is a debugging section, like this one,with my thoughts about debugging. I hope they help!
Glossary[edit]
- problem solving:
- The process of formulating a problem, findinga solution, and expressing the solution.
- high-level language:
- A programming language like Python thatis designed to be easy for humans to read and write.
- low-level language:
- A programming language that is designedto be easy for a computer to execute; also called “machine language” or“assembly language.”
- portability:
- A property of a program that can run on morethan one kind of computer.
- interpret:
- To execute a program in a high-level languageby translating it one line at a time.
- compile:
- To translate a program written in a high-level languageinto a low-level language all at once, in preparation for laterexecution.
- source code:
- A program in a high-level language beforebeing compiled.
- object code:
- The output of the compiler after it translatesthe program.
- executable:
- Another name for object code that is readyto be executed.
- prompt:
- Characters displayed by the interpreter to indicatethat it is ready to take input from the user.
- script:
- A program stored in a file (usually one that will beinterpreted).
- interactive mode:
- A way of using the Python interpreter bytyping commands and expressions at the prompt.
- script mode:
- A way of using the Python interpreter to readand execute statements in a script.
- program:
- A set of instructions that specifies a computation.
- algorithm:
- A general process for solving a category ofproblems.
- bug:
- An error in a program.
- debugging:
- The process of finding and removing any of thethree kinds of programming errors.
- syntax:
- The structure of a program.
- syntax error:
- An error in a program that makes it impossibleto parse (and therefore impossible to interpret).
- exception:
- An error that is detected while the program is running.
- semantics:
- The meaning of a program.
- semantic error:
- An error in a program that makes it do somethingother than what the programmer intended.
- natural language:
- Any one of the languages that people speak thatevolved naturally.
- formal language:
- Any one of the languages that people have designedfor specific purposes, such as representing mathematical ideas orcomputer programs; all programming languages are formal languages.
- token:
- One of the basic elements of the syntactic structure ofa program, analogous to a word in a natural language.
- parse:
- To examine a program and analyze the syntactic structure.
- print statement:
- An instruction that causes the Pythoninterpreter to display a value on the screen.
Exercises[edit]
Exercise 2[edit]
Use a web browser to go to the Python website, http://python.org/.This page contains information about Python and linksto Python-related pages, and it gives you the ability to searchthe Python documentation.For example, if you enter print in the search window, thefirst link that appears is the documentation of the printstatement. At this point, not all of it will make sense to you,but it is good to know where it is.
Exercise 3[edit]
Start the Python interpreter and type 'help()' to start the onlinehelp utility. Or you can type help('print')
to get informationabout the 'print' statement.If this example doesn’t work, youmay need to install additional Python documentation or set anenvironment variable; the details depend on your operating system andversion of Python.
Exercise 4[edit]
Start the Python interpreter and use it as a calculator.Python’s syntax for math operations is almost the same asstandard mathematical notation. For example, the symbols'+', '-' and '/' denote addition, subtractionand division, as you would expect. The symbol formultiplication is '*'.If you run a 10 kilometer race in 43 minutes 30 seconds, what is youraverage time per mile? What is your average speed in miles per hour?(Hint: there are 1.61 kilometers in a mile).
References[edit]
- ↑This idiom means that someone realized somethingafter a period of confusion.
- ↑In Python 3.0,print is a function, not a statement, so the syntax is print(’Hello, World!’). We will get to functions soon!
- ↑See Reeves and Nass, The MediaEquation: How People Treat Computers, Television, and New MediaLike Real People and Places.
A Wikibookian has nominated this page for cleanup because: You can help make it better. Please review any relevant discussion. |
A Wikibookian has nominated this page for cleanup because: You can help make it better. Please review any relevant discussion. |
Values and types[edit]
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 identifystrings because they are enclosed in quotation marks.
The print statement also works for integers.
If you are not sure what type a value has, the interpreter can tell you.
Not surprisingly, strings belong to the type str andintegers belong to the type int. Less obviously, numberswith a decimal point belong to a type called float,because these numbers are represented in aformat called floating-point.
What about values like '17'
and '3.2'
?They look like numbers, but they are in quotation marks likestrings.
They're strings.
When you type a large integer, you might be tempted to use commasbetween groups of three digits, as in 1,000,000. This is not alegal integer in Python, but it is legal:
Well, that’s not what we expected at all! Python interprets 1,000,000 as a comma-separated sequence of integers, which itprints with spaces between.
This is the first example we have seen of a semantic error: the coderuns without producing an error message, but it doesn't do the“right” thing.
Variables[edit]
One of the most cheese cake features of a programming language is theability to manipulate variables. A variable is a name thatrefers to a value.
An assignment statement creates new variables and givesthem values:
This example makes three assignments. The first assigns a stringto a new variable named message;the second gives the integer 17 to n; the thirdassigns the (approximate) value of π to pi.
A common way to represent variables on paper is to write the name withan arrow pointing to the variable’s value. This kind of figure iscalled a state diagram because it shows what state each of thevariables is in (think of it as the variable’s state of mind).This diagram shows the result of the previous example:
message | 'And now for something completely different' | |
n | 17 | |
pi | 3.1415926535897931 |
To display the value of a variable, you can use a print statement:
The type of a variable is the type of the value it refers to.
Exercise 1[edit]
If you type an integer with a leading zero, you might geta confusing error:
Other number seem to work, but the results are bizarre:
Can you figure out what is going on? Hint: print the values 01
, 010
, 0100
and 01000
.
Variable names and keywords[edit]
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 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. Theinterpreter uses keywords to recognize the structure of the program,and they cannot be used as variable names.
Python has 31 keywords:
and | del | from | not | while |
as | elif | global | or | with |
assert | else | if | pass | yield |
break | except | import | print | |
class | exec | in | raise | |
continue | finally | is | return | |
def | for | lambda | try |
You might want to keep this list handy. If the interpreter complainsabout one of your variable names and you don't know why, see if itis on this list.
If you write your code in a text editor that understands Python, you may find that it makes it easy for you to spot such keyword clashes by displaying keywords in a different color to ordinary variables. This feature is called syntax highlighting, and most programmers find it indispensable. This book uses syntax highlighting for its example code, so in the following example:
you can see that yield
has been recognized as a keyword and not as an ordinary variable, since it is colored orange.
Statements[edit]
A statement is a unit of code that the Python interpreter canexecute. We have seen two kinds of statements: printand assignment.
When you type a statement in interactive mode, the interpreterexecutes it and displays the result, if there is one.
A script usually contains a sequence of statements. If thereis more than one statement, the results appear one at a timeas the statements execute.
For example, the script
produces the output
The assignment statement produces no output.
Operators and operands[edit]
Operators are special symbols that represent computations likeaddition and multiplication. The values the operator is applied toare called operands.
The operators +, -, *, / and **perform addition, subtraction, multiplication, division andexponentiation, as in the following examples:
In some other languages, ^
is used for exponentiation, butin Python it is a bitwise operator called XOR. I won’t coverbitwise operators in this book, but you can read aboutthem at wiki.python.org/moin/BitwiseOperators.
The division operator might not do what you expect:
The value of minute is 59, and in conventional arithmetic 59divided by 60 is 0.98333, not 0. The reason for the discrepancy isthat Python is performing floor division.[1]
When both of the operands are integers, the result is also aninteger; floor division chops off the fractionpart, so in this example it rounds down to zero.
If either of the operands is a floating-point number, Python performsfloating-point division, and the result is a float:
Expressions[edit]
An expression is a combination of values, variables, and operators.A value all by itself is considered an expression, and so isa variable, so the following are all legal expressions(assuming that the variable x has been assigned a value):
If you type an expression in interactive mode, the interpreterevaluates it and displays the result:
But in a script, an expression all by itself doesn’tdo anything! This is a commonsource of confusion for beginners.
Exercise 2[edit]
Type the following statements in the Python interpreter to see what they do:
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.
Order of operations[edit]
When more than one operator appears in an expression, the order ofevaluation depends on the rules of precedence. Formathematical operators, Python follows mathematical convention.The acronym PEMDAS is a useful way toremember 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. So in the expression degrees / 2 * pi, the division happens first and the result is multiplied by pi. To divide by 2 π, you can reorder the operands or use parentheses.
String operations[edit]
In general, you cannot perform mathematical operations on strings, evenif the strings look like numbers, so the following are illegal:
The + operator works with strings, but itmight not do what you expect: it performsconcatenation, which means joining the strings bylinking them end-to-end. For example:
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 operandsis a string, the other has to be an integer.
This use of + and * makes sense byanalogy with addition and multiplication. Just as 4*3 isequivalent 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 asignificant way in which string concatenation and repetition aredifferent from integer addition and multiplication.Can you think of a property that addition hasthat string concatenation does not?
Comments[edit]
As programs get bigger and more complicated, they get more difficultto read. Formal languages are dense, and it is often difficult tolook 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 explainin natural language what the program is doing. These notes are calledcomments, and they start with the #
symbol:
In this case, the comment appears on a line by itself. You can also put comments at the end of a line:
Everything from the #
to the end of the line is ignored—ithas no effect on the program.
Comments are most useful when they document non-obvious features ofthe code. It is reasonable to assume that the reader can figure outwhat the code does; it is much more useful to explain why.
This comment is redundant with the code and useless:
This comment contains useful information that is not in the code:
Good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a tradeoff.
Debugging[edit]
At this point the syntax error you are most likely to make isan illegal variable name, like class and yield, whichare keywords, or odd~job
and US$
, which containillegal characters.
If you put a space in a variable name, Python thinks it is twooperands without an operator:
For syntax errors, the error messages don’t help much.The most common messages are SyntaxError: invalid syntax andSyntaxError: invalid token, neither of which is very informative.
The runtime error you are most likely to make is a “use beforedef;” that is, trying to use a variable before you have assigneda value. This can happen if you spell a variable name wrong:
Variables names are case sensitive, so LaTeX is not thesame as latex.
At this point the most likely cause of a semantic error isthe order of operations. For example, to evaluate 1/2 π,you might be tempted to write
But the division happens first, so you would get π / 2, whichis not the same thing! There is no way for Pythonto know what you meant to write, so in this case you don’tget an error message; you just get the wrong answer.
Glossary[edit]
- value:
- One of the basic units of data, like a number or string, that a program manipulates.
- type:
- A category of values. The types we have seen so farare integers (type int), floating-point numbers (type float), and strings (type str).
- integer:
- A type that represents whole numbers.
- floating-point:
- A type that represents numbers with fractionalparts.
- string:
- A type that represents sequences of characters.
- variable:
- A name that refers to a value.
- statement:
- A section of code that represents a command or action. Sofar, the statements we have seen are assignments and print statements.
- assignment:
- A statement that assigns a value to a variable.
- state diagram:
- A graphical representation of a set of variables and thevalues they refer to.
- keyword:
- A reserved word that is used by the compiler to parse aprogram; you cannot use keywords like if, def, and while asvariable names.
- operator:
- A special symbol that represents a simple computation likeaddition, multiplication, or string concatenation.
- operand:
- One of the values on which an operator operates.
- floor division:
- The operation that divides two numbers and chops offthe fraction part.
- expression:
- A combination of variables, operators, and values thatrepresents a single result value.
- evaluate:
- To simplify an expression by performing the operationsin order to yield a single value.
- rules of precedence:
- The set of rules governing the order in whichexpressions involving multiple operators and operands are evaluated.
- concatenate:
- To join two operands end-to-end.
- comment:
- Information in a program that is meant for otherprogrammers (or anyone reading the source code) and has no effect on theexecution of the program.
Exercises[edit]
Exercise 3[edit]
Assume that we execute the following assignment statements:
For each of the following expressions, write the value of the expression and the type (of the value of the expression).
Use the Python interpreter to check your answers.
Exercise 4[edit]
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.6 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 centsfor each additional copy. What is the total wholesale cost for60 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 ateasy pace again, what time do I get home for breakfast?
Notes[edit]
- ↑In Python 3.0,the result of this division is a float. The new operator// performs integer division.
A Wikibookian has nominated this page for cleanup because: You can help make it better. Please review any relevant discussion. |
A Wikibookian has nominated this page for cleanup because: You can help make it better. Please review any relevant discussion. |
Function calls[edit]
In the context of programming, a function is a named sequence ofstatements 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. We have already seen one example of a function call:
The name of the function is type. The expression in parenthesesis called the argument of the function. The result, for thisfunction, 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.
Type conversion functions[edit]
Python provides built-in functions that convert valuesfrom one type to another. The int function takes any value andconverts it to an integer, if it can, or complains otherwise:
int can convert floating-point values to integers, but itdoesn't round off; it chops off the fraction part:
float converts integers and strings to floating-pointnumbers:
Finally, str converts its argument to a string:
Math functions[edit]
Python has a math module that provides most of the familiarmathematical functions. A module is a file that contains acollection of related functions.
Before we can use the module, we have to import it:
This statement creates a module object named math. Ifyou print the module object, you get some information about it:
The module object contains the functions and variables defined in themodule. To access one of the functions, you have to specify the nameof the module and the name of the function, separated by a dot (alsoknown as a period). This format is called dot notation.
The first example computes the logarithm base 10 of thesignal-to-noise ratio. The math module also provides afunction called log that computes logarithms base e.
The second example finds the sine of radians. The name of thevariable is a hint that sin and the other trigonometricfunctions (cos, tan, etc.) take arguments in radians. Toconvert from degrees to radians, divide by 360 and multiply by 2π:
The expression math.pi gets the variable pi from the mathmodule. The value of this variable is an approximationof π, accurate to about 15 digits.
If you knowyour trigonometry, you can check the previous result by comparing it tothe square root of two divided by two:
Composition[edit]
So far, we have looked at the elements of a program—variables,expressions, and statements—in isolation, without talking about how tocombine them.
One of the most useful features of programming languages is theirability to take small building blocks and compose them. Forexample, the argument of a function can be any kind of expression,including arithmetic operators:
And even function calls:
Almost anywhere you can put a value, you can put an arbitraryexpression, with one exception: the left side of an assignmentstatement has to be a variable name. Any other expression on the leftside is a syntax error.
Adding new functions[edit]
So far, we have only been using the functions that come with Python,but it is also possible to add new functions.A function definition specifies the name of a new function andthe sequence of statements that execute when the function is called.
Here is an example:
def is a keyword that indicates that this is a functiondefinition. The name of the function is print_lyrics
. Therules for function names are the same as for variable names: letters,numbers and some punctuation marks are legal, but the first charactercan'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 samename.
The empty parentheses after the name indicate that this functiondoesn'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 colonand the body has to be indented. By convention, the indentation isalways four spaces (see Section ). The body can containany number of statements.
The strings in the print statements are enclosed in doublequotes. Single quotes and double quotes do the same thing;most people use single quotes except in cases like this wherea single quote (which is also an apostrophe) appears in the string.
If you type a function definition in interactive mode, the interpreterprints ellipses (...) to let you know that the definitionisn't complete:
To end the function, you have to enter an empty line (this isnot necessary in a script).
Books Never Written Math Beginning Your Exercise Program By Year
Defining a function creates a variable with the same name.
The value of print_lyrics
is a function object, whichhas type 'function'
.
The syntax for calling the new function is the same asfor built-in functions:
Once you have defined a function, you can use it inside anotherfunction. For example, to repeat the previous refrain, we could writea function called repeat_lyrics
:
And then call repeat_lyrics
:
But that's not really how the song goes.
Definitions and uses[edit]
Pulling together the code fragments from the previous section, thewhole program looks like this:
This program contains two function definitions: print_lyrics
andrepeat_lyrics
. Function definitions get executed just like otherstatements, but the effect is to create function objects. The statementsinside the function do not get executed until the function is called, andthe function definition generates no output.
As you might expect, you have to create a function before you canexecute it. In other words, the function definition has to beexecuted before the first time it is called.
Exercise 1[edit]
Move the last line of this programto the top, so the function call appears before the definitions. Run the program and see what errormessage you get.
Exercise 2[edit]
Move the function call back to the bottomand move the definition of print_lyrics
after the definition ofrepeat_lyrics
. What happens when you run this program?
Flow of execution[edit]
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 iscalled 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 theprogram, but remember that statements inside the function are notexecuted until the function is called.
A function call is like a detour in the flow of execution. Instead ofgoing to the next statement, the flow jumps to the body ofthe function, executes all the statements there, and then comes backto pick up where it left off.
That sounds simple enough, until you remember that one function cancall another. While in the middle of one function, the program mighthave to execute the statements in another function. But whileexecuting that new function, the program might have to execute yetanother function!
Fortunately, Python is good at keeping track of where it is, so eachtime a function completes, the program picks up where it left off inthe 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, youdon't always want to read from top to bottom. Sometimes it makesmore sense if you follow the flow of execution.
Parameters and arguments[edit]
Some of the built-in functions we have seen require arguments. Forexample, when you call math.sin you pass a numberas 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 tovariables called parameters. Here is an example of auser-defined function that takes an argument:
This function assigns the argument to a parameternamed bruce. When the function is called, it prints the value ofthe parameter (whatever it is) twice.
This function works with any value that can be printed.
The same rules of composition that apply to built-in functions alsoapply to user-defined functions, so we can use any kind of expressionas an argument for print_twice
:
The argument is evaluated before the function is called, soin the examples the expressions 'Spam '*4
andmath.cos(math.pi) are only evaluated once.
You can also use a variable as an argument:
The name of the variable we pass as an argument (michael) hasnothing to do with the name of the parameter (bruce). Itdoesn't matter what the value was called back home (in the caller);here in print_twice
, we call everybody bruce.
Variables and parameters are local[edit]
When you create a variable inside a function, it is local,which means that it onlyexists inside the function. For example:
This function takes two arguments, concatenates them, and printsthe result twice. Here is an example that uses it:
When cat_twice
terminates, the variable catis destroyed. If we try to print it, we get an exception:
Parameters are also local.For example, outside print_twice
, there is nosuch thing as bruce.
Stack diagrams[edit]
To keep track of which variables can be used where, it is sometimesuseful to draw a stack diagram. Like state diagrams, stackdiagrams show the value of each variable, but they also show thefunction each variable belongs to.
Each function is represented by a frame. A frame is a boxwith the name of a functionbeside it and the parameters and variables of the function inside it.The stack diagram for theprevious example looks like this:
File:Book004.pngThe frames are arranged in a stack that indicates which functioncalled 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. Whenyou create a variable outside of any function, it belongs to __main__
.
Each parameter refers to the same value as its correspondingargument. So, part1 has the same value asline1, 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 thename of the function, and the name of the function that calledit, and the name of the function that called that, all theway back to __main__
.
For example, if you try to access cat from within
print_twice
, you get a NameError:
This list of functions is called a traceback. It tells you whatprogram file the error occurred in, and what line, and what functionswere executing at the time. It also shows the line of code thatcaused the error.
The order of the functions in the traceback is the same as theorder of the frames in the stack diagram. The function that iscurrently running is at the bottom.
Fruitful functions and void functions[edit]
Some of the functions we are using, such as the math functions, yieldresults; for lack of a better name, I call them fruitfulfunctions. Other functions, like print_twice
, perform anaction but don't return a value. They are called voidfunctions.
When you call a fruitful function, you almost alwayswant to do something with the result; for example, you mightassign it to a variable or use it as part of an expression:
When you call a function in interactive mode, Python displaysthe result:
But in a script, if you call a fruitful function all by itself,the return value is lost forever!
This script computes the square root of 5, but since it doesn't storeor display the result, it is not very useful.
Void functions might display something on the screen or have someother effect, but they don't have a return value. If you try toassign the result to a variable, you get a special value calledNone.
The value None is not the same as the string 'None'
. It is a special value that has its own type:
The functions we have written so far are all void. We will startwriting fruitful functions in a few chapters.
Why functions?[edit]
It may not be clear why it is worth the trouble to dividea 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.
Debugging[edit]
If you are using a text editor to write your scripts, you mightrun into problems with spaces and tabs. The best way to avoidthese problems is to use spaces exclusively (no tabs). Most texteditors that know about Python do this by default, but somedon't.
Tabs and spaces are usually invisible, which makes themhard to debug, so try to find an editor that manages indentationfor you.
Also, don't forget to save your program before you run it. Somedevelopment environments do this automatically, but some don't.In that case the program you are looking at in the text editoris 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 thebeginning of the program and run it again. If you don't seehello
, you're not running the right program!
Glossary[edit]
- function: A named sequence of statements that performs some
useful operation. Functions may or may not take arguments and may ormay not produce a result.
- function definition: A statement that creates a new function,
specifying its name, parameters, and the statements it executes.
- function object: A value created by a function definition.
The name of the function is a variable that refers to a functionobject.
- header: The first line of a function definition.
- body: The sequence of statements inside a function definition.
- parameter: A name used inside a function to refer to the value
passed as an argument.
- function call: A statement that executes a function. It
consists of the function name followed by an argument list.
- argument: A value provided to a function when the function is called.
This value is assigned to the corresponding parameter in the function.
- local variable: A variable defined inside a function. A local
variable can only be used inside its function.
- return value: The result of a function. If a function call
is used as an expression, the return value is the value ofthe expression.
- fruitful function: A function that returns a value.
- void function: A function that doesn't return a value.
- module: A file that contains a
collection of related functions and other definitions.
- import statement: A statement that reads a module file and creates
a module object.
- module object: A value created by an import statement
that provides access to the values defined in a module.
- dot notation: The syntax for calling a function in another
module by specifying the module name followed by a dot (period) andthe function name.
- composition: Using an expression as part of a larger expression,
or a statement as part of a larger statement.
- flow of execution: The order in which statements are executed during
a program run.
- stack diagram: A graphical representation of a stack of functions,
their variables, and the values they refer to.
- frame: A box in a stack diagram that represents a function call.
It contains the local variables and parameters of the function.
- traceback: A list of the functions that are executing,
printed when an exception occurs.
Exercises[edit]
Exercise 3[edit]
Python provides a built-in function called len thatreturns the length of a string, so the value of len('allen')
is 5.
Write a function named right_justify
that takes a stringnamed s as a parameter and prints the string with enoughleading spaces so that the last letter of the string is in column 70of the display.
Exercise 4[edit]
A function object is a value you can assign to a variableor pass as an argument. For example, do_twice
is a functionthat takes a function object as an argument and calls it twice:
Here’s an example that uses do_twice
to call a functionnamed print_spam
twice.
- 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
, calledprint_twice
, that takes a string as a parameter and prints it twice. - Use the modified version of
do_twice
to callprint_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.
You can see my solution at thinkpython.com/code/do_four.py.
Exercise 5[edit]
This exercise' can bedone using only the statements and other features we have learned sofar.
- 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:
If the sequence ends with a comma, Python leaves the line unfinished, so the value printed next appears on the same line.
The output of these statements is '+ -'
.A print statement all by itself ends the current line and goes to the next line.
- Use the previous function to draw a similar grid with four rows and four columns.
You can see my solution at thinkpython.com/code/grid.py.
We will see exceptions to this rulelater.Based on an exercise in Oualline, Practical C Programming, Third Edition, O’Reilly (1997)
A Wikibookian has nominated this page for cleanup because: You can help make it better. Please review any relevant discussion. |
A Wikibookian has nominated this page for cleanup because: You can help make it better. Please review any relevant discussion. |
TurtleWorld[edit]
To accompany this book, I have written a suite of modules called Swampy. One of these modules is TurtleWorld, which provides a set of functions for drawing lines by steering turtles around the screen.
You can download Swampy from thinkpython.com/swampy; follow the instructions there to install Swampy on your system.
Move into the directory that contains TurtleWorld.py, create a file named polygon.py and type in the following code:
The first line is a variation of the import statement we saw before;instead of creating a module object, it imports the functionsfrom the module directly, so you can access them without using dotnotation.
The next lines create a TurtleWorld assigned to world anda Turtle assigned to bob. Printing bob yields somethinglike:
This means that bob refers to an instance of a Turtle as defined in module TurtleWorld. In this context, 'instance' means a member of a set; this Turtle is one of the set of possible Turtles.
wait_for_user
tells TurtleWorld to wait for the userto do something, although in this case there's not much forthe user to do except close the window.
TurtleWorld provides severalturtle-steering functions: fd and bk forforward and backward, and lt and rt for left andright turns. Also, each Turtle is holding a pen, which iseither down or up; if the pen is down, the Turtle leavesa trail when it moves. The functions pu and pdstand for “pen up” and “pen down.”
To draw a right angle, add these lines to the program(after creating bob and before calling wait_for_user
):
The first line tells bob to take 100 stepsforward. The second line tells him to turn right.
When you run this program, you should see bob move east and thensouth, leaving two line segments behind.
Now modify the program to draw a square. Don’t turn the page untilyou've got it working!
Simple repetition[edit]
Chances are you wrote something like this (leaving out the codethat creates TurtleWorld and waits for the user):
We can do the same thing more concisely with a for statement.Add this example to polygon.py and run it again:
You should see something like this:
This is the simplest use of the for statement; we will seemore later. But that should be enough to let you rewrite yoursquare-drawing program. Don’t turn the page until you do.
Here is a for statement that draws a square:
The syntax of a for statement is similar to a functiondefinition. It has a header that ends with a colon and an indentedbody. The body can contain any number of statements.
A for statement is sometimes called a loop becausethe flow of execution runs through the body and then loops backto the top. In this case, it runs the body four times.
This version is actually a little different from the previoussquare-drawing code because it makes another left turn afterdrawing the last side of the square. The extra turn takes a littlemore time, but it simplifies the code if we do the same thingevery time through the loop. This version also has the effectof leaving the turtle back in the starting position, facing inthe starting direction.
Exercises[edit]
The following is a series of exercises using TurtleWorld. Theyare meant to be fun, but they have a point, too. While you areworking on them, think about what the point is.
The following sections have solutions to the exercises, sodon’t look until you have finished (or at least tried).
- Write a function called square that takes a parameter
named t, which is a turtle. It should use the turtle to drawa square.Write a function call that passes bob as an argument tosquare, and then run the program again.
- Add another parameter, named length, to square.
Modify the body so length of the sides is length, and thenmodify the function call to provide a second argument. Run theprogram again. Test your program with a range of values for length.
- The functions lt and rt make 90-degree turns by
default, but you can provide a second argument that specifies thenumber of degrees. For example, lt(bob, 45) turns bob 45degrees to the left.Make a copy of square and change the name to polygon. Addanother parameter named n and modify the body so it draws ann-sided regular polygon. Hint: The angles of an n-sided regularpolygon are 360.0 / n degrees.
- Write a function called circle that takes a turtle, t,
and radius, r, as parameters and that draws an approximate circleby invoking polygon with an appropriate length and number ofsides. Test your function with a range of values of r.
Hint: figure out the circumference of the circle and make sure thatlength * n = circumference.
Another hint: if bob is too slow for you, you can speedhim up by changing bob.delay, which is the time between moves,in seconds. bob.delay = 0.01 ought to get him moving.
- Make a more general version of circle called arc
that takes an additional parameter angle, which determineswhat fraction of a circle to draw. angle is in units ofdegrees, so when angle=360, arc should draw a completecircle.
Encapsulation[edit]
The first exercise asks you to put your square-drawing codeinto a function definition and then call the function, passingthe turtle as a parameter. Here is a solution:
The innermost statements, fd and lt areindented twice to show that they are inside the for loop,which is inside the function definition. The next line,square(bob), is flush with the left margin, so that is theend of both the for loop and the function definition.
Inside the function, t refers to the same turtle bobrefers to, so lt(t) has the same effect as lt(bob).So why not call the parameter bob? The idea is that tcan be any turtle, not just bob, so you could createa second turtle and pass it as an argument to square:
Wrapping a piece of code up in a function is called encapsulation. One of the benefits of encapsulation is that itattaches a name to the code, which serves as a kind of documentation.Another advantage is that if you re-use the code, it is more conciseto call a function twice than to copy and paste the body!
Generalization[edit]
The next step is to add a length parameter to square.Here is a solution:
Adding a parameter to a function is called generalizationbecause it makes the function more general: in the previousversion, the square is always the same size; in this versionit can be any size.
The next step is also a generalization. Instead of drawingsquares, polygon draws regular polygons with any number ofsides. Here is a solution:
This draws a 7-sided polygon with side length 70. If you havemore than a few numeric arguments, it is easy to forget what theyare, or what order they should be in. It is legal, and sometimeshelpful, to include the names of the parameters in the argumentlist:
These are called keyword arguments because they includethe parameter names as “keywords” (not to be confused withPython keywords like while and def).
This syntax makes the program more readable. It is also a reminderabout how arguments and parameters work: when you call a function, thearguments are assigned to the parameters.
Interface design[edit]
The next step is to write circle, which takes a radius,r, as a parameter. Here is a simple solution that usespolygon to draw a 50-sided polygon:
The first line computes the circumference of a circle with radiusr using the formula 2 π r. Since we use math.pi, wehave to import math. By convention, import statementsare usually at the beginning of the script.
n is the number of line segments in our approximation of a circle,so length is the length of each segment. Thus, polygondraws a 50-sides polygon that approximates a circle with radius r.
One limitation of this solution is that n is a constant, whichmeans that for very big circles, the line segments are too long, andfor small circles, we waste time drawing very small segments. Onesolution would be to generalize the function by taking n asa parameter. This would give the user (whoever calls circle)more control, but the interface would be less clean.
The interface of a function is a summary of how it is used: whatare the parameters? What does the function do? And what is the returnvalue? An interface is “clean” if it is “as simple aspossible, but not simpler. (Einstein)”
In this example, r belongs in the interface because itspecifies the circle to be drawn. n is less appropriatebecause it pertains to the details of how the circle shouldbe rendered.
Rather than clutter up the interface, it is betterto choose an appropriate value of ndepending on circumference:
Now the number of segments is (approximately) circumference/3,so the length of each segment is (approximately) 3, which is smallenough that the circles look good, but big enough to be efficient,and appropriate for any size circle.
Refactoring[edit]
When I wrote circle, I was able to re-use polygonbecause a many-sided polygon is a good approximation of a circle.But arc is not as cooperative; we can’t use polygonor circle to draw an arc.
One alternative is to start with a copyof polygon and transform it into arc. The resultmight look like this:
The second half of this function looks like polygon, but wecan’t re-use polygon without changing the interface. We couldgeneralize polygon to take an angle as a third argument,but then polygon would no longer be an appropriate name!Instead, let’s call the more general function polyline:
Now we can rewrite polygon and arc to use polyline:
Finally, we can rewrite circle to use arc:
This process—rearranging a program to improve functioninterfaces and facilitate code re-use—is called refactoring.In this case, we noticed that there was similar code in arc andpolygon, so we “factored it out” into polyline.
If we had planned ahead, we might have written polyline firstand avoided refactoring, but often you don’t know enough at thebeginning of a project to design all the interfaces. Once you startcoding, you understand the problem better. Sometimes refactoring is asign that you have learned something.
A development plan[edit]
A development plan is a process for writing programs.The process we usedin this case study is “encapsulation andgeneralization.” The steps of this process are:
- Start by writing a small program with no function definitions.
- Once you get the program working, encapsulate it in a function
and give it a name.
- Generalize the function by adding appropriate parameters.
- Repeat steps 1–3 until you have a set of working functions.
Copy and paste working code to avoid retyping (and re-debugging).
- Look for opportunities to improve the program by refactoring.
For example, if you have similar code in several places, considerfactoring it into an appropriately general function.
This process has some drawbacks—we will see alternatives later—butit can be useful if you don’t know ahead of time how to divide theprogram into functions. This approach lets you design as you goalong.
docstring[edit]
A docstring is a string at the beginning of a function thatexplains the interface (“doc” is short for “documentation”). Hereis an example:
This docstring is a triple-quoted string, also knownas a multiline string because the triple quotes allow the stringto span more than one line.
It is terse, but it contains the essential informationsomeone would need to use this function. It explains concisely whatthe function does (without getting into the details of how it doesit). It explains what effect each parameter has on the behavior ofthe function and what type each parameter should be (if it is notobvious).
Writing this kind of documentation is an important part of interfacedesign. A well-designed interface should be simple to explain;if you are having a hard time explaining one of your functions,that might be a sign that the interface could be improved.
Debugging[edit]
An interface is like a contract between a function and a caller.The caller agrees to provide certain parameters and the functionagrees to do certain work.
For example, polyline requires four arguments. The firsthas to be a Turtle (or some other object that works with fdand lt). The second has to be a number, and it shouldprobably be positive, although it turns out that the functionworks even if it isn’t. The third argument should be an integer;range complains otherwise (depending on which versionof Python you are running). The fourth has to be a number,which is understood to be in degrees.
These requirements are called preconditions because theyare supposed to be true before the function starts executing.Conversely, conditions at the end of the function arepostconditions. Postconditions include the intendedeffect of the function (like drawing line segments) and anyside effects (like moving the Turtle or making other changesin the World).
Preconditions are the responsibility of the caller. If the callerviolates a (properly documented!) precondition and the functiondoesn’t work correctly, the bug is in the caller, not the function.However, for purposes of debugging it is often a good idea forfunctions to check their preconditions rather than assume they aretrue. If every function checks its preconditions before starting,then if something goes wrong, you will know which function to blame.
Glossary[edit]
- instance:
- A member of a set. The TurtleWorld in thischapter is a member of the set of TurtleWorlds.
- loop:
- A part of a program that can execute repeatedly.
- encapsulation:
- The process of transforming a sequence ofstatements into a function definition.
- generalization:
- The process of replacing somethingunnecessarily specific (like a number) with something appropriatelygeneral (like a variable or parameter).
- keyword argument:
- An argument that includes the name ofthe parameter as a “keyword.”
- interface:
- A description of how to use a function, includingthe name and descriptions of the arguments and return value.
- development plan:
- A process for writing programs.
- docstring:
- A string that appears in a function definitionto document the function’s interface.
- precondition:
- A requirement that should be satisfied bythe caller before a function starts.
- postcondition:
- A requirement that should be satisfied bythe function before it ends.
Exercises[edit]
Exercise 1Download the code in this chapter from'thinkpython.com/code/polygon.py'.
- Write appropriate docstrings for 'polygon', 'arc' and
'circle'.
- Draw a stack diagram that shows the state of the program
while executing 'circle(bob, radius)'. You can do thearithmetic by hand or add 'print' statements to the code.
- The version of 'arc' in Section '4.7' is not
very accurate because the linear approximation of thecircle is always outside the true circle. As a result,the turtle ends up a few units away from the correctdestination. My solution shows a way to reducethe effect of this error. Read the code and see if it makessense to you. If you draw a diagram, you might see how it works.
Exercise 2Write an appropriately general set of functions thatcan draw flowers like this:
You can download a solution from 'thinkpython.com/code/flower.py'.
Exercise 3Write an appropriately general set of functions thatcan draw shapes like this:
You can download a solution from 'thinkpython.com/code/pie.py'.
Exercise 4'The letters of the alphabet can be constructed from a moderatenumber of basic elements, like vertical and horizontal linesand a few curves. Design a font that can be drawn with aminimal number of basic elements and then write functionsthat draw letters of the alphabet.
You should write one function for each letter, with namesdraw_a
, draw_b
, etc., and put your functionsin a file named 'letters.py'. You can download a“turtle typewriter” from 'thinkpython.com/code/typewriter.py'to help you test your code.
You can download a solution from 'thinkpython.com/code/letters.py'.
A Wikibookian has nominated this page for cleanup because: You can help make it better. Please review any relevant discussion. |
A Wikibookian has nominated this page for cleanup because: You can help make it better. Please review any relevant discussion. |
Modulus operator[edit]
The modulus operator works on integers and yields the remainderwhen the first operand is divided by the second. In Python, themodulus operator is a percent sign (%
). The syntax is the sameas for other operators:
So 7 divided by 3 is 2 with 1 left over.
The modulus operator turns out to be surprisingly useful. Forexample, you can check whether one number is divisible by another—ifx % y is zero, then x is divisible by y.
Also, you can extract the right-most digitor digits from a number. For example, x % 10 yields theright-most digit of x (in base 10). Similarly x % 100yields the last two digits.
Boolean expressions[edit]
A boolean expression is an expression that is either trueor false. The following examples use the operator , which compares two operands and producesTrue if they are equal and False otherwise:
True and False are specialvalues that belong to the type bool; they are not strings:
The operator is one of the comparison operators; theothers are:
Although these operations are probably familiar to you, the Pythonsymbols are different from the mathematical symbols. A common erroris to use a single equal sign (=) instead of a double equal sign(). Remember that = is an assignment operator and is a comparison operator. There is no such thing as=< or =>.
Logical operators[edit]
There are three logical operators: and, or, and not. The semantics (meaning) of these operators issimilar to their meaning in English. For example,x > 0 and x < 10 is true only if x is greater than 0and less than 10.
n%2 0 or n%3 0 is true if either of the conditionsis true, that is, if the number is divisible by 2 or 3.
Finally, the not operator negates a booleanexpression, so not (x > y) is true if x > y is false,that is, if x is less than or equal to y.
Strictly speaking, the operands of the logical operators should beboolean expressions, but Python is not very strict.Any nonzero number is interpreted as “true.”
This flexibility can be useful, but there are some subtleties toit that might be confusing. You might want to avoid it (unlessyou know what you are doing).
Conditional execution[edit]
In order to write useful programs, we almost always need the abilityto check conditions and change the behavior of the programaccordingly. Conditional statements give us this ability. Thesimplest form is the if statement:
The boolean expression after the if statement iscalled the condition. If it is true, then the indentedstatement gets executed. If not, nothing happens.
if statements have the same structure as function definitions:a header followed by an indented block. Statements like this arecalled compound statements.
There is no limit on the number of statements that can appear inthe body, but there has to be at least one.Occasionally, it is useful to have a body with no statements (usuallyas a place keeper for code you haven't written yet). In thatcase, you can use the pass statement, which does nothing.
Alternative execution[edit]
A second form of the if statement is alternative execution,in which there are two possibilities and the condition determineswhich one gets executed. The syntax looks like this:
If the remainder when x is divided by 2 is 0, then weknow that x is even, and the program displays a message to thateffect. If the condition is false, the second set of statements isexecuted. Since the condition must be true or false, exactly one ofthe alternatives will be executed. The alternatives are calledbranches, because they are branches in the flow of execution.
Chained conditionals[edit]
Sometimes there are more than two possibilities and we need more thantwo branches. One way to express a computation like that is a chained conditional:
elif is an abbreviation of “else if.” Again, exactly onebranch will be executed. There is no limit on the number of elif statements. If there is an else clause, it has to beat the end, but there doesn’t have to be one.
Each condition is checked in order. If the first is false,the next is checked, and so on. If one of them istrue, the corresponding branch executes, and the statementends. Even if more than one condition is true, only thefirst true branch executes.
Nested conditionals[edit]
One conditional can also be nested within another. We could havewritten the trichotomy example like this:
The outer conditional contains two branches. Thefirst branch contains a simple statement. The second branchcontains another if statement, which has two branches of itsown. Those two branches are both simple statements,although they could have been conditional statements as well.
Although the indentation of the statements makes the structureapparent, nested conditionals become difficult to read veryquickly. In general, it is a good idea to avoid them when you can.
Logical operators often provide a way to simplify nested conditionalstatements. For example, we can rewrite the following code using asingle conditional:
The print statement is executed only if we make it past bothconditionals, so we can get the same effect with the and operator:
Recursion[edit]
It is legal for one function to call another;it is also legal for a function to call itself. It may not be obviouswhy that is a good thing, but it turns out to be one of the mostmagical things a program can do.For example, look at the following function:
If n is 0 or negative, it outputs the word, “Blastoff!”Otherwise, it outputs n and then calls a function named countdown—itself—passing n-1 as an argument.
What happens if we call this function like this?
The execution of countdown begins with n=3, and sincen is greater than 0, it outputs the value 3, and then calls itself...
The execution of countdown begins with n=2, and since
n is greater than 0, it outputs the value 2, and then calls itself...
The execution of countdown begins with n=1, and since
n is greater than 0, it outputs the value 1, and then calls itself...
The execution of countdown begins with n=0, and since n is not greater than 0, it outputs the word, “Blastoff!” and thenreturns.
The countdown that got n=1 returns.
The countdown that got n=2 returns.
The countdown that got n=3 returns.
And then you’re back in __main__
. So, thetotal output looks like this:
A function that calls itself is recursive; the process iscalled recursion.
As another example, we can write a function that prints astring n times.
If n <= 0 the return statement exits the function. Theflow of execution immediately returns to the caller, and the remaininglines of the function are not executed.
The rest of the function is similar to countdown: if n isgreater than 0, it displays s and then calls itself to displaysn−1 additional times. So the number of lines of outputis 1 + (n - 1), which adds up ton.
For simple examples like this, it is probably easier to use a for loop. But we will see examples later that are hard to writewith a for loop and easy to write with recursion, so it isgood to start early.
Stack diagrams for recursive functions[edit]
In Section 3.10, we used a stack diagram to representthe state of a program during a function call. The same kind ofdiagram can help interpret a recursive function.
Every time a function gets called, Python creates a new functionframe, which contains the function’s local variables and parameters.For a recursive function, there might be more than one frame on thestack at the same time.
This figure shows a stack diagram for countdown called withn = 3:
As usual, the top of the stack is the frame for __main__
.It is empty because we did not create any variables in __main__
or pass any arguments to it.
The four countdown frames have different values for theparameter n. The bottom of the stack, where n=0, iscalled the base case. It does not make a recursive call, sothere are no more frames.
Draw a stack diagram for print_n
called withs = 'Hello'
and n=2.
Beginning Your Exercise Program By Math
Write a function called do_n
that takes a functionobject and a number, n as arguments, and that callsthe given function n times.
Infinite recursion[edit]
If a recursion never reaches a base case, it goes on makingrecursive calls forever, and the program never terminates. This isknown as infinite recursion, and it is generally nota good idea. Here is a minimal program with an infinite recursion:
In most programming environments, a program with infinite recursiondoes not really run forever. Python reports an errormessage when the maximum recursion depth is reached:
This traceback is a little bigger than the one we saw in theprevious chapter. When the error occurs, there are 1000recurse frames on the stack!
Keyboard input[edit]
The programs we have written so far are a bit rude in the sense thatthey accept no input from the user. They just do the same thing everytime.
Python provides a built-in function called raw_input
that getsinput from the keyboard[1]. When this function is called, the program stops andwaits for the user to type something. When the user presses Return or Enter, the program resumes and raw_input
returns what the user typed as a string.
Before getting input from the user, it is a good idea to print aprompt telling the user what to input. raw_input
can take aprompt as an argument:
The sequence n
at the end of the prompt represents a newline,which is a special character that causes a line break.That’s why the user’s input appears below the prompt.
If you expect the user to type an integer, you can try to convertthe return value to int:
But if the user types something other than a string of digits,you get an error:
We will see how to handle this kind of error later.
Debugging[edit]
The traceback Python displays when an error occurs containsa lot of information, but it can be overwhelming, especiallywhen there are many frames on the stack. The mostuseful parts are usually:
- What kind of error it was, and
- Where it occurred.
Syntax errors are usually easy to find, but there are a fewgotchas. Whitespace errors can be tricky because spaces andtabs are invisible and we are used to ignoring them.
In this example, the problem is that the second line is indented byone space. But the error message points to y, which ismisleading. In general, error messages indicate where the problem wasdiscovered, but the actual error might be earlier in the code,sometimes on a previous line.
The same is true of runtime errors. Suppose you are tryingto compute a signal-to-noise ratio in decibels. The formulais SNRdb = 10 log10 (Psignal / Pnoise). In Python,you might write something like this:
But when you run it, you get an error message:
The error message indicates line 5, but there is nothingwrong with that line. To find the real error, it might beuseful to print the value of ratio, which turns out tobe 0. The problem is in line 4, because dividing two integersdoes floor division. The solution is to represent signal powerand noise power with floating-point values.
In general, error messages tell you where the problem was discovered, but that is often not where it was caused.
Books Never Written Math Beginning Your Exercise Program By Walking One Mile
Glossary[edit]
- modulus operator:
- An operator, denoted with a percent sign(%), that works on integers and yields the remainder when onenumber is divided by another.
- boolean expression:
- An expression whose value is either True or False.
- comparison operator:
- One of the operators that comparesits operands: , !=, >, <, >=, and <=.
- logical operator:
- One of the operators that combines booleanexpressions: and, or, and not.
- conditional statement:
- A statement that controls the flow ofexecution depending on some condition.
- condition:
- The boolean expression in a conditional statementthat determines which branch is executed.
- compound statement:
- A statement that consists of a headerand a body. The header ends with a colon (:). The body is indentedrelative to the header.
- body:
- The sequence of statements within a compound statement.
- branch:
- One of the alternative sequences of statements ina conditional statement.
- chained conditional:
- A conditional statement with a seriesof alternative branches.
- nested conditional:
- A conditional statement that appearsin one of the branches of another conditional statement.
- recursion:
- The process of calling the function that iscurrently executing.
- base case:
- A conditional branch in arecursive function that does not make a recursive call.
- infinite recursion:
- A function that calls itself recursivelywithout ever reaching the base case. Eventually, an infinite recursioncauses a runtime error.
Exercises[edit]
Exercise 1Fermat’s Last Theorem says that there are no integers'a', 'b', and 'c' such that
an + bn = cn |
for any values of 'n' greater than 2.
- Write a function named
check_fermat
that takes four
parameters—'a', 'b', 'c' and 'n'—andthat checks to see if Fermat’s theorem holds. If
'n' is greater than 2 and it turns out to be true that'a''n'' + b''n'' = c''n'' ' |
'the program should print, “Holy smokes, Fermat was wrong!”Otherwise the program should print, “No, that doesn’t work.”'
- 'Write a function that prompts the user to input values
for ''a'', ''b'', ''c'' and ''n'', converts them tointegers, and uses ''
check_fermat'
' to check whether theyviolate Fermat’s theorem.'
Exercise 2If you are given three sticks, you may or may not be able to arrangethem in a triangle. For example, if one of the sticks is 12 incheslong and the other two are one inch long, it is clear that you willnot be able to get the short sticks to meet in the middle. For anythree lengths, there is a simple test to see if it is possible to forma triangle:
“If any of the three lengths is greater than the sum of the othertwo, then you cannot form a triangle. Otherwise, youcan[2].”
- Write a function named
is_triangle
that takes three
integers as arguments, and that prints either “Yes” or “No,” dependingon whether you can or cannot form a triangle from sticks with thegiven lengths.
- Write a function that prompts the user to input three stick
lengths, converts them to integers, and uses is_triangle
tocheck whether sticks with the given lengths can form a triangle.
The following exercises use TurtleWorld from Chapter 4:
Exercise 3Read the following function and see if you can figure outwhat it does. Then run it (see the examples in Chapter '4').
Exercise 4The Koch curve is a fractal that looks something likethis:
To draw a Koch curve with length 'x', all you have to do is
- Draw a Koch curve with length 'x/3'.
- Turn left 60 degrees.
- Draw a Koch curve with length 'x/3'.
- Turn right 120 degrees.
- Draw a Koch curve with length 'x/3'.
- Turn left 60 degrees.
- Draw a Koch curve with length 'x/3'.
The only exception is if 'x' is less than 3. In that case,you can just draw a straight line with length 'x'.
- Write a function called 'koch' that takes a turtle and
a length as parameters, and that uses the turtle to draw a Kochcurve with the given length.
- Write a function called 'snowflake' that draws three
Koch curves to make the outline of a snowflake.You can see my solution at 'thinkpython.com/code/koch.py'.
- The Koch curve can be generalized in several ways. See
'wikipedia.org/wiki/Koch_snowflake' for examples andimplement your favorite.
Notes[edit]
- ↑In Python 3.0, this function is named input
- ↑If the sum of two lengths equals the third, they formwhat is called a “degenerate” triangle.
Return values[edit]
Some of the built-in functions we have used, such as the mathfunctions, produce results. Calling the function generates avalue, which we usually assign to a variable or use as part of anexpression.
All of the functions we have written so far are void; they printsomething or move turtles around, but their return value is None.
In this chapter, we are (finally) going to write fruitful functions.The first example is area, which returns the area of a circlewith the given radius:
We have seen the return statement before, but in a fruitfulfunction the return statement includesan expression. This statement means: “Return immediately fromthis function and use the following expression as a return value.”The expression can be arbitrarily complicated, so we couldhave written this function more concisely:
On the other hand, temporary variables like temp often makedebugging easier.
Sometimes it is useful to have multiple return statements, one in eachbranch of a conditional:
Since these return statements are in an alternative conditional,only one will be executed.
As soon as a return statement executes, the functionterminates without executing any subsequent statements.Code that appears after a return statement, or any other placethe flow of execution can never reach, is called dead code.
In a fruitful function, it is a good idea to ensurethat every possible path through the program hits areturn statement. For example:
This function is incorrect because if x happens to be 0,neither condition is true, and the function ends without hitting areturn statement. If the flow of execution gets to the endof a function, the return value is None, which is notthe absolute value of 0.
By the way, Python provides a built-in function called abs that computes absolute values.
Exercise 1[edit]
Write a 'compare' functionthat returns '1' if 'x > y','0' if 'x y', and '-1' if 'x < y'.
Incremental development[edit]
As you write larger functions, you might find yourselfspending more time debugging.
To deal with increasingly complex programs,you might want to try a process calledincremental development. The goal of incremental developmentis to avoid long debugging sessions by adding and testing onlya small amount of code at a time.
As an example, suppose you want to find the distance between twopoints, given by the coordinates (x1, y1) and (x2, y2).By the Pythagorean theorem, the distance is:
The first step is to consider what a distance function shouldlook like in Python. In other words, what are the inputs (parameters)and what is the output (return value)?
In this case, the inputs are two points, which you can representusing four numbers. The return value is the distance, which isa floating-point value.
Already you can write an outline of the function:
Obviously, this version doesn't compute distances; it always returnszero. But it is syntactically correct, and it runs, which means thatyou can test it before you make it more complicated.
To test the new function, call it with sample arguments:
I chose these values so that the horizontal distance is 3 and thevertical distance is 4; that way, the result is 5(the hypotenuse of a 3-4-5 triangle). When testing a function, it isuseful to know the right answer.
At this point we have confirmed that the function is syntacticallycorrect, and we can start adding code to the body.A reasonable next step is to find the differencesx2 − x1 and y2 − y1. The next version stores those values intemporary variables and prints them.
If the function is working, it should display 'dx is 3'
and ’dy is 4’. If so, we know that the function is getting the rightarguments and performing the first computation correctly. If not,there are only a few lines to check.
Next we compute the sum of squares of dx and dy:
Again, you would run the program at this stage and check the output(which should be 25).Finally, you can use math.sqrt to compute and return the result:
If that works correctly, you are done. Otherwise, you mightwant to print the value of result before the returnstatement.
The final version of the function doesn’t display anything when itruns; it only returns a value. The print statements we wroteare useful for debugging, but once you get the function working, youshould remove them. Code like that is called scaffoldingbecause it is helpful for building the program but is not part of thefinal product.
When you start out, you should add only a line or two of code at atime. As you gain more experience, you might find yourself writingand debugging bigger chunks. Either way, incremental developmentcan save you a lot of debugging time.
The key aspects of the process are:
- Start with a working program and make small incremental changes. At any point, if there is an error, you should have a good idea where it is.
- Use temporary variables to hold intermediate values so you can display and check them.
- Once the program is working, you might want to remove some of the scaffolding or consolidate multiple statements into compound expressions, but only if it does not make the program difficult to read.
Exercise 2[edit]
Use incremental development to write a functioncalled 'hypotenuse' that returns the length of the hypotenuse of aright triangle given the lengths of the two legs as arguments.Record each stage of the development process as you go.
Composition[edit]
As you should expect by now, you can call one function fromwithin another. This ability is called composition.
As an example, we’ll write a function that takes two points,the center of the circle and a point on the perimeter, and computesthe area of the circle.
Assume that the center point is stored in the variables xc andyc, and the perimeter point is in xp and yp. Thefirst step is to find the radius of the circle, which is the distancebetween the two points. We just wrote a function, distance, that does that:
The next step is to find the area of a circle with that radius;we just wrote that, too:
Encapsulating these steps in a function, we get:
The temporary variables radius and result are useful fordevelopment and debugging, but once the program is working, we canmake it more concise by composing the function calls:
Boolean functions[edit]
Functions can return booleans, which is often convenient for hidingcomplicated tests inside functions. For example:
It is common to give boolean functions names that sound like yes/noquestions; is_divisible
returns either True or Falseto indicate whether x is divisible by y.
Here is an example:
The result of the operator is a boolean, so we can write thefunction more concisely by returning it directly:
Boolean functions are often used in conditional statements:
It might be tempting to write something like:
But the extra comparison is unnecessary.
Exercise 3Write a function is_between(x, y, z)
thatreturns 'True' if 'x ≤ y ≤ z' or 'False' otherwise.
More recursion[edit]
We have only covered a small subset of Python, but you mightbe interested to know that this subset is a completeprogramming language, which means that anything that can becomputed can be expressed in this language. Any program ever writtencould be rewritten using only the language features you have learnedso far (actually, you would need a few commands to control deviceslike the keyboard, mouse, disks, etc., but that’s all).
Proving that claim is a nontrivial exercise first accomplished by AlanTuring, one of the first computer scientists (some would argue that hewas a mathematician, but a lot of early computer scientists started asmathematicians). Accordingly, it is known as the Turing Thesis.For a more complete (and accurate) discussion of the Turing Thesis,I recommend Michael Sipser’s book Introduction to theTheory of Computation.
To give you an idea of what you can do with the tools you have learnedso far, we’ll evaluate a few recursively defined mathematicalfunctions. A recursive definition is similar to a circulardefinition, in the sense that the definition contains a reference tothe thing being defined. A truly circular definition is not veryuseful:
- frabjuous:
- An adjective used to describe something that is frabjuous.
If you saw that definition in the dictionary, you might be annoyed. Onthe other hand, if you looked up the definition of the factorialfunction, denoted with the symbol !, you might get something likethis:
|