




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































Introduction
Dedication
Preface
About Python
Installation
First Steps
Basics
Operators and Expressions
Control flow
Functions
Modules
Data Structures
Problem Solving
Object Oriented Programming
Input and Output
Exceptions
Standard Library
More
What Next
Appendix: FLOSS
Appendix: About
Appendix: Revision History
Appendix: Translations
Appendix: Translation How-to
Feedback
"A Byte of Python" is a free book on programming using the Python language. It serves as a tutorial or guide to the Python language for a beginner audience. If all you know about computers is how to save text files, then this is the book for you.
This book will teach you to use Python version 3. There will also be guidance for you to adapt to the older and more common Python version 2 in the book.
Here are what people are saying about the book:
Somewhere around 2004 - 05 when I was convinced I wasn’t smart enough to be a programmer , I came came across the original A Byte of #Python, and that changed my entire perspective on computing and life , I owe a lot to that book @swaroopch had written. -- Rahul on Jul 30, 2020
This is the book that got me into programming almost a decade ago. Thank you @swaroopch. You changed my life. -- Stefan Froelich on Aug 2, 2019
I am writing this email to thank you for the great help your book has done for me! It was a really good book that I enjoyed thoroughly. As a 15 year old who has never done programming before, trying to learn Python online was difficult and I couldn't understand anything. But I felt like your book gave was much easier to understand and eased me into the whole new world of programming. Thanks to you, I can now write a high level language with ease. I thought programming would be hard and boring, but with your book's help, I realised how fun and interesting yet simple it can be! I would like to thank you again for your hard work on helping out beginners like me. -- Prottyashita Tahiyat on Sep 17, 2019 This is the best beginner's tutorial I've ever seen! Thank you for your effort. -- Walt Michalik
The best thing i found was "A Byte of Python", which is simply a brilliant book for a beginner. It's well written, the concepts are well explained with self evident examples. -- Joshua Robin
Excellent gentle introduction to programming #Python for beginners -- Shan Rajasekaran start to love python with every single page read -- Herbert Feutl
perfect beginners guide for python, will give u key to unlock magical world of python -- Dilip
I should be doing my actual "work" but just found "A Byte of Python". A great guide with great examples. -- Biologist John
Recently started reading a Byte of python. Awesome work. And that too for free. Highly recommended for aspiring pythonistas. -- Mangesh A Byte of Python, written by Swaroop. (this is the book I'm currently reading). Probably the best to start with, and probably the best in the world for every newbie or even a more experienced user. -- Apostolos Enjoying Reading #ByteOfPython by @swaroopch best book ever -- Yuvraj Sharma
A Byte of Python by @swaroopch is still the "Best newbie guide to python" -- Nickson Kaigi
I would like to thank you for your book A Byte of Python which i myself find the best way to learn python. I am a 15 year old i live in egypt my name is Ahmed. Python was my second programming language i learn visual basic 6 at school but didn't enjoy it, however i really enjoyed learning python. I made the addressbook program and i was sucessful. i will try to start make more programs and read python programs (if you could tell me source that would be helpful). I will also start on learning java and if you can tell me where to find a tutorial as good as yours for java that would help me a lot. Thanx. -- Ahmed Mohammed
A wonderful resource for beginners wanting to learn more about Python is the 110-page PDF tutorial A Byte of Python by Swaroop C H. It is well-written, easy to follow, and may be the best introduction to Python programming available. -- Drew Ames
Yesterday I got through most of Byte of Python on my Nokia N800 and it's the easiest and most concise introduction to Python I have yet encountered. Highly recommended as a starting point for learning Python. -- Jason Delport
Byte of Vim and Python by @swaroopch is by far the best works in technical writing to me. Excellent reads #FeelGoodFactor -- Surendran
"Byte of python" best one by far man (in response to the question "Can anyone suggest a good, inexpensive resource for learning the basics of Python? ") -- Justin LoveTrue
The Book Byte of python was very helpful ..Thanks bigtime :) Chinmay
Always been a fan of A Byte of Python - made for both new and experienced programmers. -- Patrick Harrington
I started learning python few days ago from your book..thanks for such a nice book. it is so well written, you made my life easy..so you found a new fan of yours..thats me :) tons of thanks. -- Gadadhari Bheem
Before I started to learn Python, I've acquired basic programming skills in Assembly, C, C++, C# and Java. The very reason I wanted to learn Python is it's popular (people are talking about it) and powerful (reality). This book written by Mr. Swaroop is a very good guide for both brand-new programmers and new python programmers. Took 10 half days to go through it. Great Help! -- Fang Biyi (PhD Candidate ECE, Michigan State University)
Thank you ever so much for this book!! This book cleared up many questions I had about certain aspects of Python such as object oriented programming. I do not feel like an expert at OO but I know this book helped me on a first step or two. I have now written several python programs that actually do real things for me as a system administrator. They are all procedural oriented but they are small by most peoples standards. Again, thanks for this book. Thank you for having it on the web. -- Bob
I just want to thank you for writing the first book on programming I've ever really read. Python is now my first language, and I can just imagine all the possibilities. So thank you for giving me the tools to create things I never would have imagined I could do before. -- "The Walrus"
I wanted to thank you for writing A Byte Of Python (2 & 3 Versions). It has been invaluable to my learning experience in Python & Programming in general. Needless to say, I am a beginner in the programming world, a couple of months of self study up to this point. I had been using youtube tutorials & some other online tutorials including other free books. I decided to dig into your book yesterday, & I've learned more on the first few pages than any other book or tutorial. A few things I had been confused about, were cleared right up with a GREAT example & explanation. Can't wait to read (and learn) more!! Thank you so much for not only writing the book, but for putting it under the creative commons license (free). Thank goodness there are unselfish people like you out there to help & teach the rest of us. -- Chris
I wrote you back in 2011 and I was just getting into Python and wanted to thank you for your tutorial "A Byte of Python". Without it, I would have fallen by the wayside. Since then I have gone on to program a number of functions in my organization with this language with yet more on the horizon. I would not call myself an advanced programmer by any stretch but I notice the occasional request for assistance now from others since I started using it. I discovered, while reading "Byte" why I had ceased studying C and C++ and it was because the book given to me started out with an example containing an augmented assignment. Of course, there was no explanation for this arrangement of operators and I fell on my head trying to make sense of what was on the written page. As I recall it was a most frustrating exercise which I eventually abandoned. Doesn't mean C or C++ is impossible to learn, or even that I am stupid, but it does mean that the documentation I worked my way through did not define the symbols and words which is an essential part of any instruction. Just as computers will not be able to understand a computer word or computer symbol that is outside the syntax for the language being used, a student new to any field will not grasp his subject if he encounters words or symbols for which there are no definitions. You get a "blue screen" as it were in either case. The solution is simple, though: find the word or symbol and get the proper definition or symbol and lo and behold,the computer or student can proceed. Your book was so well put together that I found very little in it I couldn't grasp. So, thank you. I encourage you to continue to include full definitions of terms. The documentation with Python is good, once you know, (the examples are its strength from what I see) but in many cases it seems that you have to know in order to understand the documentation which to my mind is not what should be. Third party tutorials express the need for clarification of the documentation and their success largely depends on the words that are used to describe the terminology. I have recommended your book to many others. Some in Australia, some in the Caribbean and yet others in the US. It fills a niche no others do. I hope you are doing well and wish you all the success in the future. -- Nick
hey, this is ankush(19). I was facing a great difficulty to start with python. I tried a lot of books but all were bulkier and not target oriented; and then i found this lovely one, which made me love python in no time. Thanks a lot for this "beautiful piece of book". -- Ankush
I would like to thank you for your excellent guide on Python. I am a molecular biologist (with little programming background) and for my work I need to handle big datasets of DNA sequences and to analyse microscope images. For both things, programming in python has been useful, if not essential to complete and publish a 6-years project. That such a guide is freely available is a clear sign that the forces of evil are not yet ruling the world! :) -- Luca
Since this is going to be the first language you learn, you should use A Byte of Python. It really gives a proper introduction into programming in Python and it is paced well enough for the average beginner. The most important thing from then on will be actually starting to practice making your own little programs. -- " {Unregistered}"
Just to say a loud and happy thank you very much for publishing "A Byte of Python" and "A Byte of Vim". Those books were very useful to me four or five years ago when I starting learning programming. Right now I'm developing a project that was a dream for a long, long time and just want to say thank you. Keep walking. You are a source of motivation. All the best. -- Jocimar
Finished reading A byte of Python in 3 days. It is thoroughly interesting. Not a single page was boring. I want to understand the Orca screen reader code. Your book has hopefully equipped me for it. -- Dattatray
Hi, 'A byte of python' is really a good reading for python beginners. So, again, NICE WORK! i'm a 4 years experienced Java&C developer from China. Recently, i want to do some work on zim-wiki note project which uses pygtk to implement. i read your book in 6 days, and i can read and write python code examples now. thx for your contribution. plz keep your enthusiasm to make this world better, this is just a little encourage from China. -- Lee
A printed hardcopy of the book can be purchased at https://swaroopch.com/buybook/ for your offline reading pleasure, and to support the continued development and improvement of this book.
Visit https://github.com/swaroopch/byte-of-python/releases/latest to download a PDF file (best for desktop reading) or an EPUB file (best for devices such as mobile, tablet, ebook readers).
Visit https://github.com/swaroopch/byte-of-python for the raw content (for suggesting corrections, changes, translating, etc.)
If you are interested in reading or contributing translations of this book to other human languages, please see Translations.
To Kalyan Varma and many other seniors at PESIT who introduced us to GNU/Linux and the world of open source.
To the memory of Atul Chitnis, a friend and guide who shall be missed greatly.
To the pioneers who made the Internet happen. This book was first written in 2003. It still remains popular, thanks to the nature of sharing knowledge on the Internet as envisioned by the pioneers.
Python is one of those rare languages which can claim to be both simple and powerful. You will find yourself pleasantly surprised to see how easy it is to concentrate on the solution to the problem rather than the syntax and structure of the language you are programming in.
The official introduction to Python is:
Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python's elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.
I will discuss most of these features in more detail in the next section.
Guido van Rossum, the creator of the Python language, named the language after the BBC show "Monty Python's Flying Circus". He doesn't particularly like snakes that kill animals for food by winding their long bodies around them and crushing them.
Python is a simple and minimalistic language. Reading a good Python program feels almost like reading English, although very strict English! This pseudo-code nature of Python is one of its greatest strengths. It allows you to concentrate on the solution to the problem rather than the language itself.
As you will see, Python is extremely easy to get started with. Python has an extraordinarily simple syntax, as already mentioned.
Python is an example of a FLOSS (Free/Libre and Open Source Software). In simple terms, you can freely distribute copies of this software, read its source code, make changes to it, and use pieces of it in new free programs. FLOSS is based on the concept of a community which shares knowledge. This is one of the reasons why Python is so good - it has been created and is constantly improved by a community who just want to see a better Python.
When you write programs in Python, you never need to bother about the low-level details such as managing the memory used by your program, etc.
Due to its open-source nature, Python has been ported to (i.e. changed to make it work on) many platforms. All your Python programs can work on any of these platforms without requiring any changes at all if you are careful enough to avoid any system-dependent features.
You can use Python on GNU/Linux, Windows, FreeBSD, Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, BeOS, OS/390, z/OS, Palm OS, QNX, VMS, Psion, Acorn RISC OS, VxWorks, PlayStation, Sharp Zaurus, Windows CE and PocketPC!
You can even use a platform like Kivy to create games for your computer and for iPhone, iPad, and Android.
This requires a bit of explanation.
A program written in a compiled language like C or C++ is converted from the source language i.e. C or C++ into a language that is spoken by your computer (binary code i.e. 0s and 1s) using a compiler with various flags and options. When you run the program, the linker/loader software copies the program from hard disk to memory and starts running it.
Python, on the other hand, does not need compilation to binary. You just run the program directly from the source code. Internally, Python converts the source code into an intermediate form called bytecodes and then translates this into the native language of your computer and then runs it. All this, actually, makes using Python much easier since you don't have to worry about compiling the program, making sure that the proper libraries are linked and loaded, etc. This also makes your Python programs much more portable, since you can just copy your Python program onto another computer and it just works!
Python supports procedure-oriented programming as well as object-oriented programming (OOP). In procedure- oriented languages, the program is built around procedures or functions which are nothing but reusable pieces of programs. In object-oriented languages, the program is built around objects which combine data and functionality. Python has a very powerful but simplistic way of doing OOP, especially when compared to big languages like C++ or Java.
If you need a critical piece of code to run very fast or want to have some piece of algorithm not to be open, you can code that part of your program in C or C++ and then use it from your Python program.
You can embed Python within your C/C++ programs to give scripting capabilities for your program's users.
The Python Standard Library is huge indeed. It can help you do various things involving regular expressions,documentation generation, unit testing, threading, databases, web browsers, CGI, FTP, email, XML, XML-RPC, HTML, WAV files, cryptography, GUI (graphical user interfaces), and other system-dependent stuff. Remember, all this is always available wherever Python is installed. This is called the Batteries Included philosophy of Python.
Besides the standard library, there are various other high-quality libraries which you can find at the Python Package Index.
When we refer to "Python 3" in this book, we will be referring to any version of Python equal to or greater than version Python 3.6.0.
Visit https://www.python.org/downloads/ and download the latest version. At the time of this writing, it was Python 3.5.1 The installation is just like any other Windows-based software.
Note that if your Windows version is pre-Vista, you should download Python 3.4 only as later versions require newer versions of Windows.
CAUTION: Make sure you check option Add Python 3.5 to PATH.
To change install location, click on Customize installation , then Next and enter C:\python35 (or another appropriate location) as the install location.
If you didn�t check the Add Python 3.5 PATH option earlier, check Add Python to environment variables. This does the same thing as Add Python 3.5 to PATH on the first install screen.
You can choose to install Launcher for all users or not, it does not matter much. Launcher is used to switch between different versions of Python installed.
If your path was not set correctly (by checking the Add Python 3.5 Path or Add Python to environment variables options), then follow the steps in the next section ( DOS Prompt ) to fix it. Otherwise, go to the Running Python prompt on Windows section in this document.
NOTE: For people who already know programming, if you are familiar with Docker, check out Python in Docker and Docker on Windows.
If you want to be able to use Python from the Windows command line i.e. the DOS prompt, then you need to set the PATH variable appropriately.
For Windows 2000, XP, 2003 , click on Control Panel -> System -> Advanced -> Environment Variables. Click on the variable named PATH in the System Variables section, then select Edit and add ;C:\Python35 (please verify that this folder exists, it will be different for newer versions of Python) to the end of what is already there. Of course, use the appropriate directory name.
For older versions of Windows, open the file C:\AUTOEXEC.BAT and add the line PATH=%PATH%;C:\Python35 and restart the system. For Windows NT, use the AUTOEXEC.NT file.
For Windows Vista:
Click Start and choose Control Panel Click System, on the right you'll see "View basic information about your computer" On the left is a list of tasks, the last of which is Advanced system settings. Click that. The Advanced tab of the System Properties dialog box is shown. Click the Environment Variables button on the bottom right. In the lower box titled System Variables scroll down to Path and click the Edit button. Change your path as need be. Restart your system. Vista didn't pick up the system path environment variable change until I restarted.
For Windows 7 and 8:
Right click on Computer from your desktop and select Properties or click Start and choose Control Panel -> System and Security -> System. Click on Advanced system settings on the left and then click on the Advanced tab. At the bottom click on Environment Variables and under System variables , look for the PATH variable, select and then press Edit. Go to the end of the line under Variable value and append ;C:\Python35 (please verify that this folder exists, it will be different for newer versions of Python) to the end of what is already there. Of course, use the appropriate folder name. If the value was %SystemRoot%\system32; It will now become %SystemRoot%\system32;C:\Python Click OK and you are done. No restart is required, however you may have to close and reopen the command line.
For Windows 10:
Windows Start Menu > Settings > About > System Info (this is all the way over to the right) > Advanced System Settings > Environment Variables (this is towards the bottom) > (then highlight Path variable and click Edit ) > New > (type in whatever your python location is. For example, C:\Python35\ )
For Windows users, you can run the interpreter in the command line if you have set the PATH variable appropriately.
To open the terminal in Windows, click the start button and click Run. In the dialog box, type cmd and press [enter] key.
Then, type python and ensure there are no errors.
For Mac OS X users, use Homebrew: brew install python.
To verify, open the terminal by pressing [Command + Space] keys (to open Spotlight search), type Terminal and press [enter] key. Now, run python3 and ensure there are no errors.
For GNU/Linux users, use your distribution's package manager to install Python 3, e.g. on Debian & Ubuntu: sudo apt-get update && sudo apt-get install python.
To verify, open the terminal by opening the Terminal application or by pressing Alt + F2 and entering gnome- terminal. If that doesn't work, please refer the documentation of your particular GNU/Linux distribution. Now, run python3 and ensure there are no errors.
You can see the version of Python on the screen by running:
$ python3 -V Python 3.6.
NOTE: $ is the prompt of the shell. It will be different for you depending on the settings of the operating system on your computer, hence I will indicate the prompt by just the $ symbol.
We will now see how to run a traditional 'Hello World' program in Python. This will teach you how to write, save and run Python programs.
There are two ways of using Python to run your program - using the interactive interpreter prompt or using a source file. We will now see how to use both of these methods.
Open the terminal in your operating system (as discussed previously in the Installation chapter) and then open the Python prompt by typing python3 and pressing [enter] key.
Once you have started Python, you should see >>> where you can start typing stuff. This is called the Python interpreter prompt.
At the Python interpreter prompt, type:
print("Hello World")
followed by the [enter] key. You should see the words Hello World printed to the screen.
Here is an example of what you should be seeing, when using a Mac OS X computer. The details about the Python software will differ based on your computer, but the part from the prompt (i.e. from >>> onwards) should be the same regardless of the operating system.
$ python Python 3.6.0 (default, Jan 12 2017, 11:26:36) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print("Hello World") Hello World
Notice that Python gives you the output of the line immediately! What you just entered is a single Python statement. We use print to (unsurprisingly) print any value that you supply to it. Here, we are supplying the text Hello World and this is promptly printed to the screen.
If you are using a GNU/Linux or OS X shell, you can exit the interpreter prompt by pressing [ctrl + d] or entering exit() (note: remember to include the parentheses, () ) followed by the [enter] key.
If you are using the Windows command prompt, press [ctrl + z] followed by the [enter] key.
We cannot type out our program at the interpreter prompt every time we want to run something, so we have to save them in files and can run our programs any number of times.
To create our Python source files, we need an editor software where you can type and save. A good programmer's editor will make your life easier in writing the source files. Hence, the choice of an editor is crucial indeed. You have to choose an editor as you would choose a car you would buy. A good editor will help you write Python programs easily, making your journey more comfortable and helps you reach your destination (achieve your goal) in a much faster and safer way.
One of the very basic requirements is syntax highlighting where all the different parts of your Python program are colorized so that you can see your program and visualize its running.
If you have no idea where to start, I would recommend using PyCharm Educational Edition software which is available on Windows, Mac OS X and GNU/Linux. Details in the next section.
If you are using Windows, do not use Notepad - it is a bad choice because it does not do syntax highlighting and also importantly it does not support indentation of the text which is very important in our case as we will see later. Good editors will automatically do this.
If you are an experienced programmer, then you must be already using Vim or Emacs. Needless to say, these are two of the most powerful editors and you will benefit from using them to write your Python programs. I personally use both for most of my programs, and have even written an entire book on Vim.
In case you are willing to take the time to learn Vim or Emacs, then I highly recommend that you do learn to use either of them as it will be very useful for you in the long run. However, as I mentioned before, beginners can start with PyCharm and focus the learning on Python rather than the editor at this moment.
To reiterate, please choose a proper editor - it can make writing Python programs more fun and easy.
If you are interested in a detailed discussion on this topic, check out Finding the Perfect Python Code Editor.
PyCharm Educational Edition is a free editor which you can use for writing Python programs.
When you open PyCharm, you'll see this, click on Create New Project :
Change untitled to helloworld as the location of the project, you should see details similar to this:
Click the Create button.
Right-click on the helloworld in the sidebar and select New -> Python File :