




























































































Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!





























































































Editorial Support: Elliott Hauser, Sue Blumenberg Cover Design: Aimee Andrion
Copyright 2009- Dr. Charles R. Severance.
This work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 3.0 Unported License. This license is available at
http://creativecommons.org/licenses/by-nc-sa/3.0/
You can see what the author considers commercial and non-commercial uses of this material as well as license exemptions in the Appendix titled “Copyright Detail”.
iv
Students who find this book interesting and want to further explore should look at Allen B. Downey’s Think Python book. Because there is a lot of overlap be- tween the two books, students will quickly pick up skills in the additional areas of technical programming and algorithmic thinking that are covered in Think Python. And given that the books have a similar writing style, they should be able to move quickly through Think Python with a minimum of effort.
As the copyright holder of Think Python , Allen has given me permission to change the book’s license on the material from his book that remains in this book from the GNU Free Documentation License to the more recent Creative Commons Attribu- tion — Share Alike license. This follows a general shift in open documentation licenses moving from the GFDL to the CC-BY-SA (e.g., Wikipedia). Using the CC-BY-SA license maintains the book’s strong copyleft tradition while making it even more straightforward for new authors to reuse this material as they see fit.
I feel that this book serves as an example of why open materials are so important to the future of education, and I want to thank Allen B. Downey and Cambridge University Press for their forward-looking decision to make the book available under an open copyright. I hope they are pleased with the results of my efforts and I hope that you, the reader, are pleased with our collective efforts.
I would like to thank Allen B. Downey and Lauren Cowles for their help, patience, and guidance in dealing with and resolving the copyright issues around this book.
Charles Severance www.dr-chuck.com Ann Arbor, MI, USA September 9, 2013
Charles Severance is a Clinical Associate Professor at the University of Michigan School of Information.
Writing programs (or programming) is a very creative and rewarding activity. You can write programs for many reasons, ranging from making your living to solving a difficult data analysis problem to having fun to helping someone else solve a problem. This book assumes that everyone needs to know how to program, and that once you know how to program you will figure out what you want to do with your newfound skills.
We are surrounded in our daily lives with computers ranging from laptops to cell phones. We can think of these computers as our “personal assistants” who can take care of many things on our behalf. The hardware in our current-day computers is essentially built to continuously ask us the question, “What would you like me to do next?”
Programmers add an operating system and a set of applications to the hardware and we end up with a Personal Digital Assistant that is quite helpful and capable of helping us do many different things.
Our computers are fast and have vast amounts of memory and could be very helpful to us if we only knew the language to speak to explain to the computer what we would like it to “do next”. If we knew this language, we could tell the computer to do tasks on our behalf that were repetitive. Interestingly, the kinds of things computers can do best are often the kinds of things that we humans find boring and mind-numbing.
What Next?
What Next?
What Next?
What Next?
What Next?
What Next?
Figure 1.1: Personal Digital Assistant
Pick Me!
Pick Me!
Pick Me!
Pick Me!
Pick Me!
Buy Me :)
Figure 1.2: Programmers Talking to You
For example, look at the first three paragraphs of this chapter and tell me the most commonly used word and how many times the word is used. While you were able to read and understand the words in a few seconds, counting them is almost painful because it is not the kind of problem that human minds are designed to solve. For a computer, the opposite is true, reading and understanding text from a piece of paper is hard for a computer to do but counting the words and telling you how many times the most used word was used is very easy for the computer:
python words.py Enter file: words.txt to 16
Our “personal information analysis assistant” quickly told us that the word “to” was used sixteen times in the first three paragraphs of this chapter. This very fact that computers are good at things that humans are not is why you need to become skilled at talking “computer language”. Once you learn this new language, you can delegate mundane tasks to your partner (the computer), leaving more time for you to do the things that you are uniquely suited for. You bring creativity, intuition, and inventiveness to this partnership.
1.1 Creativity and motivation
While this book is not intended for professional programmers, professional pro- gramming can be a very rewarding job both financially and personally. Building useful, elegant, and clever programs for others to use is a very creative activity. Your computer or Personal Digital Assistant (PDA) usually contains many dif- ferent programs from many different groups of programmers, each competing for your attention and interest. They try their best to meet your needs and give you a great user experience in the process. In some situations, when you choose a piece of software, the programmers are directly compensated because of your choice. If we think of programs as the creative output of groups of programmers, perhaps the following figure is a more sensible version of our PDA: For now, our primary motivation is not to make money or please end users, but instead for us to be more productive in handling the data and information that we will encounter in our lives. When you first start, you will be both the programmer and the end user of your programs. As you gain skill as a programmer and pro- gramming feels more creative to you, your thoughts may turn toward developing programs for others.
Input and Output Devices
Software
Main Memory
Central Processing Unit
What Next?
Network
Secondary Memory
Figure 1.4: Where Are You?
As a programmer, your job is to use and orchestrate each of these resources to solve the problem that you need to solve and analyze the data you get from the solution. As a programmer you will mostly be “talking” to the CPU and telling it what to do next. Sometimes you will tell the CPU to use the main memory, secondary memory, network, or the input/output devices.
You need to be the person who answers the CPU’s “What next?” question. But it would be very uncomfortable to shrink you down to 5mm tall and insert you into the computer just so you could issue a command three billion times per second. So instead, you must write down your instructions in advance. We call these stored instructions a program and the act of writing these instructions down and getting the instructions to be correct programming.
1.3 Understanding programming
In the rest of this book, we will try to turn you into a person who is skilled in the art of programming. In the end you will be a programmer - perhaps not a professional programmer, but at least you will have the skills to look at a data/information analysis problem and develop a program to solve the problem.
In a sense, you need two skills to be a programmer:
Once you learn one programming language such as Python, you will find it much easier to learn a second programming language such as JavaScript or C++. The
new programming language has very different vocabulary and grammar but the problem-solving skills will be the same across all programming languages. You will learn the “vocabulary” and “sentences” of Python pretty quickly. It will take longer for you to be able to write a coherent program to solve a brand-new problem. We teach programming much like we teach writing. We start reading and explaining programs, then we write simple programs, and then we write in- creasingly complex programs over time. At some point you “get your muse” and see the patterns on your own and can see more naturally how to take a problem and write a program that solves that problem. And once you get to that point, programming becomes a very pleasant and creative process.
We start with the vocabulary and structure of Python programs. Be patient as the simple examples remind you of when you started reading for the first time.
1.4 Words and sentences
Unlike human languages, the Python vocabulary is actually pretty small. We call this “vocabulary” the “reserved words” or “keywords”. These are words that have very special meaning to Python. When Python sees these words in a Python program, they have one and only one meaning to Python. Later as you write programs you will make up your own words that have meaning to you called variables. You will have great latitude in choosing your names for your variables, but you cannot use any of Python’s reserved words as a name for a variable.
When we train a dog, we use special words like “sit”, “stay”, and “fetch”. When you talk to a dog and don’t use any of the reserved words, they just look at you with a quizzical look on their face until you say a reserved word. For example, if you say, “I wish more people would walk to improve their overall health”, what most dogs likely hear is, “blah blah blah walk blah blah blah blah.” That is because “walk” is a reserved word in dog language. Many might suggest that the language between humans and cats has no reserved words^1. The reserved words in the language where humans talk to Python include the following:
False await else import pass None break except in raise True class finally is return and continue for lambda try as def from nonlocal while assert del global not with async elif if or yield
That is it, and unlike a dog, Python is already completely trained. When you say “try”, Python will try every time you say it without fail.
We will learn these reserved words and how they are used in good time, but for now we will focus on the Python equivalent of “speak” (in human-to-dog language). The nice thing about telling Python to speak is that we can even tell it what to say by giving it a message in quotes: (^1) http://xkcd.com/231/
print('Hello world!') Hello world!
This is looking much better, so you try to communicate some more:
print('You must be the legendary god that comes from the sky') You must be the legendary god that comes from the sky print('We have been waiting for you for a long time') We have been waiting for you for a long time print('Our legend says you will be very tasty with mustard') Our legend says you will be very tasty with mustard print 'We will have a feast tonight unless you say File "
", line 1 print 'We will have a feast tonight unless you say ˆ SyntaxError: unterminated string literal (detected at line 1 )
The conversation was going so well for a while and then you made the tiniest mistake using the Python language and Python brought the spears back out.
At this point, you should also realize that while Python is amazingly complex and powerful and very picky about the syntax you use to communicate with it, Python is not intelligent. You are really just having a conversation with yourself, but using proper syntax.
In a sense, when you use a program written by someone else the conversation is between you and those other programmers with Python acting as an intermediary. Python is a way for the creators of programs to express how the conversation is supposed to proceed. And in just a few more chapters, you will be one of those programmers using Python to talk to the users of your program.
Before we leave our first conversation with the Python interpreter, you should prob- ably know the proper way to say “good-bye” when interacting with the inhabitants of Planet Python:
good-bye Traceback (most recent call last): File "
", line 1 , in NameError: name 'good' is not defined if you don't mind, I need to leave File " ", line 1 if you don't mind, I need to leave ˆ SyntaxError: unterminated string literal (detected at line 1 ) quit()
You will notice that the error is different for the first two incorrect attempts. The second error is different because if is a reserved word and Python saw the reserved word and thought we were trying to say something but got the syntax of the sentence wrong.
The proper way to say “good-bye” to Python is to enter quit() at the interactive chevron >>> prompt. It would have probably taken you quite a while to guess that one, so having a book handy probably will turn out to be helpful.
1.6 Terminology: Interpreter and compiler
Python is a high-level language intended to be relatively straightforward for hu- mans to read and write and for computers to read and process. Other high-level languages include Java, C++, PHP, Ruby, Basic, Perl, JavaScript, and many more. The actual hardware inside the Central Processing Unit (CPU) does not under- stand any of these high-level languages.
The CPU understands a language we call machine language. Machine language is very simple and frankly very tiresome to write because it is represented all in zeros and ones:
001010001110100100101010000001111 11100110000011101010010101101101 ...
Machine language seems quite simple on the surface, given that there are only zeros and ones, but its syntax is even more complex and far more intricate than Python. So very few programmers ever write machine language. Instead we build various translators to allow programmers to write in high-level languages like Python or JavaScript and these translators convert the programs to machine language for actual execution by the CPU.
Since machine language is tied to the computer hardware, machine language is not portable across different types of hardware. Programs written in high-level lan- guages can be moved between different computers by using a different interpreter on the new machine or recompiling the code to create a machine language version of the program for the new machine.
These programming language translators fall into two general categories: (1) inter- preters and (2) compilers.
An interpreter reads the source code of the program as written by the programmer, parses the source code, and interprets the instructions on the fly. Python is an interpreter and when we are running Python interactively, we can type a line of Python (a sentence) and Python processes it immediately and is ready for us to type another line of Python.
Some of the lines of Python tell Python that you want it to remember some value for later. We need to pick a name for that value to be remembered and we can use that symbolic name to retrieve the value later. We use the term variable to refer to the labels we use to refer to this stored data.
x = 6 print(x) 6 y = x * 7