Byte of Python
Byte of Python
Introduction 1.1
Dedication 1.2
Preface 1.3
About Python 1.4
Facility 1,5
First steps 1,6
The essential 1,7
Operators and Expressions 1.8
Control flow 1,9
Features 1,10
Modules 1,11
Data structures 1.12
Problem resolution 1,13
Object-oriented programming 1,14
Input and output 1,15
Exceptions 1,16
Standard Library 1,17
Further 1,18
Whats Next 1,19
Appendix: FLOSS 1,20
Appendix: About 1,21
Appendix: Revision History 1,22
Appendix: Translations 1,23
Appendix: Translation Procedures 1,24
Feedback 1,25
1
Introduction
A Python byte
"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, this is the book for you.
Sometime around 2004-05, when I was convinced I wasn't smart enough to be a programmer, I came across the original A
Byte of #Python, and that changed my entire perspective on computing and life, I owe it to a lot to that book. @swaroopch
had written. - Rahul on July 30, 2020
This is the book that introduced me to programming almost a decade ago. Thanks @swaroopch. You changed my life. -
Stefan Froelich on August 2, 2019
I am writing this email to thank you for the great help your book has given me. It was a really good book that I really
enjoyed. As a 15 year old who had never done programming before, trying to learn Python online was difficult and I
couldn't understand anything. But I felt like his book was much easier to understand and helped me get into the new world
of programming. Thanks to you, I can now write a high-level language with ease. I thought programming would be
difficult and boring, but with the help of your book, I realized how fun and interesting, yet simple, it can be! I would like to
thank you again for your hard work in helping beginners like me. - Prottyashita Tahiyat on September 17, 2019
This is the best beginner tutorial I've ever seen! Thanks for your effort. -Walt Michalik
The best I found was "A Byte of Python", which is just a brilliant book for beginners. It is well written, the concepts are
well explained with obvious examples. -Joshua Robin
start loving Python with every page you read - Herbert Feutl
perfect guide for Python beginners, will give you the key to unlock the magical world of Python - Dilip
I should be doing my actual "job", but I just found "A Python Byte". A great guide with great examples. - Biologist John
I recently started reading a Python Byte. Awesome work. And that too for free. Highly recommended for aspiring
pythonists. - Mangesh
A Python byte, 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 the best book ever - Yuvraj Sharma
A Byte of Python by @swaroopch is still the "best beginner's guide to Python" - Nickson Kaigi
2
Introduction
Thank you very much for writing A Byte Of Python. I started learning to code two days ago and I'm already creating some
simple games. Your guidance has been a dream and I just wanted to let you know how valuable it has been. -Franklin
I am from Dayanandasagar College of Engineering (7th sem, CSE). First of all, I want to say that your book "The Python
Byte" is too good a book for a Python beginner like me. The concepts are so well explained with simple examples that it
helped me learn Python easily. Thank you so much. - Madhura
I am an 18 year old IT student studying at the University of Ireland. I would like to express my gratitude to you for writing
your book "A Byte of Python", I already had knowledge of 3 programming languages: C, Java and Javascript, and Python
was by far the easiest language I have ever learned, and that was because mainly because his book was fantastic and made
learning Python very simple and interesting. It is one of the best written and easy to follow programming books I have ever
read.
Congratulations and keep up the great work. -Matt
Hello I'm from the Dominican Republic. My name is Pavel, I recently read your book A Byte of Python and I consider it
excellent!! :). I learned a lot from all the examples. Your book is a great help for newbies like me... - Pavel Simo
I am a student from China, now, I have read the book A byte of Python, Oh, it's beautiful. The book is very simple but can
help all beginners. You know I am interesting in Java and cloud computing many times, I have to code the program for the
server, so I think Python is a good choice, finish your book, I think not only is it a good choice, you should use Python . My
English is not very good, email to you, I just want to thank you! Best wishes to you and your family. -Roy Lau
I recently finished reading Byte of Python and thought I should really thank you. I was very sad to reach the final pages, as
now I have to go back to boring, tedious, etc. manuals to learn Python. Anyway, I really appreciate your book. Samuel
Young
Dear Swaroop, I am taking a class from an instructor who has no interest in teaching. We are using Learning Python,
Second Edition, from O'Reilly. It is not a text for beginners without programming knowledge, and an instructor who
should be working in another field. Thank you very much for your book, without it I would have no idea about Python and
programming. Thanks a million, you can break down the message to a level that beginners can understand and not
everyone. -Jose Duarte
I love your book! It's the best Python tutorial ever and a very useful reference. Brilliant, a true masterpiece! Keep up the
good work! - Chris-André Sommerseth
First of all, I want to thank you for this great book. I think it's a good book for those looking for a Python beginner tutorial.
I think it was two or two years ago when I first heard about this book. At that time, I still couldn't read any English books,
so I got a Chinese translation, which led me to the door of Python programming. Recently, I reread this book. This time, of
course, the English version. I couldn't believe I could read the entire book without my dictionary at hand. Of course, it's all
down to your effort to make this book easy to understand. - myd7349
I'm just emailing you to thank you for writing Byte of Python online. I had been trying out Python for a few months before
stumbling upon your book, and while I had limited success with pyGame, I never completed a program. Thanks to its
simplification of categories, Python really seems like an achievable goal. It seems like I have finally learned the basics and
can continue towards my real goal, game development. Once again, thank you SO MUCH for posting such to
Structured and useful guide to basic web programming. It pushed me in and out of OOP with an understanding where two
textbooks had failed. -Matt Gallivan
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 15 years
old, I live in Egypt and my name is Ahmed. Python was my second programming language. I learned Visual Basic 6 in
school, but I didn't enjoy it, however, I really enjoyed learning Python. I did the address book program and was successful.
I'll try to start making more programs and reading Python programs (if you could tell me the source it would be helpful). I'm
also going to start 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. Thank you. -Ahmed Mohammed
3
Introduction
A wonderful resource for beginners who want to learn more about Python is the 110-page A Byte of Python PDF tutorial
by Swaroop C H. It's well written, easy to follow, and may be the best introduction to Python programming available. -
Drew Ames
I ran through most of Byte of Python yesterday on my Nokia N800 and it's the easiest and most concise introduction to
Python I've found. Highly recommended as a starting point for learning Python. -Jason Delport
Byte of Vim and Python by @swaroopch is by far the best work on technical writing for me. Great reads #FeelGoodFactor
– Surendran
"Python Byte" the best by far (in response to the question "Can anyone suggest a good, inexpensive resource for learning
the basics of Python?") - Justin LoveTrue
The Byte Python Book was very helpful. Thanks big time :) Chinmay
I've always been a fan of A Byte of Python, made for both new and experienced programmers. -Patrick Harrington
I started learning Python a few days ago from your book...thanks for such a nice book. it's so well written, you made my
life easier...so you found a new fan of yours...that's me :) tons of thanks. - Gadadhari Bheem
Before I started learning Python, I acquired basic programming skills in Assembly, C, C++, C#, and Java. The real reason I
wanted to learn Python is that it is popular (people talk about it) and powerful (the reality). This book written by Mr.
Swaroop is a very good guide for both new and new Python programmers. It took 10 and a half days to review it. Great
help! - Fang Biyi (PhD Candidate ECE, Michigan State University)
Thank you very much for this book!! This book clarified many questions I had about certain aspects of Python, such as
object-oriented programming. I don't feel like an OO expert, but I know this book helped me with a first step or two. I've
now written several Python programs that actually do real things for me as a system administrator. They are all procedure-
oriented, but small by most people's standards. Again, thank you for this book. Thanks for having it on the web. --Beto
I just want to thank you for writing the first book on programming that I've actually read. Python is now my first language
and I can imagine all the possibilities. So thank you for giving me the tools to create things I never would have imagined I
could do before. - "Walrus"
I wanted to thank you for writing A Byte Of Python (versions 2 and 3). It has been invaluable to my learning experience in
Python and Programming in general. Needless to say, I am a beginner in the world of programming, a couple of months of
self-study at this point. I had been using youtube tutorials and some other online tutorials including other free books. I
decided to dig into your book yesterday, and I've learned more in the first few pages than in any other book or tutorial.
Some things I had been confused about were clarified with a GREAT example and explanation. I can't wait to read (and
learn) more!! Thank you very much for not only writing the book, but for putting it under the creative commons license
(free).
Thank God that there are selfless people like you who help and teach the rest of us. - Chris
I wrote to you in 2011 and I was getting into Python and wanted to thank you for your "A Byte of Python" tutorial. Without
him, I would have fallen by the wayside. I have since moved on to programming a number of functions in my organization
with this language with more on the horizon. I wouldn't call myself an advanced programmer by any means, but I now notice
the occasional request for help from others since I started using it. I discovered, while reading "Byte", why I had stopped
studying C and C++ and it was because the book I was given started with an example that contained an augmented task. Of
course, there was no explanation for this arrangement of operators and I fell headlong trying to make sense of what was on
the written page. As I remember, it was a most frustrating exercise that I finally abandoned. It doesn't mean that C or C++ is
impossible to learn, or even that I'm stupid, but it does mean that the documentation I worked my way through didn't 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 a computer symbol that is outside the syntax of the language being used, a student new to any field will
not understand his subject if he encounters words or symbols for which there are no definitions. . You get a "blue screen" so
to speak in any case. However, the solution is simple: look up the word or symbol and get the appropriate definition or
symbol and, lo and behold, the computer or student can continue. Your book or even that I'm stupid, but that means that the
documentation I worked with 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 a computer symbol that is outside the syntax of the language
4
Introduction
being used, a student new to any field will not understand his subject if he encounters words or symbols for which there are
no definitions. . You get a "blue screen" so to speak in any case. However, the solution is simple: look up the word or symbol
and get the appropriate definition or symbol and, lo and behold, the computer or student can continue. Your book or even
that I'm stupid, but that means that the documentation I worked with 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 a computer symbol that
is outside the syntax of the language being used, a student new to any field will not understand his subject if he encounters
words or symbols for which there are no definitions. . You get a "blue screen" so to speak in any case. However, the solution
is simple: look up the word or symbol and get the appropriate definition or symbol and, lo and behold, the computer or
student can continue. Your book Just as computers will not be able to understand a computer word or a computer symbol that
is outside the syntax of the language being used, a student new to any field will not understand his subject if he encounters
words or symbols that he does not understand. There are definitions. You get a "blue screen" so to speak in any case.
However, the solution is simple: look up the word or symbol and get the appropriate definition or symbol and, lo and behold,
the computer or student can continue. Your book Just as computers will not be able to understand a computer word or a
computer symbol that is outside the syntax of the language being used, a student new to any field will not understand his
subject if he encounters words or symbols that he does not understand. There are definitions. You get a "blue screen" so to
speak in any case. However, the solution is simple: look up the word or symbol and get the appropriate definition or symbol
and, lo and behold, the computer or student can continue. Your book finds the word or symbol and gets the appropriate
definition or symbol and lo and behold, the computer or student can continue. Your book finds the word or symbol and gets
the appropriate definition or symbol and lo and behold, the computer or student can continue. Your book
5
Introduction
it was so well put together that I found very little in it that I could not understand. So thanks. I encourage you to continue to
include full definitions of terms. The documentation with Python is good, once you know it (the examples are its strength
from what I see) but in many cases it seems that you have to know to understand the documentation which in my opinion is
not what it should be. Third-party tutorials express the need to clarify documentation and their success depends largely on
the words used to describe the terminology. I have recommended your book to many others. Some in Australia, some in the
Caribbean and some in the United States. It fills a niche that no one else does. I hope you are doing well and I wish you
every success in the future. - Nick
hey, this is ankush (19). I was facing great difficulty in getting started with Python. I tried many books, but they were all
bulkier and not goal-oriented; and then I found this lovely one, which made me love Python in no time. Thank you very
much for this "beautiful book." - Ankush
I would like to thank you for your excellent guide on Python. I am a molecular biologist (with little programming
experience) and for my work I need to handle large data sets of DNA sequences and analyze microscopic images. For
both, Python programming has been helpful, if not essential, in completing and publishing a 6-year project. That such a
guide is freely available is a clear sign that evil forces do not yet rule the world! :) - Luca
Since this will be the first language you will learn, you should use A Byte of Python. It really provides a proper
introduction to Python programming and is well-paced enough for the average beginner. The most important thing from
that moment on will be to start practicing creating your own small programs. - "{Not registered}"
Just to say a big happy thank you for publishing "A Byte of Python" and "A Byte of Vim". I found those books very
useful four or five years ago when I started learning programming. Right now I am developing a project that was a dream
for a long, long time and I just want to say thank you. Keep walking. You are a source of motivation. All the best. -
Jocimar
I finished reading One Byte of Python in 3 days. It's very interesting. Not a single page was boring. I want to understand
the Orca screen reader code. Hopefully your book has prepared me for that. - Dattatray
Hi, 'A Python Byte' is really a good read for Python beginners. So again, GOOD JOB! I am a Java & C developer with 4
years of experience in China. Recently, I want to do some work on the zim-wiki note project that uses pygtk to implement.
I read your book in 6 days and now I can read and write Python code examples. thank you for your contribution. Please
keep your enthusiasm to improve this world, this is just a little encouragement from China. - Read
I am Isen from Taiwan, a PhD student in the Department of Electrical Engineering, National Taiwan University. I would
like to thank you for your great book. I think it is not only easy to read, but also comprehensive and comprehensive for a
Python newcomer. The reason I read your book is that I am starting to work in the GNU Radio framework. His book
allowed me to grasp most of the important core ideas and skills of Python with minimal time. I also saw that you don't
mind readers sending you a thank you note in your book. So I really like your book and appreciate it. Thank you. - Isen I-
Chun Chao
The book is even used by NASA! It is used in their Jet Propulsion Laboratory with their Deep Space Network project.
Academic courses
This book is being used as teaching material in several educational institutions:
6
Introduction
License
This book is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License .
This means:
You are free to Share, that is, copy, distribute and transmit this book.
You can remix, that is, make changes to this book (especially translations). You
can use it for commercial purposes.
Keep in mind:
Please do not sell electronic or printed copies of the book unless you have clearly and prominently mentioned in the
description that these copies are not from the original author of this book.
Attribution should be displayed in the introductory description and cover page of the document by linking to
https://python.swaroopch.com and clearly indicating that the original text(s) can be retrieved from this
location. All code/scripts provided in this book are licensed under the BSD 3-clause License unless otherwise
noted.
Read now
You can read it online at https://python.swaroopch.com
Discharge
Visit https://github.com/swaroopch/byte-of-python/releases/latest to download a PDF file (best for desktop reading) or EPUB
file (best for devices like mobile, tablets, e-book readers ).
Visit https://github.com/swaroopch/byte-of-python for the raw content (to suggest fixes, changes, translate, etc.)
7
Dedication
Dedication
To Kalyan Varma and many other seniors at PESIT who introduced us to GNU/Linux and the world of open source.
In memory of Atul Chitnis , a friend and guide who will be greatly missed.
Towards pioneers who made the Internet possible . This book was first written in 2003. It still remains popular, thanks to the nature
of
sharing knowledge on the Internet as the pioneers imagined.
8
Preface
Preface
Python is probably one of the few programming languages that is both simple and powerful. This is good for beginners and
experts alike, and most importantly, it's fun to program with. This book aims to help you learn this wonderful language and show
you how to get things done quickly and painlessly - in effect, 'The Antidote to Your Programming Problems'.
The goal is that if all you know about computers is how to save text files, then you can learn Python from this book. If you have prior
programming experience, you can also learn Python from this book.
If you have prior programming experience, you'll be interested in the differences between Python and your favorite programming
language; I have highlighted many of those differences. A little warning though, Python will soon become your favorite programming
language.
Official website
The official website of the book is https://python.swaroopch.com where you can read the entire book online, download the latest
versions of the book, buy a print copy and also send me your feedback.
Success in life is not so much a matter of talent and opportunity as it is of focus and perseverance. - C.W. Wendte
9
About Python
About Python
Python is one of those rare languages that can boast of being simple and powerful. You'll be pleasantly surprised to see how easy it
is to focus on the solution to the problem rather than the syntax and structure of the language you're programming in.
Python is a powerful programming language that is easy to learn. It has efficient high-level data structures and a simple
but effective approach to object-oriented programming. Python's elegant syntax and dynamic typing, along 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.
Python Features
Simple
Python is a simple and minimalist language. Reading a good Python program feels almost like reading English, albeit very strict
English! This pseudocode nature of Python is one of its greatest strengths. It allows you to focus on the solution to the problem
rather than the language itself.
Easy to learn
As you will see, Python is extremely easy to get started with. Python has an extraordinarily simple syntax, as already mentioned.
Laptop
Due to its open source nature, Python has been ported (i.e. changed to work on) many platforms. All of your Python programs
can work on any of these platforms without requiring any changes if you are careful enough to avoid any system-dependent
features.
10
About Python
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.
Interpreted
This requires a bit of explanation.
A program written in a compiled language such as C or C++ is converted from the source language, i.e. C or C++, to a language
spoken by your computer (binary code, i.e. 0 and 1) using a compiler with various indicators and options. When you run the
program, the linker/loader software copies the program from the hard drive to memory and starts running it.
Python, on the other hand, does not need compilation to binary. Simply run the program directly from the source code.
Internally, Python converts the source code into an intermediate format called bytecodes and then translates it into your
computer's native language and then executes it. All of this actually makes using Python much easier, since you don't have to
worry about compiling the program, making sure the right libraries are linked and loaded, etc. This also makes your Python
programs much more portable, as you can simply copy your Python program to another computer and it just works!
Object-oriented
Python supports procedure-oriented programming and object-oriented programming (OOP). In procedure-oriented languages,
the program is based on procedures or functions that are nothing more than reusable program pieces. In object-oriented
languages, the program is based on objects that combine data and functionality. Python has a very powerful but simplistic way
of doing OOP, especially when compared to large languages like C++ or Java.
Extensible
If you need a critical piece of code to run very fast or want some algorithm fragment not to be open, you can code that part of your
program in C or C++ and then use it from your Python program.
Integrable
You can embed Python within your C/C++ programs to provide scripting capabilities to the users of your program.
Extensive libraries
The Python standard library is huge. 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
(interfaces user graphics), and other things that depend on the system. Remember, all of this is always available wherever Python
is installed. This is called the Python Stacks Included philosophy.
In addition to the standard library, there are several other high-quality libraries that you can find in the Python Package Index .
Summary
Python is indeed an exciting and powerful language. It has the right combination of performance and features that make writing
Python programs fun and easy.
Python 3 vs 2
You can ignore this section if you are not interested in the difference between "Python version 2" and "Python version 3". But
keep in mind which version you are using. This book is written for Python version 3.
11
About Python
Remember that once you have properly understood and learned how to use one version, you can easily know the differences and
use the other. The hard part is learning to program and understanding the basics of the Python language itself. That's our goal in
this book, and once you've achieved that, you can easily use Python 2 or Python 3 depending on your situation.
Eric S. Raymond is the author of "The Cathedral and the Bazaar" and is also the person who coined the term Open Source.
He said that Python has become his favorite programming language . This article was the real inspiration for my first
Python brush.
Bruce Eckel is the author of the famous books 'Thinking in Java' and 'Thinking in C++'. He says that no language has made
him more productive than Python. He says that Python is perhaps the only language that focuses on making things easier for
the programmer. Read the full interview for more details.
Peter Norvig is a well-known Lisp author and head of search quality at Google (thanks to Guido van Rossum for pointing
him out). He said that writing Python is like writing in pseudocode . He says Python has always been an integral part of
Google. In fact, you can verify this statement by looking at the Google Jobs page which lists knowledge of Python as a
requirement for software engineers.
12
Facility
Facility
When we refer to "Python 3" in this book, we will mean any version of Python equal to or greater than version Python 3.6.0 .
Installation on Windows
Visit https://www.python.org/downloads/ and download the latest version. At the time of writing, it was Python 3.5.1. Installation is
like any other Windows-based software.
Please note that if your version of Windows is older than Vista, you should download Python 3.4 only as later versions require
newer versions of Windows.
CAUTION: Make sure to check the Add Python 3.5 to PATH option.
To change the installation location, click Customize installation , then Next and enter C:\python35 (or another appropriate
location) as the installation location.
If you didn't check the Add Python 3.5 PATH option above, check Add Python to Environment Variables . This does the same
thing as Adding Python 3.5 to PATH on the first installation screen.
You can choose to install Launcher for all users or not, it doesn't matter much. The launcher is used to switch between different
installed Python versions.
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 Command Prompt ) to fix it. Otherwise, go to the Running Python prompt on
NOTE: For people already familiar with programming, if you are familiar with Docker, see Python on Docker and Docker on
Windows .
For Windows 2000, XP, 2003, click Control Panel -> System -> Advanced -> Environment Variables . Click the variable
named PATH in the System Variables section, then select Edit and Add ; C:\Python35 (check that this folder exists, it will be
different for newer versions of Python) at 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 reboot the
system. For Windows NT, use the AUTOEXEC.NT file.
Click System, on the right you will see "View basic information about your computer"
On the left is a list of tasks, the last of which is Advanced System Settings . Click on that.
The Advanced tab of the System Properties dialog box is displayed. Click the Environment Variables button at the
bottom right.
In the bottom box titled System Variables, scroll down to Path and click the Edit button.
Change your path as necessary.
Reboot your system. Vista didn't pick up the system path environment variable change until I rebooted.
13
Facility
Click OK and you're done. A reboot is not necessary, however, you may need to close and reopen the command prompt.
Windows Start Menu > Settings > About > System Information (this is all the way to the right) > Advanced System Settings
> Environment Variables (this is towards the bottom) > (then highlight Variable Path and click Edit ) > New > (type the
location of your Python. For example, C:\Python35\ )
To open the terminal in Windows, click the Start button and click Run. In the dialog box, type cmd and press the [enter] key.
Installation on Mac OS
For Mac OS X users, use Homebrew : brew install python3 .
To check, open the terminal by pressing [Command + Space] keys (to open Spotlight search), type Terminal and press
[enter] key. Now, run python3 and make sure there are no errors.
Installation on GNU/Linux
For GNU/Linux users, use your distribution's package manager to install Python 3, for example on Debian and Ubuntu: sudo
apt-get update && sudo apt-get install python3 .
To verify, open the terminal by opening the Terminal app or by pressing Alt + F2 and entering gnome-terminal. If that doesn't
work, check the documentation for your particular GNU/Linux distribution. Now, run python3 and make sure there are no errors.
NOTE: $ is the-Vshell prompt. It will be different for you depending on the operating system configuration on your computer, so
$python3
Python
I will 3.6.0
indicate the message with the $ symbol only.
CAUTION: The output may be different on your computer, depending on the version of Python software installed on your computer.
Summary
14
Facility
From now on, we will assume that you have Python installed on your system.
15
First steps
First steps
Now we will 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 to use Python to run your program: using the interpreter's interactive prompt or using a source file. Now we
will see how to use both methods.
Once you've started Python, you should see >>> where you can start writing things. This is called a Python interpreter prompt.
Followed
print(by"Hello
the [enter] key.
World" ) You should see the words Hello World printed on the screen.
Below is an example of what you should see when using a Mac OS X computer. Details about the Python software will differ
depending on your computer, but the prompt part (i.e. from >>> onwards) should be the same regardless of the operating system.
Note that Python gives you the output of the line immediately! What you just entered is a single Python statement. We use
print to print (unsurprisingly) whatever value you give it. Here, we are providing the text Hello world and this
$python3
is quickly printed on the screen.
Python 3.6.0 (default , Jan 12 2017 , 11:26:36 )
[GCC 4.2.1 Supported by Apple LLVM 8.0.0 (clang- 800.0.38 )] in
How to exit
Darwin the interpreter
Type "help" , "copyright" message
, "credits" or "license" for more
information.
>>> print( "Hello World" )
If you are using a GNU/Linux or OS X shell, you can exit the interpreter prompt by pressing [ctrl+d] or by entering exit()
Hello World
(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.
Choose an editor
We can't write our program at the interpreter prompt every time we want to run something, so we have to save them in files and
we can run our programs as many times as we want.
To create our Python source files, we need editing software where we can write and save. A good programmer's editor will make
your life easier when writing source files. Therefore, choosing an editor is crucial. You have to choose a publisher like you
would choose a car you would buy. A good editor will help you write Python programs easily, making your journey more
comfortable and will help you reach your destination (achieve your goal) in a much faster and safer way.
16
First steps
One of the very basic requirements is syntax highlighting where all the different parts of your Python program are colored so
that you can see your program and visualize its execution.
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; is a poor choice because it does not highlight syntax and, more importantly, does
not support text indentation, which is very important in our case, as we will see later. Good editors will do this automatically.
If you are an experienced programmer, you should already be using Push 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, I recommend learning how to use either of them as it will serve you
well in the long run. However, as I mentioned before, beginners can start with PyCharm and focus learning on Python instead of
the editor at this point.
To reiterate, choose a suitable editor: it can make writing Python programs more fun and easier.
PyCharm
PyCharm Educational Edition is a free editor that you can use to write Python programs. When
you open PyCharm, you will see this, click Create New Project:
17
First steps
18
First steps
Change untitled to helloworld as the project location, you should see details similar to this:
19
First steps
Right click on the Hello World button in the sidebar and select New -> Python File :
20
First steps
21
First steps
Delete the lines that are already present and now write the following:
Nowprint(
right click on what
"Hello you) typed (without selecting the text) and click Run 'hello'.
World"
You should now see the output (what it prints) of your program:
22
First steps
Phew! It was quite a few steps to get started, but from now on, whenever we ask you to create a new file, remember to right click on
helloworld on the left -> New -> Python File and continue with the same steps to write and run as shown above.
You can find more information about PyCharm on the PyCharm Quickstart page.
Push
1. Install Push
Mac OS X users should install the macvim package through HomeBrew
Windows users should download the "self-installing executable" from the Vim website
GNU/Linux users should obtain Vim from their distribution's software repositories, for example Debian and Ubuntu
users can install the vim package.
2. Install jedi-vim autocomplete plugin.
3. Install corresponding Jedi python package: install pip -U jedi
Emacs
1. Install Emacs 24+ .
Mac OS
GNU/Linux users should obtain Emacs from their distribution's software repositories, for example Debian and
Ubuntu users can install the emacs24 package.
2. Install ELPY
23
First steps
Now let's get back to programming. There is a tradition that whenever you learn a new programming language, the first program
1
you write and run is the 'Hello World' program; all it does is say 'Hello world' when you run it. Like Simon Cozens says, it's the
"traditional incantation to the programming gods to help you learn the language better."
Start your editor choice, enter the following program and save it as hello.py. If you
are using PyCharm, we have already discussed how to run from a source file .
For other editors, open a new hello.py file and type this:
Where should
print( I saveWorld"
"Hello the file?
) To any folder for which you know the folder location. If you don't understand what that means,
create a new folder and use that location to save and run all your Python programs:
/tmp/py on Mac OS
/tmp/py on GNU/Linux
C:\py on Windows
To create the above folder (for the OS you are using), use the mkdir command in the terminal, for example mkdir
/tmp/py .
IMPORTANT: Always make sure you give it the .py file extension, for example foo.py. To run
$python
hello.py hello
world
24
First steps
If you got the result as shown above, congratulations! - you have successfully run your first Python program. You have
successfully passed the hardest part of learning programming, that is, getting started with your first program!
In case you get an error, write the above program exactly as shown above and run the program again. Note that Python is case-
sensitive, that is, printing is not the same as Print; note the lowercase p in the former and the uppercase P in the latter. Also,
make sure there are no spaces or tabs before the first character on each line; We'll see why this is important later.
A Python program is made up of statements. In our first program, we only have one statement. In this statement, we call
statement print to which we supply the text "hello world".
Getting help
If you need quick information about any function or statement in Python, you can use the built-in help function. This is very
useful, especially when using interpreter prompting. For example, run help('len'): This displays help for the len function used to
count the number of elements.
Likewise, you can learn about almost anything in Python. Use help() to get more information about using the help itself.
In case you need to get help for operators like return, then you need to put those quotes in quotes like help('return') so that Python
doesn't get confused about what we are trying to do.
Summary
You should now be able to write, save, and run Python programs with ease.
Now that you are a Python user, let's learn some more Python concepts.
1.
the author of the amazing book 'Beginning Perl' ↩
25
The
essenti
The essential
Print Hello world is not enough, is it? You want to do more than that, you want to take some input, manipulate it and get
something out of it. We can achieve this in Python using constants and variables, and we will also learn some other concepts in
this chapter.
Comments
Comments are any text to the right of the # symbol and are primarily useful as notes to the reader of the program.
For example:
either:
print( 'Hello World' ) # Note that print is a function
Use#asNote
manythat
useful comments
print is a as you can in your program to:
function print( 'Hello World'
) Explain assumptions
Explain important
decisions Explain
important details
explain the problems you are trying to solve
explain the problems you are trying to overcome in your program, etc.
The code tells you how, the comments should tell you why .
This is useful for readers of your program so that they can easily understand what the program does. Remember, that person may
be you after six months.
Literal constants
An example of a literal constant is a number like 5 , 1.23 , or a string like 'This is a string' or "It's a string!" .
It is called literal because it is literal; you use its value literally. The number 2 always represents itself and nothing else; It is a
constant because its value cannot be changed. Therefore, all of these are called literal constants.
Numbers
Numbers are mainly of two types: integers and floats.
Examples of floating point numbers (or floats for short) are 3.23 and 52.3E-4 . The E notation indicates powers of 10. In this
case, 52.3E-4 means 52.3 * 10^-4^ .
There is no separate long type. The int type can be an integer of any size.
26
The
essenti
String instruments
A string is a sequence of characters. Strings are basically a bunch of words.
You will use strings in almost every Python program you write, so pay attention to the next part.
A phrase
You can specify strings using single quotes such as "Quote me on this." All
whitespace, that is, spaces and tabs, within the quotes are preserved as is.
Double quotes
Double-quoted strings work exactly the same as single-quoted strings. An example is "What's your name?" .
Triple Quotes
You can specify multi-line strings using triple quotes - ("" "or '''). You can freely use single and double quotes inside triple
quotes. An example is:
Strings
'''Thisare
is aimmutable
multi-line string. This is the first
line. This is the second line.
There is no separate char data type in Python. There is no real need and I'm sure you won't miss it.
Remember that single-quoted strings and double-quoted strings are the same, they do not differ in any way.
Production:
age = 20
name = 'Swaroop'
$python str_format.py
print( "{0} was {1} years old when he wrote this book" . format (name,
Swaroop
age)) was (
print 20"Why
years
isold
{0}when he wrote
playing this python?" . format (name))
with that
book Why is Swaroop playing with that python?
27
The
essenti
A string can use certain specifications, and the format method can then be called to replace those specifications with the
corresponding arguments to the format method.
Notice the first usage where we use {0} and this corresponds to the name of the variable that is the first argument of the format
method. Similarly, the second specification is {1} corresponding to age, which is the second argument of the format method.
Note that Python starts counting from 0, which means the first position is at index 0, the second position is at index 1, and so on.
Note that we could have achieved the same thing using string concatenation:
but name
that is+much
'es' uglier
+ strand error+ prone.
(age) Second, the conversion to string would be done automatically by the format method
'years'
instead of the explicit conversion to strings needed in this case. Thirdly, when we use the format method, we can change the
message without having to deal with the variables used and vice versa.
Also note that the numbers are optional, so you could also have written like:
which
agewill
= 20give the exact same output as the previous program.
name = 'Swaroop'
We can also name the parameters:
print( "{} was {} years old when he wrote this book" . format (name,
age)) print ( "Why is {} playing with that python?" . format (name))
which
agewill
= 20give the exact same output as the previous program.
name = 'Swaroop'
Python 3.6 introduced a shorter way of making named parameters, called "f-strings":
print( "{name} was {age} years old when he wrote this book" . format (name = name, age =
age)) print ( 'Why is {name} playing with that python?' . format (name = name ))
which
agewill
= 20give the exact same output as the previous program.
name = 'Swaroop'
What Python does in the format method is that it substitutes each argument value in place of the specification. There may be
impression( f '{name} was {age} years old when he wrote this book' ) # notice the 'f' before
more detailed specifications such as:
the string impression( f'Why is {name} playing with that python? ' ) # notice the 'f' before
the string
# decimal precision (.) of 3 for float '0.333'
print( '{0: .3f}' . format ( 1.0 / 3 ))
# fill with underscores (_) with text centered
# (^) at 11 width ' Hello ' print(
'{0:_^11}' . format ( 'Hello' ))
# based on 'Swaroop wrote a Python byte' keyword
print( "{name} wrote {book}" . format (name = 'Swaroop' , book = 'A Python Byte' ))
28
The
essenti
Production:
Since we're discussing formatting, note that print always ends with an invisible "new line" character (\n) so repeated calls to print
0.333
Or you
ab can end with a space:
Theprint(
output is:
'a' , end = '' )
print( 'B' , end = '' )
print( 'C' )
to B.C.
Escape sequences
Suppose you want to have a string containing a single quote ('), how will you specify this string? For example, the string is "What
is your name?" . You cannot specify 'What is your name?' because Python will get confused as to where the string starts and ends.
Therefore, you will need to specify that this single quote does not indicate the end of the string. This can be done with the help of
what is called escape sequence. The single quote is specified as \': notice the backslash. Now, you can specify the string as 'What
is your name?' .
Another way to specify this specific string would be "What is your name?" that is, using double quotes. Similarly, you must
use an escape sequence to use a double quote on a double-quoted string. Additionally, you must indicate the backslash using
the escape sequence \\.
What if I wanted to specify a two-line string? One way is to use a string enclosed in triple quotes as shown previously or you can
use an escape sequence for the newline character - \n to indicate the beginning of a new line. An example is:
Another useful escape sequence you should know about is tab:\t. There are many more escape sequences, but I have only
'This is the first line\nThis is the second line'
mentioned the most useful ones here.
One thing to note is that in a string, a single backslash at the end of the line indicates that the string continues on the next line,
but no new line is added. For example:
29
The
essenti
It is equivalent to
Always use raw strings when working with regular expressions. Otherwise, a lot of backtracking may be required. For
example, backreferences can be named '\\ 1' or '\ 1'.
Variable
Using only literal constants can soon become boring; we need some way to store any information and manipulate it as well. This
is where the variables come into play. Variables are exactly what their name implies: their value can vary, that is, you can store
anything using a variable. Variables are just parts of your computer's memory where you store certain information. Unlike literal
constants, you need some method to access these variables and therefore give them names.
Identifier designation
Variables are examples of identifiers. Identifiers are names given to identify something. There are some rules you should follow
for naming identifiers:
The first character of the identifier must be a letter of the alphabet (uppercase ASCII or lowercase ASCII or Unicode
character) or an underscore (_).
The rest of the identifier name can consist of letters (uppercase ASCII or lowercase ASCII or Unicode character),
underscores (_), or digits (0-9).
Identifier names are case-sensitive. For example, myname and myName are not the same. Note the lowercase n in the
former and the uppercase N in the latter.
Examples of valid identifier names are I , name_2_3 . Examples of invalid identifier names are 2 things , this is
Type of data
Variables can contain values of different types called data types. The basic types are numbers and strings, which we have already
discussed. In later chapters, we'll see how to create our own types using classes .
Object
Remember, Python refers to everything used in a program as an object. This is understood in a generic sense. Instead of saying "the
something "', we say "the object."
Python is strongly object-oriented in the sense that everything is an object, including numbers, strings, and functions.
30
The
essenti
Now we will see how to use variables together with literal constants. Save the following example and run the program.
For PyCharm
1. Open PyCharm .
2. Create a new file with the mentioned file name.
3. Write the program code given in the example.
4. Right click and run the current file.
NOTE: Whenever you have to provide command line arguments , click Run -> Edit Configurations and type the arguments
in the Script Parameters: section and click the OK button:
# File name:
var.py i = 5
print(
i)i=i+
1
31
The
essenti
print (i)
Production:
(=). string.
This lineThis is the second
is called a statement because it indicates that something must be done and in this case we plug in the name of the
line.
variable
I to value 5. Next, we print the value of i using the print statement which, as expected, simply prints the
value of the variable to the screen.
Then we add 1 to the value stored in i and store it again. Then we print it and as expected we get the value 6.
Similarly, we assign the string literal to the variable s and then print it.
Variables are used simply by assigning them a value. No data type declaration or definition is needed/used.
An example of a logical line is a statement like print('hello world') - if this was on a line by itself (as you see it in an editor), then
this also corresponds to a physical line.
Implicitly, Python encourages the use of a single statement per line, which makes the code more readable.
If you want to specify more than one logical line on a single physical line, you must explicitly specify it with a semicolon (;)
indicating the end of a logical line/statement. For example:
i = 5 ; print (i)
32
The
essenti
However, I strongly recommend that you limit yourself to writing a maximum of a single logical line to each physical line. The
idea is that you should never use semicolons. In fact, I have never used or seen a semicolon in a Python program.
There is one type of situation where this concept is really useful: if you have a long line of code, you can split it into multiple physical
lines using the backslash. This is known as an explicit line join:
Production:
s = 'This is a string. \
This continues the chain.
' fingerprints)
Similar,
This is a rope. This continues the chain.
is the
i same
= as
\ 5
Sometimes
i = 5 there is an implicit assumption that it is not necessary to use a backslash. This is the case where the logical line has a
leading parenthesis, leading brackets, or leading braces but no trailing braces. This is called an implicit line join. You can see this
in action when we write programs using list in later chapters.
Bleeding
White space is important in Python. In fact, the white space at the beginning of the line is important. This is called indentation.
The leading white space (spaces and tabs) at the beginning of the logical line is used to determine the indentation level of the
logical line, which in turn is used to determine the grouping of statements.
This means that statements that go together must be equally indented. Each of these sets of statements is called a block. We will
see examples of the importance of blocks in later chapters.
One thing to remember is that incorrect indentation can lead to errors. For example:
When
i =you
5 run this you get the following error:
# Bug below! Notice a single space at the beginning of the line.
print( 'The value is' , I)
Notice that there
File
print( is a single
thespace
"whitespace.py",
'I repeat, atis'
line
value the
3 beginning
, I) of the second line. The error indicated by Python tells us that the program
syntax isprint ('The value is', i)
invalid, that is, the program was not written correctly. What this means for you is that you can't arbitrarily start new
^
blocks of statements (except
IndentationError: the default
unexpected main block you've been using all along, of course). Cases where you can use
indentation
33
The
essenti
How to bleed
Use four spaces for indentation. This is the official recommendation of the Python language. Good editors will
automatically do this for you. Be sure to use a consistent number of spaces for indentation; otherwise your program will not
run or will have unexpected behavior.
Python will always indent blocks and never use curly braces. Run more. fromfutureimport suspenders learn
Summary
Now that we've covered a lot of nitty-gritty details, we can move on to more interesting things, like control flow statements.
Make sure you are comfortable with what you have read in this chapter.
34
Operators and Expressions
Operators are functions that do something and can be represented by symbols like + or special keywords. Operators require
some data to operate and such data is called operands. In this case, 2 and 3 are the operands.
Operators
We will briefly see the operators and their use.
Note that you can evaluate the expressions given in the examples using the interpreter interactively. For example, to test the
expression 2 + 3, use the Python interpreter's interactive prompt:
Gives the subtraction of one number from the other; if the first operand is absent, it is assumed to be zero.
-5.2 gives a negative number and 50 - 24 gives 26 .
* (multiply)
Gives the multiplication of the two numbers or returns the string repeated so many times.
2*3 gives 6 . 'la' * 3 gives 'lalala' .
** (energy)
Divide x by y
13/3 gives 4.333333333333333
Divide x by y and round your answer down to the nearest whole value. Note that if one of the values is a float, you will
get a float.
13 // 3 gives 4
-13 // 3 gives -5
% (module)
35
Operators and Expressions
Shifts the bits of the number to the left by the specified number of bits. (Each number is represented in memory by bits
or binary digits, i.e. 0 and 1)
2 << 2 gives 8 . 2 is represented by 10 in bits.
Shifting left by 2 bits gives 1000, which represents the decimal 8.
>> (Right turn)
Shifts the bits of the number to the right by the specified number of bits.
11 >> 1 gives 5 .
11 is represented in bits by 1011 which when shifted to the right by 1 bit gives 101 which is
the decimal 5. (And bits)
AND
And from bit-level numbers: if both bits are 1, the result is 1. Otherwise it is 0.
5 and 3 gives 1 ( 0101 and 0011 gives 0001 )
| (bitwise OR)
Bitwise XOR of numbers: If both bits (1 or 0) are the same, the result is 0. Otherwise it is 1.
5^3 gives 6 ( O101^0011 gives 0110 )
~ (bit inversion)
Returns if x is less than y. All comparison operators return True or False. Note the capitalization of these names.
5 <3 gives False and 3 <5 gives True .
Comparisons can be chained arbitrarily: 3 <5 <7 gives True.
> (larger than)
== (equal to)
no (NOT boolean)
36
Operators and Expressions
If x is,TRUE
return Fake . If x is False , it returns True .
x = True; no x returns False .
or (boolean OR)
Realize
a = 2var=var operation expression becomes var=expression operation .
a* = 3
Evaluation order
If you had an expression like 2 + 3 * 4, is the addition or multiplication done first? Our high school math tells us that
multiplication should be done first. This means that the multiplication operator has higher precedence than the addition operator.
The following table provides the precedence table for Python, from lowest precedence (least binding) to highest precedence (most
binding). This means that in a given expression, Python will first evaluate the operators and expressions at the bottom of the table
before those listed at the top of the table.
The following table, taken from the Python Reference Manual , is provided for the sake of completeness. It is much better to use
parentheses to group operators and operands appropriately to explicitly specify precedence. This makes the program more
readable. See Changing the evaluation order below for more details.
37
Operators and Expressions
*, /, //,
: Multiplication, division, floor division and remainder
+x, -x,
: Positive, negative, bitwise NOT
*
: Exponentiation
Operators that we have not yet encountered will be explained in later chapters.
Operators with the same precedence are listed in the same row in the table above. For example, + and - have the same
precedence.
Using parentheses has an additional advantage: it helps us change the order of evaluation. For example, if you want addition to
be evaluated before multiplication in an expression, you can write something like (2 + 3) * 4.
Associativity
Operators are usually associated from left to right. This means that operators with the same precedence are evaluated from left to
right. For example, 2 + 3 + 4 evaluates to (2 + 3) + 4.
Expressions
Example (save as expression.py ):
Production:
length = 5
amplitude = 2
How$area
does
= itlength
python work* width
expression.py Area
print( 'The area is'is,
Thearea)
length and width of the rectangle
10 are stored in variables with the same name. We use them to calculate the area and perimeter
of the rectangle with the help of expressions. We store the result of the length * width expression in the variables area and then
print it using the print function. In the second case, we directly use the expression value 2 * (length + width) in the print function.
38
Operators and Expressions
Also, notice how Python beautifully prints the output. Although we haven't specified a space between 'The area is' and the area of
the variable, Python puts it in for us so that we get a nice clean result and the program is much more readable this way (since we
don't have to worry about spacing in the strings we use for output). This is an example of how Python makes life easier for the
programmer.
Summary
We have seen how to use operators, operands and expressions: these are the basic building blocks of any program. Next, we will
see how to make use of these in our programs using declarations.
39
Control flow
Control flow
In the programs we have seen so far, there have always been a series of statements faithfully executed by Python in exact order
from top to bottom. What if you wanted to change the flow of how it works? For example, do you want the program to make
some decisions and do different things depending on different situations, such as printing 'Good morning' or 'Good evening'
depending on the time of day?
As you may have guessed, this is achieved using control flow statements. There are three control flow statements in Python:
Yes , for and time .
The if statement
The if statement is used to check a condition: if the condition is true, we execute a block of statements (called if block), otherwise we
process another block of statements (called else block). The else clause is optional.
Production:
number = 23
guess = Int ( contribution ( 'Enter an integer:' ))
How$python
Ifdoes it if.py
guess work
== number:
Enter a whole
# The number:
new block 50
starts here
No, print(
it's a Congratulations,
little lower thanyou guessed it.
that)Done
print( '(but you don't win any
prizes!)' ) # The new block ends here
$python
elif if.py
guess
Enter a whole#number: 22
<number:
No, Another
it's a little
block higher than that
Doneprint( 'No, it's a little higher than
that' ) # You can do whatever you want in
$python if.py
a block...
Enter
the an :
rest integer: 23
Congratulations, you it's
impression( 'No, guessed
a little lower than that' )
it. #
(but
youyou don't
must havewin any > number to get here
guessed
prizes!) Done
print( 'Done' )
40
Control flow
In this program, we take guesses from the user and check if it is the number we have. We set the variable number to any integer
we want, say 23. Then, we take the user's guess using the input() function. Functions are just reusable programs. We will read
more about them in the next chapter .
We supply a string to the built-in input function which prints it to the screen and waits for user input. Once we enter something
and press the kbd:[enter] key, the input() function returns what we entered, as a string. We then convert this string to an integer
using int and then store it in the variable guess. Int is actually a class, but all you need to know now is that you can use it to
convert a string to an integer (assuming the string contains a valid integer in the text).
Next, we compare the user's guess with the number we have chosen. If they are the same, we print a success message. Note that
we use indentation levels to tell Python which statements belong to which block. This is why indentation is so important in
Python. I hope you stick to the "consistent indentation" rule. It's you?
Notice how the if statement contains a colon at the end; we are telling Python that a block of statements follows.
Then, we check if the guess is less than the number, and if so, we inform the user that they must guess a little more than that.
What we have used here is the elif clause which actually combines two related if else-if else statements into one combined if-
elif-else statement. This makes the program easier and reduces the amount of indentation required.
The elif and else statements must also have a colon at the end of the logical line followed by its corresponding block of
statements (with proper indentation, of course)
You can have another if statement inside the if block of an if statement and so on; This is called a nested if statement.
Remember that the elif and else parts are optional. A valid minimum if statement is:
Yeah true :
print( 'If true' )
Once Python has finished executing the entire if statement along with the associated elif and else clauses, it moves on to the next
statement in the block containing the if statement. In this case, it is the main block (where the program execution begins), and the
next instruction is the print ('Ready') statement. After this, Python sees the ends of the program and simply terminates.
Although this is a very simple program, I have been pointing out many things that you should notice. These are all pretty
straightforward (and surprisingly simple for those of you with C/C++ experience). You will have to be aware of all of these things
initially, but after a little practice you will become comfortable with them and it will all feel "natural" to you.
There is no switch statement in Python. You can use an if..elif..else statement to do the same thing (and in some cases, use
a dictionary to do it fast)
number = 23
running =
True
running time :
guess = Int ( contribution ( 'Enter an integer:' ))
If guess == number:
41
Control flow
print( 'Done' )
Production:
How$python
does it while.py
work
Enter an integer:
In this
50 program, we are still playing the guessing game, but the advantage is that the user can keep guessing until they guess
No, it's a little lower than
correctly; It is not necessary to repeatedly run the program for each divination, as we have done in the previous section. . This
that. Enter a whole number: 22
aptlyNo,
demonstrates the use
it's a little of thethan
higher while statement.
that. Enter an integer: 23
We Congratulations,
move the input andyou
if statements inside the while loop and set the variable being executed to True before the while loop.
guessed it.
First,
Thewewhile
checkloop
if thehas
running variable is True and then proceed to execute the corresponding while block. Once this block has
ended. Made
been executed, the condition is checked again, which in this case is the variable being executed. If true, we execute the while
block again, otherwise we continue by executing the optional else block and then continue with the next statement.
The else block is executed when the while loop condition becomes False; This may even be the first time the condition is
verified. If there is an else clause for a while loop, it is always executed unless you exit the loop with a
statement breakage .
True and false are called boolean types and you can think of them as equivalent to the value 1 and 0
respectively.
Remember that you can have an else clause for the while loop.
The by circle
The for..in statement is another looping statement that iterates over a sequence of objects, that is, it goes through each element in a
sequence. We will see more about sequences in detail in later chapters. What you need to know now is that a sequence is just an
ordered collection of elements.
times I in distance ( 1 ,
5 ): print (i)
the rest :
print( 'The for loop has ended' )
42
Control flow
Production:
How$python
does it work
for.py 1
In this
2 program, we are printing a sequence of numbers. We generate this sequence of numbers using the built-in range
3
function.
4
The for loop has ended
What we do here is we give it two numbers and the range returns a sequence of numbers starting from the first number and going
to the second number. For example, the range (1,5) gives the sequence [1, 2, 3, 4]. By default, the range takes a step count of 1.
If we provide a third number to the range, then that becomes the step count. For example, the range (1,5,2) gives [1,3].
Remember that the range extends to the second number, that is, it does not include the second number.
Note that distance() outputs only one number at a time, if you want the entire list of numbers, call list() on distance() , for
example list(range(5)) will result in [0, 1, 2. 3. 4] . Lists are explained in the data structures chapter .
The for loop then iterates over this range - for i in the range (1,5) is equivalent to for i in [1, 2, 3, 4] which is like assigning each
number (or object) in the sequence to i, one at a time, and then execute the block of statements for each value of
YO . In this case, we simply print the value in the statements block.
Remember that the else part is optional. When included, it is always executed once after the for loop ends, unless a break
statement is encountered.
Remember that the for..in loop works for any sequence. Here, we have a list of numbers generated by the built-in range
function, but in general we can use any type of sequence of any type of objects. We will explore this idea in detail in later
chapters.
Python's for loop is radically different from C/C++'s for loop. C# programmers will notice that the for loop in Python is
similar to the foreach loop in C#. Java programmers will notice that the same is similar to for (int i: IntArray) in Java 1.5.
In C/C++, if you want to write for (int i = 0; i <5; i++) , then in Python you write only for i in the range (0,5) .
As you can see, the per loop is simpler, more expressive, and less error-prone in Python.
An important note is that if you escape a for or time loop, any corresponding loops else the block is not executed.
True time :
s = input ( 'Enter something:'
) If s == 'leave' :
rip
print( 'The length of the string is' , len
( print( 'Done' )
43
Control flow
Production:
How$python
does it break.py
work
Enter something: programming is fun
In this program,
String we is
length repeatedly
18 take user input and print the length of each input each time. We provide a special condition to
stopEnter something: When the job is
the program by checking if the user input is 'exit'. We stop the program by exiting the loop and reach the end of the
finished The length of the rope is 21
program.
Enter something: If you want your work to be fun
too: the length of the rope is 37
TheEnter
lengthsomething:
of the input use
string can be found out using the len function. Remember
Python! The length of the
thatstring
the break
is statement
11 Enter can be used with the for loop as well. Swaroop Poetic
something: exit
Python
Programming is fun
Production:
True time :
s = input ( 'Enter something:'
) If s == 'leave' :
$ pythonrip
continue.py Enter
If len (s) < 3 :
something: a Too
print( 'Too
small small' ) Continue
Please enter
print( 'Input is of sufficient
something:
length'12 Too
) # Do other processing
small
here...
Enter something: abc
44
Control flow
In this program, we accept user input, but process the input string only if it is at least 3 characters long. So, we use the
Incorpo function to get the length and if the length is less than 3, we skip the rest of the statements in the block using the
rated l
Contin
statement. Otherwise, the rest of the statements are executed in the loop, performing any type of processing that we want
to do.
here.
Note that the continue statement also works with the for loop.
Summary
We have seen how to use the three control flow statements: if, while and for along with their interrupt and
Follow statements. These are some of the most used parts of Python and therefore it is essential to get comfortable
with them.
45
Features
Features
Functions are reusable programs. They allow you to give a name to a block of statements, allowing you to execute that block using
the specified name anywhere in your program and as many times as you like. This is known as calling the function. We have
already used many built-in functions like len and range.
The concept of a function is probably the most important building block of any non-trivial software (in any programming
language), so we will explore various aspects of functions in this chapter.
Functions are defined using the def keyword. After this keyword comes an identifier name for the function, followed by a pair of
parentheses that may enclose some variable names, and the colon that ends the line. Next follows the block of declarations that
are part of this function. An example will show that this is actually very simple:
Production:
def say hello ():
# block belonging to the print function
( 'Hello World' )
How$python
# does it work
End of function
function1.py hello
We world
define
say a function
hello() called
# call thesay_hello
functionusing
say the syntax as explained above. This function takes no parameters and therefore there
are hello()
no variables declared
# call in parentheses.
the function again Function parameters are simply entered into the function so that we can pass different
Notice that we can call the same function twice, which means we don't have to write the same code again.
Function parameters
A function can take parameters, which are values that you give to the function so that the function can do something using those
values. These parameters are like variables except that the values of these variables are defined when we call the function and they
already have values assigned when the function is executed.
The parameters are specified within the pair of parentheses in the function definition, separated by commas. When we call the
function, we provide the values in the same way. Note the terminology used: the names given in the function definition are called
parameters, while the values you provide in the function call are called arguments.
def print_max ( a,
b ): If a > b:
print (a, 'is maximum'
) elif a == b:
print (a, 'equals' , B)
else :
46
Features
x = 5
y = 7
Production:
How$python
does it function_param.py
work
4 is maximum
Here, we maximum
7 is define a function called print_max that uses two parameters called a and b. We find out the largest number using a
simple if..else statement and then print the largest number.
The first time we call the print_max function, we directly supply the numbers as arguments. In the second case, we call the
function with variables as arguments. print_max(x, y) causes the value of argument x to be assigned to parameter a and the
value of argument y to be assigned to parameter b. The print_max function works the same in both cases.
Local variables
When you declare variables within the definition of a function, they are in no way related to other variables with the same names
used outside the function, that is, the variable names are local to the function. This is called the scope of the variable. All variables
have the scope of the block in which they are declared starting from the name definition point.
Production:
x = 50
How$python
does
def it work
func ( X ):
function_local.py
print( 'x x is
The50
firstis'
time, we
x) print
x = the
2 value of name x with the first line in the function body, Python uses the value of the parameter declared in
The local x
the mainprint( 'Localthe
block, above x function
was changed to' ,
definition. X)
changed to 2 x is
func(x)
print( 'x is still' , X)
47
Features
Next, we assign the value 2 to x. The name x is local to our function. So when we change the value of x in the function, the x
defined in the main block is not affected.
With the last print statement, we display the value of x as defined in the main block, thus confirming that it is not actually
affected by the local assignment within the previously called function.
You can use the values of such variables defined outside the function (assuming there is no variable with the same name inside
the function). However, this is not recommended and should be avoided, since it is not clear to the reader of the program where
the definition of that variable is. Using the global declaration makes it very clear that the variable is defined in an outermost
block.
Production:
x = 50
How$python
doesfunc
def it work
():
function_global.py x is
The50
global declaration is used to declare that x is a global variable; Therefore, when we assign a value to x inside the function,
global
thatChanged
change isglobal x to 2
reflected when we use the value of x in the main block.
The print( 'xx is 2
value of
is' , x) x = 2
You can specify more than one global variable using the same global declaration, for example global x, y, z .
print( 'Global x changed to' , X)
Default
func() argument values
print( 'The value of x is' , X)
For some functions, you may want to make some parameters optional and use default values in case the user does not want to
provide values for them. This is done with the help of default argument values. You can specify default argument values for
parameters by adding to the parameter name in the function definition the assignment operator (=) followed by the default value.
Note that the value of the default argument must be a constant. More precisely, the value of the default argument should be
immutable; this is explained in detail in later chapters. For now, remember this.
48
Features
Production:
def say ( message, times =
1 ): print(message *
times)
How$ does it work
python
function_default.py
say hi' ) Hello
TheWorldWorldWorldWorldWorld
function called say is used to print a string as many times as specified. If we do not provide a value, then by default the
string is printed only once. We achieve this by specifying a default argument value of 1 to the parameter times.
On the first use of say, we supply only the string and it prints it once. In the second use of say, we provide both the string and an
argument 5 indicating that we want to say the string message 5 times.
CAUTION
Only parameters at the end of the parameter list can receive default argument values, that is, you cannot have a parameter
with a default argument value before a parameter without a default argument value in the parameter list. function.
This is because values are assigned to parameters by position. For example, def func (a, b = 5) is valid, but def func
(a = 5, b) is invalid.
Keyword arguments
If you have some functions with many parameters and you want to specify only some of them, then you can give values for such
parameters by naming them - this is called keyword arguments - we use name (keyword) instead of position (which we have
been using all the time) to specify the function arguments.
There are two advantages: one, using the function is easier since we don't need to worry about the order of the arguments. Two,
we can give values to only those parameters we want, as long as the other parameters have default argument values.
Production:
def func ( a, b = 5, c = 10 ):
print( 'a is' , a, 'yb is' , B, 'yc is' , C)
$ python
func 3 , 7 )
function_keyword.py
func ( 25 , c = a is 3
and
24 )bfunc
is 7(and
c =c is 10 a is
25 ,
50 and
a =b 100
is 5)and c is 24
49
Features
The function named func has one parameter without a default argument value, followed by two parameters with default
argument values.
In the first use of func(3, 7), parameter a gets the value 3, parameter b gets the value 7, and c gets the default value of 10.
In the second use function (25, c = 24), the variable a gets the value of 25 due to the position of the argument. Then the
parameter c gets the value of 24 because of the name i.e. keyword arguments. The variable b gets the default value of 5.
In the third use function (c = 50, a = 100), we use keyword arguments for all specified values. Note that we are specifying the
value for parameter c before a, even though a is defined before c in the function definition.
VarArgs Parameters
Sometimes you may want to define a function that can take any number of parameters, i.e. a variable number of arguments, this
can be achieved using stars (save as function_varargs.py):
Production:
def total ( a = 5, * numbers, ** phonebook
): print ( 'a' , a)
How$python
does it work
#iterate through all elements in tuple
function_varargs.py a 10
per single object in numbers:
When we declare 1an asterisked parameter as *param, all positional
single_item arguments from that point to the end are collected as a tuple
print( 'single object' , single object)
single_item 2
called 'param'.
single_item 3
#iterate through all dictionary elements
Inge 1560
Similarly,
bywhen we declare
first_part, a double-starred
second_part parameter as **param,
in phonebook.items(): all keyword arguments from that point to the end are
John 2231
collected as
Cat 1123
a dictionary called
print(first_part, 'param'.
second_part)
We total( 10 , tuples
will explore 1 , 2and
, 3dictionaries
, Jack = 1123 , John
in a later = 2231
chapter . , Inge = 1560 )
50
Features
Production:
max def ( x, y ):
If x > y:
return
How$python
does it work
X elif x ==
function_return.py
y: 3
The maximum function
return returns
'The the maximum
numbers of the parameters, in this case the numbers given to the function. Use a simple
are equal'
if...else else : to find the largest value and then return that value.
statement
return and
Note that a return statement without a value is equivalent to returning None. None is a special type in Python that represents nothing.
For example, it is used to indicate that a variable has no value if it has a value of None.
Every function implicitly contains a return None statement at the end unless you have written your own return statement.
You can see this running print(some_function()) where the function some_function does not use the return statement like:
def
TIP:some_function ():function
There is a built-in called max that already implements the 'find maximum' functionality, so use this built-in
approve
function whenever possible.
DocStrings
Python has a nifty feature called docstrings, usually referred to by its shorter name docstrings. DocStrings is an important tool
to use as it helps document the program better and makes it easier to understand. Surprisingly, we can even retrieve the
docstring of, say a function, when the program is running.
def print_max ( x, y ):
'''Print maximum of two numbers.
If x > y:
print (x, 'is maximum'
) else :
print (and, 'is maximum' )
51
Features
Production:
How$python
does it function_docstring.py
work
5 is maximum
A string in the
Prints first logical
maximum of twoline of a function is the docstring for that function. Please note that DocStrings also apply to
numbers.
modules and classes that we will learn about in the respective chapters.
Both values must be integers.
The convention followed for a document string is a multi-line string where the first line begins with a capital letter and ends with a
period. Then the second line is blank followed by a detailed explanation starting from the third line. You are strongly
recommended to follow this convention for all your docstrings for all your non-trivial functions.
We can access the docstring of the print_max function using the doc (notice the double underline) (name belonging to) attribute
of the function. Just remember that Python treats everything as an object and this includes functions. We will learn more about
objects in the chapter on classes .
If you've used help() in Python, you've already seen the use of docstrings! What he does is look for the Doc
attribute of that function and displays it in a neat way for you. You can try it in the function above, just include
help (print_max) in your program. Remember to press the q key to exit help .
Automated tools can retrieve your program documentation this way. Therefore, I strongly recommend that you use docstrings for
any non-trivial functions you write. The pydoc command that comes with your Python distribution works similarly to help() using
docstrings.
Summary
We have seen many aspects of the features, but keep in mind that we have not covered all aspects of them yet. However, we have
already covered most of what you will use regarding Python functions on a daily basis.
52
Modules
Modules
You've seen how you can reuse code in your program by defining functions once. What if you wanted to reuse a series of functions in
other programs you write? As you may have guessed, the answer is modules.
There are several methods for writing modules, but the easiest way is to create a file with a .py extension that contains
functions and variables.
Another approach is to write the modules in the native language in which the Python interpreter was written. For example, you can
write modules in the C programming language and when they are compiled, they can be used from your Python code when using
the standard Python interpreter.
Another program can import a module to make use of its functionality. This is how we can also use the Python standard library.
First, we'll look at how to use the standard library modules.
Production:
import sys
this module_using_sys.
print(
module.'\n\nThe PYTHONPATH
The sys module is' functions
contains , sys.path, '\n'
related ) Python interpreter and its environment, that is, the system.
to the
py us
They are
When Python executes the import sys statement, it looks for the sys module. In this case, it is one of the built-in modules and
argument
therefore
s Python knows where to find it.
If it was not a compiled module, that is, a module written in Python, then the Python interpreter will look for it in the
directories listed in itsissys.path
The PYTHONPATH variable. If the module is found, the instructions in the body of that module are executed and the
['/tmp/py',
# many entries here, not shown here
module is available for use. Note that initialization is done only the first time we import a module.
'/Library/Python/2.7/site-packages',
The variable argv in the sys module is accessed using dotted notation, i.e. sys.argv. It clearly indicates that this name is part of
the sys module. Another advantage of this approach is that the name does not clash with any argv variables used in your
program.
53
Modules
The sys.argv variable is a list of strings (lists are explained in detail in a later chapter ). Specifically, the sys.argv contains the list
of command line arguments, that is, the arguments passed to your program using the command line.
If you are using an IDE to write and run these programs, find a way to specify command line arguments for the program in the
menus.
Here, when we execute python module_using_sys.py are arguments , we execute the module module_using_sys.py with the
python command and the other things that follow are arguments passed to the program. Python stores command line
arguments in the sys.argv variable for us to use.
Remember, the name of the script being run is always the first item in the sys.argv list. So in this case we will have
'module_using_sys.py' as sys.argv [0] , 'we' as sys.argv [1] , 'are' as sys.argv [2] and 'args' as
sys.argv [3] . Notice that Python starts counting from 0 and not from 1.
Sys.path contains the list of directory names from which modules are imported. Notice that the first string in sys.path is empty;
This empty string indicates that the current directory is also part of sys.path, which is the same as the PYTHONPATH
environment variable. This means that you can directly import modules located in the current directory. Otherwise you will have
to place your module in one of the directories listed in sys.path.
Note that the current directory is the directory from which the program is started. Run imports; print (os.getcwd()) to find the
current directory of your program.
NOTE: These .pyc files are usually created in the same directory as the corresponding .py files. If Python does not have
permission to write to files in that directory, the .pyc files will not be created.
WARNING: In general, avoid using the from..import statement, use the import statement instead. This is because your
program will avoid name conflicts and be more readable.
Example:
Each module has a name and statements in a module can find the name of its module. This is useful for the particular purpose of
determining whether the module is running independently or being imported. As mentioned above, when a module is imported
for the first time, the code it contains is executed. We can use this to make the module behave in different ways.
54
Modules
depending on whether it is being used alone or imported from another module. This can be achieved using the module
name attribute.
Production:
How$python
does it module_using_name.py
work
This program runs alone
Each Python module has its name defined. If it is 'main', that implies that the user is running the module independently and we
can $python
take appropriate actions.
>>> import name_using_module
I import them from another module
>>>
Make your own modules
Creating your own modules is easy, you've been doing it all along! This is because every Python program is also a module. You
just need to make sure it has a .py extension. The following example should make it clear.
version = '0.1'
The above was a sample module. As you can see, there is nothing special compared to our usual Python program. Next, we'll
look at how to use this module in our other Python programs.
Remember that the module must be located in the same directory as the program from which we imported it or in one of the
directories listed in sys.path.
import mymodule
mymodule.say_hi()
print( 'Version' , mymodule. version )
Production:
How$python
does it mymodule_demo.py
work
Hello, this is mymodule.
Version 0.1
55
Modules
Note that we use the same dotted notation to access module members. Python makes good reuse of the same notation to give it
the distinct 'Pythonic' feel so we don't have to keep learning new ways of doing things.
Say hello()
print( 'Version' , version )
Note that if there was already a version name declared in the module mymodule imports, there would be a conflict. This is also
likely because it is common practice for each module to declare its version number with this name. Therefore, it is always
recommended to prefer the import statement even though it may make your program a little longer.
Thisfrom
will mymodule
import all import
public names
* as say_hi but will not import the version because it starts with double underscores.
Python Zen
One of the guiding principles of Python is that "Explicit is better than implicit." Run import this in Python for more information.
This function can accept arguments. If the argument is the name of a module, the function returns the list of names of that
specified module. If there are no arguments, the function returns the list of names of the current module.
Example:
$python
>>> import sys
>>> dir ()
[ 'built-in' , 'doc' , 'name' , 'package' , 'sys' , 'a' ]
56
Modules
>>> dir ()
[ 'built-in' , 'doc' , 'name' , 'package' , 'sys' ]
First, we look at the use of dir in the imported sys module. We can see the huge list of attributes it contains.
Next, we use the dir function without passing any parameters to it. By default, it returns the list of attributes of the current module.
Note that the list of imported modules is also part of this list.
To observe dir in action, we define a new variable a and assign it a value and then check dir and observe that there is an
additional value in the list of the same name. We remove the variable/attribute from the current module using the del statement
and the change is reflected back in the output of the dir function.
A note about del: This statement is used to delete a variable/name and after the statement, in this case del a, has been executed, you
can no longer access the variable a; It's like it never existed before.
Note that the dir() function works on any object. For example, run dir(str) for attributes of class str(string). There is also a vars()
function that can potentially give you the attributes and their values, but it won't work in all cases.
packages
By now, you must have started to look at the organizational hierarchy of your programs. Variables usually go inside functions.
Functions and global variables usually go inside modules. What if I wanted to organize modules? That's where packets come into
the picture.
Packages are just module folders with a special init .py file that tells Python that this folder is special because it contains
Python modules.
Suppose you want to create a package called 'world' with subpackages 'asia', 'africa', etc. and these subpackages in turn contain
modules like 'india', 'madagascar', etc.
Packages arefolder
- <some just a convenience
present in for organizing
sys.path> / modules hierarchically. You'll see many cases of this in the standard library .
- world/
- init .py
Summary- - Asia/
init .py
- India/
- init .pyof programs, modules are reusable programs. Packages are another hierarchy for organizing
Just as functions are reusable parts
- foo.py
modules. The- standard
Africa/ library that comes with Python is an example of such a set of packages and modules.
- init .py
We have seen how
- to use these modules and create our own modules.
Madagascar/
- init .py
- bar.py
57
Modules
Next, we will learn about some interesting concepts called data structures.
58
Data structures
Data structures
Data structures are basically that: they are structures that can hold some data together. In other words, they are used to store a
collection of related data.
There are four data structures built into Python: list, tuple, dictionary, and set. We will see how to use each of them and how they
make our lives easier.
List
A list is a data structure that contains an ordered collection of elements, that is, it can store a sequence of elements in a list. This is
easy to imagine if you can think of a shopping list where you have a list of items to buy, except you probably have each item on a
separate line in your shopping list, whereas in Python you put commas between them.
The list of elements must be enclosed in square brackets so that Python understands that you are specifying a list. Once you've
created a list, you can add, delete, or search for items in the list. Since we can add and delete elements, we say that a list is a
mutable data type, that is, this type can be modified.
A list is an example of using objects and classes. When we use a variable i and assign it a value, say an integer 5, you can think
of it as creating an object (i.e. instance) i of class (i.e. type) int. In fact, you can read help (int) to understand this better.
A class can also have methods, that is, functions defined for use with respect to that class only. You can use these pieces of
functionality only when you have an object of that class. For example, Python provides an add method for the list class that
allows you to add an element to the end of the list. For example, mylist.append('an item') will add that string to the list
my list . Note the use of dot notation to access object methods.
A class can also have fields that are nothing more than variables defined for use with respect to that class only. You can use these
variables/names only when you have an object of that class. Fields are also accessed using dotted notation, e.g.
mylist.field .
buy'. )
59
Data structures
Production:
How$python
does it ds_using_list.py
work
I have 4 items to
Thepurchase.
shoplist variable is a shopping list for someone going to the market. In shoplist, we only store strings of the names of items
These items are: apple mango carrot
to buy, but you can add any type of object to a list, including numbers and even other lists.
banana I also have to buy rice.
My shopping list now is ['apple', 'mango', 'carrot', 'banana',
We have also used the for..in loop to loop through the list elements. By now, you must have realized that a list is also a sequence. The
'rice']. I'll sort my list now
specialty of sequences
The ordered will be
shopping discussed
list in a later'banana',
is ['apple', section . 'carrot', 'mango',
'rice'] The first item I will buy is apple
NoteI the use of
bought thetheapple
end parameter in the print function call to indicate that we want to end the output with a space instead of the
usual line break.
Next, we add an element to the list using the add method of the list object, as already discussed before. We then verify that the
item has been added to the list by printing the contents of the list by simply passing the list to the print function which prints it in
order.
Then, we sort the list using the list sort method. It is important to understand that this method affects the list itself and does not
return a modified list; this is different from the way chains work. This is what we mean when we say that lists are mutable and
strings are immutable.
Next, when we finish purchasing an item from the market, we want to remove it from the list. We achieve this using the del
statement. Here, we mention which item in the list we want to remove and the statement removes it from the list for us. We
specify that we want to remove the first element from the list and therefore use del shoplist[0] (remember that Python starts
counting from 0).
If you want to know all the methods defined by the list object, please refer to the help (list) for details.
Tuple
Tuples are used to hold multiple objects together. Think of them as similar to lists, but without the extensive functionality that the
list class gives you. An important characteristic of tuples is that they are immutable like strings, that is, tuples cannot be modified.
Tuples are defined by specifying comma-separated elements within an optional pair of parentheses.
Tuples are generally used in cases where a statement or user-defined function can safely assume that the collection of values (that
is, the tuple of values used) will not change.
60
Data structures
new_zoo = 'monkey' , 'camel' , zoo # parentheses are not required, but are a
good idea print( 'The number of cages in the new zoo is' , len (new_zoo))
print( 'All animals in the new zoo are' , new_zoo) print
( 'Animals brought from the old zoo are' , new_zoo [ 2
]) print( 'The last animal brought from the old zoo is'
, new_zoo [ 2 ] [ 2 ]) print( 'The number of animals in
the new zoo is' ,
Production:
We can access the elements of the tuple by specifying the position of the element within a pair of square brackets, as we did with
lists. This is called an indexing operator. We access the third element in new_zoo by specifying new_zoo[2] and we access the
third element within the third element in the new_zoo tuple by specifying new_zoo[2][2]. This is quite simple once you have
understood the language.
An empty tuple is constructed with a pair of empty parentheses like myempty = (). However, a tuple with a single element is
not so simple. You must specify it using a comma after the first (and only) element so that Python can differentiate between
a tuple and a pair of parentheses surrounding the object in an expression, that is, you must specify singleton = (2
,) if you mean you want a tuple that contains element 2.
A list within a list does not lose its identity, that is, lists do not become flattened as in Perl. The same applies to a tuple
within a tuple, or a tuple within a list, or a list within a tuple, etc. As far as Python is concerned, they are just objects
stored using another object, that's all.
Dictionary
A dictionary is like an address book where you can find a person's address or contact details by knowing only their name.
That is, we associate keys (name) with values (details). Keep in mind that the key must be unique, just as you can't find the correct
information if you have two people with the exact same name.
Note that you can only use immutable objects (such as strings) for the keys of a dictionary, but you can use immutable or
mutable objects for the dictionary values. This basically translates to saying that you should only use simple objects for keys.
61
Data structures
Key-value pairs are specified in a dictionary using the notation d = {key1:value1, key2:value2}. Notice that the key-value pairs are
separated by colons and the pairs are separated by commas and all of this is enclosed in a pair of braces.
Remember that key-value pairs in a dictionary are not ordered in any way. If you want a particular order, you will need to order
them yourself before using it.
The dictionaries you will use are instances/objects of the dict class.
Production:
# 'ab' is short for 'a'ddress'b'ook
ab = {
How$python
does it ds_using_dict.py
work : '[email protected]'
'Swaroop'
Swaroop's address
, 'Larry' is [email protected]
: '[email protected]' ,
We create the ab dictionary
'Matsumoto' using the notation already discussed. We then access the key-value pairs by specifying the key using the
: '[email protected]'
There are 3 contacts in the address book
indexing,operator as explained
'Spammer' in the context of lists and tuples. Note the simple syntax.
: '[email protected]'
}
Contact Swaroop at [email protected]
We can remove key-value pairs using our old friend: the del statement. We simply specify the dictionary and indexing operator so
Contact Matsumoto address
print( "Swaroop's at [email protected]
is" , ab
thatContact
the key isLarry
removed and pass it to the del statement. It is not necessary to know the value corresponding to the key for this
at [email protected]
operation.
[ 'Swaroop' ]) # Deleting a key-value pair
Guido's address
from ab [ is [email protected]
'Spammer' ]
Next, we access each key-value pair in the dictionary using the dictionary's elements method which returns a list of tuples where
eachprint( '\nThere
tuple contains are of
a pair {}elements:
contactsthe
inkey
thefollowed
addressby
book \n' . We
the value. format ( len
retrieve this pair and assign it to the variables name
and (ab)))
corresponding address for each pair using the for..in loop and then print these values to the for block.
by Name address in ab.items ():
print( "Contact {} at {}" . format (Name address))
If 'Guido' in ab:
print( "\nGuido's address is" , ab [ 'Guido' ])
62
Data structures
We can add new key-value pairs simply by using the indexing operator to access a key and assign that value, as we have done for
Guido in the previous case.
For the list of methods of the dict class, see help (dict).
If you've used keyword arguments in your functions, you've already used dictionaries! Just think about it: you specify the
key-value pair in the parameter list of the function definition and when you access the variables inside your function, it's
just a key access from a dictionary (which is called a symbol table in the design compiler terminology).
Sequence
Lists, tuples, and strings are examples of sequences, but what are sequences and what is special about them?
The main features are membership tests (i.e. the in and not in expressions) and indexing operations, which allow us to search for a
particular element in the sequence directly.
The three types of sequences mentioned above, lists, tuples and strings, also have a cut operation that allows us to recover a portion of
the sequence, that is, a part of the sequence.
Production:
shoplist = [ 'apple' , 'mango' , 'carrot' ,
'banana' ] name = 'swaroop'
$
# python
Indexing or 'subscription' operation
ds_seq.py
# Item 0 is' , thief [ 0 ])
print( 'Item
is apple
print( Item11is' , thief [ 1 ])
'Item
is mango
print( Item22is' , thief [ 2 ] )
'Item
is carrot
print( Item 33 is' , thief [ 3 ])
'Element
is banana
print( Item --1 is' , thief [- 1 ])
'Element
1 is banana
print( Item-2 is' , thief [- 2 ])
'Element
-2 is carrot
print( ' Character 0 is' , name[ 0 ])
Character 0 is s
Element
# Cut to1ato 3 is
list # ['mango',
'carrot']
print( Element
'Element 2 at
1 to the ,
3 is' end is [ 1 : 3
thief
['carrot',
]) 'banana']
print( 'Element Element
2 at 1 to
the end - , thief
is'
[ 2 :]) print( 'Element 1 to -1 is' , thief
[ 1 :- 1 ]) print( 'The article from
beginning to end is' , thief [:])
63
Data structures
First, we look at how to use indexes to get individual elements of a sequence. This is also known as a subscription operation.
Whenever you specify a number for a sequence in square brackets as shown above, Python will look for the element
corresponding to that position in the sequence. Remember that Python starts counting numbers from 0. Therefore, thief[0]
searches for the first element and thief[3] searches for the fourth element in the thief sequence.
The index can also be a negative number, in which case the position is calculated from the end of the sequence. Therefore,
thief[-1] refers to the last element in the sequence and thief[-2] gets the second to last element in the sequence.
The cut operation is used by specifying the name of the sequence followed by an optional pair of numbers separated by colons in
square brackets. Note that this is very similar to the indexing operation you have been using so far. Remember that the numbers
are optional, but the colons are not.
The first number (before the colon) in the cutting operation refers to the position from where the cutting starts and the second
number (after the colon) indicates where the cutting will stop. If the first number is not specified, Python will start at the
beginning of the sequence. If the second number is omitted, Python will stop at the end of the sequence. Note that the returned
segment starts at the start position and will end just before the end position, that is, the start position is included but the end
position is excluded from the sequence segment.
Therefore, shoplist[1:3] returns a segment of the sequence that starts at position 1, includes position 2 but stops at position 3,
and thus a two-item segment is returned. Similarly, shoplist[:] returns a copy of the entire sequence.
You can also do slicing with negative positions. Negative numbers are used for positions from the end of the sequence. For
example, shoplist[:-1] will return a portion of the sequence that excludes the last element of the sequence but contains everything
else.
You can also provide a third argument for the slice, which is the step for the cut (by default, the step size is 1):
Note>>>
thatshoplist
when the=step is 2, we ,get'mango'
[ 'apple' the elements with position
, 'carrot' 0, 2, ...] When the step size is 3, we get the elements with position
, 'banana'
0, 3,>>>
etc.shoplist [:: 1 ]
[ 'apple' , 'mango' , 'carrot' , 'banana' ]
Place
'banana' ]
Sets are unordered collections of simple objects. They are used when the existence of an object in a collection is more important
than the order or how many times it occurs.
With sets, you can test for membership, whether it is a subset of another set, find the intersection between two sets, etc.
64
Data structures
If you remember the basic mathematics of set theory from school, then this example is self-explanatory. But if not, you can Google
"set theory" and "Venn diagram" to better understand our use of sets in Python.
References
When you create an object and assign it to a variable, the variable only refers to the object and does not represent the object itself.
That is, the variable name points to the part of your computer's memory where the object is stored. This is called binding the name
to the object.
Generally, you shouldn't worry about this, but there is a subtle effect due to references that you should know about: Example (save as
ds_reference.py):
Production:
$ python ds_reference.py
Simple assignment
the thief is ['mango', 'carrot', 'banana']
my list is ['mango', 'carrot', 'banana']
Copy making a complete cut
the thief is ['mango', 'carrot', 'banana']
my list is ['carrot', 'banana']
65
Data structures
Remember that if you want to make a copy of a list or those kinds of sequences or complex objects (not simple objects like
integers), then you must use the cut operation to make a copy. If you simply assign the variable name to another name, they will
both "refer" to the same object and this could be a problem if you are not careful.
Remember that an assignment statement for lists does not create a copy. You have to use the cut operation to make a copy
of the sequence.
The strings you use in programs are all objects of the str class. The following example shows some useful methods of this class.
For a complete list of such methods, see help (str).
Production:
# This is a string object
name = 'Swaroop'
How$python
Ifdoes it ds_str_methods.py
work
name.startswith( 'Swa' ):
Yes,print(
the string
'Yes,starts with starts with "Swa"' )
the string
Here, we see
"Swa" many
Yes, it of the string
contains methods in action. The startswith
the method is used to find out if the string starts with the given
string
If The "a"name:
'a' in
in Yes, it contains the
string. operator is used to check if a given string is part of the string.
string "war"
print( Brazil
'Yes, _ * _ the string "a"' )
contains
TheRussia _ * _ India _ * _ China
search method is used to locate the position of the given substring within the string; find returns -1 if it fails to find the
if name.find( 'war' )! = -1:
substring. The str class also has an ordered method to join the elements of a sequence with the string acting as a delimiter
print( 'Yes, contains the string "war"' )
between each element of the sequence and returns a larger string generated from this.
delimiter = '_*_'
mylist = [ 'Brazil' , 'Russia' , 'India' ,
Summary
'Porcelain' ] print (delimiter.join (mylist))
66
Data structures
We have explored in detail the various built-in data structures of Python. These data structures will be essential for writing
programs of reasonable size.
Now that we have many of the basics of Python in place, we'll next look at how to design and write a real-world Python program.
67
Problem
resolution
# Problem resolution
We have explored various parts of the Python language and now we will see how all these parts fit together, designing and
writing a program that does something useful. The idea is to learn how to write a Python script on your own.
The problem
The problem we want to solve is:
Although this is a simple problem, there is not enough information for us to begin the solution. A little more analysis is required. For
example, how do we specify which files to back up? How are they stored? Where are they stored?
After analyzing the problem properly, we design our program. We make a list of things about how our program should work. In
this case, I have created the following list of how I want it to work. If you do the design, you may not come up with the same type
of analysis, since everyone has their own way of doing things, so that's perfectly fine.
Windows users can install the zip command from the GnuWin32 project page and add C:\Program Files\GnuWin32\
bin to your system's PATH environment variable, similar to what we did to recognize the python command
itself .
The solution
Since our program design is now reasonably stable, we can write code that is an implementation of our solution. Save as
backup_ver1.py :
import you
import time
68
Problem
resolution
# 4. The name of the zip file is the current date and time
target = target_dir + os.sep + \
time.strftime '%Y%m%d%H%M%S' ) + '.PostalCode'
# 5. We use the zip command to put the files into a zip archive
zip_command = 'zip -r {0} {1}' . format (target,
'' .join (source))
Production:
Now,
Thewe$python
are in the testing phase where we test that our program works correctly. If it does not behave as expected, then we have to
backup_ver1.py Zip
debug our program, that is, eliminate errors (errors) from the program.
command is:
zip -r /Users/swa/backup/20140328084844.zip /Users/swa/notes
If the above program doesn't work for you, copy the line printed after the Zip command is on the output line, paste it into shell (on
Running:
GNU/Linux andUsers/swa/notes/
adding: Mac OS X) / cmd(stored
(on Windows),
0%) see what it is the error is and try to fix it. Also check the zip command manual
to findadding:
out what Users/swa/notes/blah1.txt
could be wrong. If this command is successful, then the problem could be in the Python program itself, so check
(stored
0%) adding: Users/swa/notes/blah2.txt
if it exactly matches the program written above.
(stored 0%) adding:
Users/swa/notes/blah3.txt (stored 0%)
How does it work
You will notice how we have converted our design into code step by step.
We make use of the time and operating system modules by importing them first. Next, we specify the files and directories to be
backed up in the source list. The target directory is where we store all the backup files and this is specified in the target_dir
variable. The name of the zip file that we are going to create is the current date and time that we generated using the
time.strftime() function. It will also have the .ZIP extension and will be stored in the target_dir directory.
Note the use of the os.sep variable: this gives you the directory separator according to your operating system, i.e. it will be '/' on
GNU/Linux, Unix, macOS and it will be '\\' on Windows. Using os.sep instead of these characters will directly make our
program portable and work on all these systems.
The time.strftime() function takes a specification like the one we used in the previous program. The %Y specification will be
replaced by the year with the century. The %m specification will be replaced by the month as a decimal number between
01 and 12 and so on. The complete list of such specifications can be found in the Python Reference Manual .
We create the name of the destination zip file using the addition operator which concatenates the strings i.e. joins the two strings
and returns a new one. Next, we create a zip_command string that contains the command we are going to execute. You can
check if this command works by running it in the shell (GNU/Linux terminal or DOS prompt).
69
Problem
resolution
The zip command we are using has a few options available, and one of these options is -r. The -r option specifies that the zip
command should work recursively for directories, that is, it should include all subdirectories and files. The options are followed
by the name of the zip file to create, followed by the list of files and directories to backup. We convert the list of sources to a
string using the string join method that we have already seen how to use.
Then, finally we execute the command using the os.system function which executes the command as if it were executed from the
system, i.e. in the shell; returns 0 if the command was successful, otherwise it returns an error number.
Depending on the output of the command, we print the appropriate message that the backup has failed or succeeded.
Instead of double backslash escape sequences, you can also use raw strings. For example, use 'C: \\ Documents' or
r'C:\Documents' . However, don't use 'C:\Documents' as you end up using an unknown \D escape sequence.
Now that we have a working backup script, we can use it whenever we want to backup files. This is called
operation phase or the software implementation phase.
The program above works correctly, but (usually) the first few programs don't work exactly as you expected. For example, there
may be problems if you have not designed the program correctly or if you have made a mistake while writing the code, etc.
Appropriately, you will have to go back to the design phase or you will have to debug your program.
Second version
The first version of our script works. However, we can make some adjustments to make it work better on a daily basis. This is
called the software maintenance phase.
One of the improvements I felt was helpful is a better file naming mechanism: using the time as the file name within a directory
with the current date as a directory within the parent backup directory. The first advantage is that your backups are stored
hierarchically and therefore it is much easier to manage. The second advantage is that the file names are much shorter. The third
advantage is that the separate directories will help you check if you have made a backup for each day, since the directory will be
created only if you have made a backup for that day.
Save as backup_ver2.py :
import you
import time
70
Problem
resolution
# 5. We use the zip command to put the files into a zip archive
zip_command = 'zip -r {0} {1}' . format (target,
'' .join (source))
Production:
How$python
does it backup_ver2.py
work
The directory /Users/swa/backup/20140329 successfully
Most of the program
created The Zip remains
commandthe same. The changes are that we check if there is a directory with the current day as its name
is:
zip -r /Users/swa/backup/20140329/073201.zip /Users/swa/notes
inside the main backup directory using the os.path.exists function. If it does not exist, we create it using the os.mkdir function.
Running:
adding: Users/swa/notes/ (stored 0%)
adding: Users/swa/notes/blah1.txt (stored
Third
0%) version
adding: Users/swa/notes/blah2.txt
(stored 0%) adding:
Users/swa/notes/blah3.txt (stored 0%)
The second version works fine when I make many backups, but when there are many backups, I find it difficult to differentiate
what the backups are for! For example, I might have made some breaking changes to a program or presentation, then I want to
associate what those changes are with the name of the zip file. This can be easily achieved by appending a user-provided
comment to the zip file name.
WARNING: The following program does not work, so don't be alarmed, follow it because there is a lesson here.
Save as backup_ver3.py :
import you
import time
71
Problem
resolution
# specified in a
list. # Example on
Windows:
# source = ['"C: \\ My Documents"', 'C: \\
Code'] # Example on Mac OS X and Linux:
source = [ '/Users/swa/notes' ]
# Note that we had to use double quotes inside the
string # for names with spaces.
# 5. We use the zip command to put the files into a zip archive
zip_command = "zip -r {0} {1}" . format (target,
'' .join (source))
Production:
How$python
this (not) works
backup_ver3.py
File "backup_ver3.py", line 39
target = today + os.sep + now + '_' +
^
Syntax error: invalid syntax
72
Problem
resolution
This program does not work! Python says that there is a syntax error that means the script does not satisfy the structure that
Python expects to see. When we look at the error given by Python, it also tells us the place where it detected the error. Then we
start debugging our program from that line.
On careful observation, we see that the single logical line has been split into two physical lines, but we have not specified that
these two physical lines belong together. Basically, Python has encountered the addition operator (+) without any operands on
that logical line and therefore doesn't know how to continue. Remember that we can specify that the logical line continues on the
next physical line by using a backslash at the end of the physical line. So, we make this correction to our program. This correction
of the program when we find errors is called error correction.
Fourth version
Save as backup_ver4.py :
import you
import time
# 5. We use the zip command to put the files into a zip archive
zip_command = 'zip -r {0} {1}' . format (target,
'' .join (source))
73
Problem
resolution
Production:
How$python
does it backup_ver4.py
work
Enter a comment -> new examples
Thisadded
program
Thenow
Zip works!
commandLet's
is:go over the actual improvements we made in version 3. We take the user's comments using the
zip -r /Users/swa/backup/20140329/074122_added_new_examples.zip /Users/swa/notes
input function and then check if the user actually entered something by finding out the length of the input using the len
Running:
function. If the Users/swa/notes/
adding: user just hit enter without
(storedentering
0%) anything (maybe it was just a routine backup or no special changes were
made),adding:
then we proceed as we have before.
Users/swa/notes/blah1.txt (stored
0%) adding: Users/swa/notes/blah2.txt
However, if a comment was provided,
(stored 0%) it is appended to the zip file name just before the .zip extension. Note that we are replacing
adding:
Users/swa/notes/blah3.txt (stored 0%)
spaces in the comment with underscores; This is because managing file names without spaces is much easier.
More refinements
The fourth version is a script that works satisfactorily for most users, but there is always room for improvement. For example,
you can include a level of verbosity for the zip command by specifying a -v option to make your program more talkative or
-q option to make it silent.
Another possible improvement would be to allow additional files and directories to be passed to the script on the command line.
We can get these names from the sys.argv list and can add them to our source list using the extension method provided by the
class list.
The most important refinement would be to not use the os.system way of creating files and instead use the built-in zip file or
tarfile modules to create these files. They are part of the standard library and are already available for use without external
dependencies on the zip program that will be available on your computer.
However, I've been using the os.system way of creating a backup in the examples above purely for pedagogical purposes, so the
example is simple enough for everyone to understand, but real enough to be useful .
Can you try writing the fifth version that uses the module zip file instead of the os.system call?
1. What (analysis)
2. How (Design)
74
Problem
resolution
3. Do it (implementation)
4. Test (test and debug)
5. Use (operation or implementation)
6. Maintain (refinement)
A recommended way to write programs is the procedure we followed when creating the backup script: do the analysis and
design. Start deploying with a simple version. Test it and debug it. Use it to make sure it works as expected. Now, add the
features you want and continue repeating the Do It-Test-Use cycle as many times as necessary.
Remember:
Summary
We have seen how to create our own Python programs/scripts and the various stages involved in writing such programs. You may
find it helpful to create your own program as we did in this chapter to get comfortable with Python and problem solving.
75
Object-oriented programming
Object-oriented programming
In all the programs we have written so far, we have designed our program around functions, that is, blocks of statements that
manipulate data. This is called the procedure-oriented form of programming. There is another way to organize your program
which is to combine data and functionality and wrap them inside something called an object. This is called an object-oriented
programming paradigm. Most of the time you can use procedural programming, but when you write large programs or have a
problem that is better suited to this method, you can use object-oriented programming techniques.
Classes and objects are the two main aspects of object-oriented programming. A class creates a new type where the objects are
instances of the class. An analogy is that you can have variables of type int, which translates to saying that variables that store
integers are variables that are instances (objects) of the int class.
Note that even integers are treated as objects (of class int). This is unlike C++ and Java (before version 1.5) where integers
are primitive native types.
C# and Java 1.5 programmers will find this similar to the concept of boxing and unboxing.
Objects can store data using ordinary variables that belong to the object. Variables that belong to an object or class are called
fields. Objects can also have functionality by using functions that belong to a class. These functions are called methods of the
class. This terminology is important because it helps us differentiate between independent functions and variables from those that
belong to a class or object. Together, the fields and methods can be called attributes of that class.
Fields are of two types: they can belong to each instance/object of the class or they can belong to the class itself. They are called
instance variables and class variables respectively.
A class is created using the class keyword. The fields and methods of the class are listed in an indented block.
the self
Class methods have only one specific difference from ordinary functions: they must have an additional name that must be added
to the beginning of the parameter list, but you do not give a value for this parameter when you call the method, Python will
provide that. This particular variable refers to the object itself and is, by convention, given the name self.
Although you can give this parameter any name, it is strongly recommended that you use the name self; any other name is definitely
frowned upon. Using a standard name has many advantages: any reader of your program will recognize it immediately, and even
specialized IDEs (integrated development environments) can help you if you use self.
The self in Python is equivalent to the this pointer in C++ and the this reference in Java and C#.
You must be wondering how Python gives the value to self and why you don't need to give it a value. An example will clarify it.
Let's say you have a class called Myclass and an instance of this class called myobject . When you call a method on this object
like myobject.method(arg1, arg2) , Python automatically converts it to MyClass.method(myobject, arg1, arg2) - this is all the
special self is about.
This also means that if you have a method that takes no arguments, then it still has to have an argument: the self.
Classes
76
Object-oriented programming
The simplest possible class is shown in the following example (save as oop_simplestclass.py ).
Production:
Person class :
approve # An empty block
$python oop_simplestclass.py
p = Person()
<main instance of .Person at 0x10171f518>
print(p)
We create a new class using the class declaration and the class name. This is followed by a block of indented statements that
form the body of the class. In this case, we have an empty block that is indicated by the pass statement.
Next, we create an object/instance of this class using the class name followed by a pair of parentheses. (We'll learn more about
instantiation in the next section.) For our verification, we confirm the type of variable by simply printing it. It tells us that we
have an instance of the Person class in the main module.
Note that the address of the computer memory where your object is stored is also printed. The address will have a different value
on your computer, since Python can store the object wherever it finds space.
Methods
We have already discussed that classes/objects can have methods like functions, except we have an additional variable of our
own. Now we will see an example (save as oop_method.py).
Production:
Person class :
def Say Hello ( self ):
method now.
77
Object-oriented programming
The method
in thatis executed as soon as an object of a class is instantiated (i.e. created). The method is useful for making some
initialization (i.e. passing initial values to your object) that you want to do with your object. Notice the double underlines at both the
beginning and end of the name.
Production:
Person class :
def in that ( self,
name ): self.name
How$ does it =work
python oop_init.py
name
Hello, my name is
Here, wedef
define
Swaroop Say the init method
Hello ( self by
): taking a parameter name (along with the usual self). Here, we simply create a new field also
called name. print( 'Hello,
Note that my two
these are name is' , variables,
different self.name)although they are both called 'name'. No problem because the dotted
notation self.name means that there is something called "name" that is part of the object called "self" and the other name is a local
p = Person( 'Swaroop' )
variable. Since we explicitly state which name we are referring to, there is no confusion.
p.say_hi()
# The 2 lines above can also be written as
When creating('Swaroop').
# Person a new instanceSay_hi()
p, of the Person class, we do so using the class name, followed by the arguments in parentheses:
p = Person('Swaroop').
We don't explicitly call the init method. This is the special meaning of this method.
Now, we can use the self.name field in our methods, which is demonstrated in the say_hi method.
There are two types of fields: class variables and object variables, which are classified according to whether the class or the
object owns the variables respectively.
Class variables are shared: all instances of that class can access them. There is only one copy of the class variable and when
any object makes a change to a class variable, all other instances will see that change.
Object variables are property of each individual object/instance of the class. In this case, each object has its own copy of the field
that is, they are not shared and are not related in any way to the field of the same name in a different instance. An example will
make this easy to understand (save as oop_objvar.py):
Robot class :
"" "Represents a robot, with a name." ""
78
Object-oriented programming
Robot.population - = 1
If Robot.population == 0 :
print( "{} was last". . format (self.name))
else :
print( "There are still {: d} robots running". . format
(Robot.population))
@classmethod
def How many ( cls ):
"" "Print the current population." ""
print( "We have {: d} robots". . format (classified population))
print( "The robots have finished their work. So let's destroy them." )
droid1.die()
droid2.die()
Production:
$ python oop_objvar.py
(Initializing R2-D2)
Greetings, my teachers call me R2-
D2. We have 1 robots.
(Initializing C-3PO)
Greetings, my teachers call me C-
3PO. We have 2 robots.
79
Object-oriented programming
We have 0 robots.
This is a long example, but it helps demonstrate the nature of class and object variables. Here, itpopulati
belongs to the Robot
class and therefore is a class variable. The name variable belongs to the object (assigned using self) and is therefore an object
variable.
Therefore, we refer to the population class variable as Robot.population and not as self.population. We refer to the variable
name of the object using the notation self.name in the methods of that object. Remember this simple difference between class
and object variables. Also note that an object variable with the same name as a class variable will hide the class variable.
Instead of Robot.population , we could have also used self. class .population because each object refers to its class through self.
class attribute.
How_many is actually a method that belongs to the class and not the object. This means that we can define it as a
class method or a static method depending on whether we need to know which class we are part of. Since we are referring to a class
variable, let's use class method .
You can imagine that decorators are a shortcut to calling a wrapper function (i.e. a function that "wraps" another function so that it
can do something before or after the inner function), so applying the @classmethod decorator is the same as calling:
Note that the init method is used to initialize the Robot instance with a name. In this method, we increase the
how_many = class method (How many)
population count one at a time since we have one more robot that is being added. Also note that the values of
self.name are specific to each object, indicating the nature of the object's variables.
Remember to reference variables and methods of the same object using self alone . This is called an attribute reference.
In this program, we also see the use of docstrings for classes and methods. We can access the docstring of the class at runtime
using Robot. Doc and the docstring method like Robot.say_hi. Doc
All class members are public. One exception: If you use data members with names that use the double underscore prefix, such as
privatevar , Python uses name mangling to effectively make it a private variable.
Therefore, the convention followed is that any variable used only within the class or object must start with an underscore and all
other names are public and can be used by other classes/objects. Remember that this is just a convention and is not enforced by
Python (except for the double underscore prefix).
All class members (including data members) are public and all methods are virtual in Python.
Inheritance
One of the main benefits of object-oriented programming is code reuse and one of the ways this is achieved is through
inheritance mechanism. Inheritance can best be imagined by implementing a type and subtype relationship between classes.
Suppose you want to write a program that should keep track of teachers and students at a university. They have some common
characteristics such as name, age and address. They also have specific characteristics such as salary, courses and licenses for
teachers and grades and fees for students.
80
Object-oriented programming
You can create two independent classes for each type and process them, but adding a new common feature would mean adding
both independent classes. This quickly becomes difficult to handle.
A better way would be to create a common class called SchoolMember and then make the teacher and student classes inherit
from this class i.e. they will become subtypes of this type (class) and then we can add specific features to these subtypes. .
There are many advantages to this approach. If we add/change any functionality in SchoolMember, this is automatically reflected
in the subtypes as well. For example, you can add a new ID card field for teachers and students by simply adding it to the
SchoolMember class. However, changes to subtypes do not affect other subtypes. Another advantage is that you can refer to a
teacher or student object as a SchoolMember object which could be useful in some situations, such as counting the number of
school members. This is called polymorphism when a subtype can be substituted in any situation where a parent type is expected,
that is, the object can be treated as an instance of the parent class.
Note also that we reuse the code from the parent class and do not need to repeat it in the different classes as we would have had
to do if we had used independent classes.
The SchoolMember class in this situation is known as the base class or the super class. The Teacher and Student classes are
called derived classes or subclasses.
SchoolMember class :
"'Represent any member of the
school.'" def in that (
me, name, age ):
self.name = name
self.age = age
print( '(SchoolMember initialized: {})' . format (self.name))
81
Object-oriented programming
member.tell()
Production:
How$python
does it oop_subclass.py
work
(School member initialized: Mrs. Shrividya)
To use inheritance,
(Teacher we specify
initialized: the names
Mrs. of the base classes in a tuple after the class name in the class definition (for example, the
Shrividya)
(School member initialized: Swaroop)
Teacher(SchoolMember) class). Next, we note that the init method of the base class is called explicitly using the self method
(Student initialized: Swaroop)
variable so we can initialize the base class part of an instance in the subclass. This is very important to remember: since we are
defining
Name:an"Ms.
init method in theAge:
Shrividya" Teacher
"40"and Student"30000"
Salary: subclasses, Python does not automatically call the constructor of the
Name: "Swaroop" Age: "25" Points: "75"
SchoolMember base class, you must explicitly call it yourself.
On the contrary, if we have not defined an init method in a subclass, Python will automatically call the constructor of the base
class.
While we could treat instances of Teacher or Student as we would an instance of SchoolMember and access SchoolMember's tell
method by simply typing Teacher.tell or Student.tell, we instead define another tell method in each subclass (using the tell method
of SchoolMember for a part) to adapt it to that subclass. Because we've done this, when we write Teacher.tell Python uses the tell
method for that subclass versus the superclass. However, if we didn't have a tell method in the subclass, Python would use the tell
method in the superclass. Python always starts looking for methods in the actual subclass type first, and if nothing is found, it
starts looking for the methods in the base classes of the subclass, one by one in the order they are specified in the tuple (here we
only have 1 base class,
A note on terminology: if more than one class is listed in the inheritance tuple, it is called multiple inheritance.
The end parameter is used in the print function in the tell() method of the super class to print a line and allow the next print to
continue on the same line. This is a trick to make the print not print a \n (new line) symbol at the end of the print.
Summary
We have now explored the various aspects of classes and objects, as well as the various terminologies associated with them. We
have also seen the benefits and difficulties of object-oriented programming. Python is highly object-oriented and understanding
these concepts carefully will help you a lot in the long run.
Next, we will learn how to handle input/output and how to access files in Python.
82
Input and output
For output, we can also use the various methods of the str(string) class. For example, you can use the rjust method to get a
string that is right-justified to a specified width. See help (str) for more details.
Another common type of input/output is file handling. The ability to create, read, and write files is essential for many programs
and we will explore this aspect in this chapter.
User input
Save this program as io_input.py :
Production:
def counter ( text ):
return text[::- 1
]
How$python3
does it work
io_input.py
Enter text: sir
We No,
use the
def it cut function
is not to reverse
a palindrome
is_palindrome ( text ):the text. We have already seen how we can make sequence cuts using the code seq [a:b] starting
return
from position text
a to == back(text)
position b. We can also provide a third argument that determines the step by which the cut is made. The default
$python3 io_input.py
stepEnter
is 1, sotext:
it returns
ma'ama continuous piece of text. Taking a negative step i.e. -1 will return the text backwards.
Yes, it is=acontribution
something palindrome (
The"Enter
input() text:
function
" takes
) If a string as an argument and displays it to the user. Then wait for the user to type something and press
the return
$ key. Once(something):
python3
is_palindrome the user has entered and pressed the return key, the input() function will return the text that the user entered.
io_input.py Enterit's a
print( "Yes,
We text: racing
take that car
text )and
palindrome" invert
else : it. If the original text and the inverted text are the same, then the text is a palindrome .
Yes, it is a
83
Input and output
Homework exercise
Checking whether a text is a palindrome should also ignore punctuation, spaces, and case. For example, "Get up and vote, sir."
It's also a palindrome, but our current program doesn't say it is. Can you improve the previous program to recognize this
palindrome?
1
If you need a hint, the idea is that...
Files
You can open and use files to read or write by creating an object of the file class and using its read, readline or
write appropriate methods to read or write to the file. The ability to read or write to the file depends on the
mode you have specified for opening the file. Then finally, when you're done with the file, call the close
method to tell Python that we're done using the file.
Production:
poem = '' '\
Programming is fun
when the work is
How$done
does it work
python3 io_using_file.py
Programming
If you want is fun
your work to be fun too:
NoteWhen
thatuse
wePython!
the can
workcreate a new file object simply by using the open method. We open (or create it if it does not already exist) this
is done
file If you
using
'' want your work to be fun too:
' the built-in open function and specifying the file name and the mode in which we want to open the file. The mode can be
use Python!
a read mode ('r'), a write mode ('w'), or an add mode ('a'). We can also specify if we are reading,
# Open for 'writing'
f = open ( 'poem.txt' ,
'w' ) # Write text to
file f.write (poem)
# Close the
file f.close()
# If no mode is specified,
The # 'r'ead mode is assumed by
default f = open ( 'poem.txt' )
True time :
line = f.readline()
# Zero length indicates
EOF If len (line) == 0 :
rip
# The `line` already has a new
line # at the end of each line
# since you are reading from a file.
print(line, end = '' )
# close the
file f.close()
84
Input and output
writing or adding in text mode ('t') or binary mode ('b'). Actually, there are many more modes available and
help (open) will give you more details about them. By default, open() considers the file to be a t'ext file and
opens it in 'r'ead mode.
In our example, we first open/create the file in text writing mode and use the write method of the file object to write our string
variable poem to the file and then finally close the file.
Next, we reopen the same file for reading. We don't need to specify a mode because 'read text file' is the default mode. We read
in each line of the file using the readline method in a loop. This method returns a complete line that includes the newline
character at the end of the line. When an empty string is returned, it means we have reached the end of the file and exit the loop.
We can see in our readline output that this program has actually written to and read our new poem.txt file.
Pickle
Python provides a standard module called pickle that you can use to store any simple Python object in a file and then retrieve it
later. This is called storing the object persistently.
Production:
import pickle
85
Input and output
Unicode
Until now, when we have been writing and using strings, or reading and writing to a file, we have only used simple English
characters. Both English and non-English characters can be represented in Unicode (see the articles at the end of this section for
more information), and Python 3 by default stores string variables (think of all the text we write using single, double or triple
quotes) in Unicode.
NOTE: If you are using Python 2, and we want to be able to read and write in languages other than English, we must use
the Unicode type, and everything starts with the u character, for example, u "hello world".
When data is sent over the Internet, we need to send it in bytes...something your computer easily understands. The rules for
>>> "hello
translating
world" Unicode
'hello (which is what Python uses when storing a string) into bytes is called encoding. A popular encoding to use is
world'
UTF-8. We can read and write UTF-8 using a simple keyword argument in our open function.
>>> type ("hello world")
<class 'str'>
How>>>
does it work
u "hello
# encoding =
world"import
utf-8 'hello
We io
use io.open and then use the encoding argument in the first open statement to encode the message, and then again in the
world'
second open statement when decoding the message. Note that we should only use encoding in the open statement when we are
f = io. open ( "abc.txt" , "wt" , encoding =
in text mode.
"utf-8" ) f. write( u "Imagine a language other
than English here" ) f.close()
Whenever we write a program that uses Unicode literals (putting au before the string) as we have used before, we have to make
suretext
that Python is told( that
= io. open our program
"abc.txt" uses UTF-8,
, encoding= "utf-and we have to put #encoding = utf -8 comments at the top of our program.
8" ).read() print(text)
You should learn more about this topic by reading:
"The absolute minimum that every software developer should absolutely and positively know about Unicode and character sets"
Python Unicode Howto
Unicode Pragmatic Talk by Nat Batchelder
Summary
We have discussed various types of input/output, about file handling, about pickle module and about Unicode. Next,
86
Input and output
1.
Use a tuple (you can find a list of all punctuation marks here ) to hold all prohibited characters, then use the
membership test to determine whether a character should be removed or not, i.e. banned = (,,, ...).! ? . ↩
87
Exceptions
Exceptions
Exceptions occur when exceptional situations occur in your program. For example, what if you are going to read a file and the file
does not exist? Or what if you accidentally deleted it when the program was running? These situations are handled by exceptions.
Similarly, what if your program has some invalid declarations? This is handled by Python, which raises its hand and tells you
there's an error.
Mistakes
Consider a simple call to the print function. What happens if we misspell print as Print? Please note the capitalization. In this case,
Python
raises a syntax error.
Note>>>
thatPrint(
a NameError
"Hello isWorld"
raised and
) the location where the error was detected is also printed. This is what an error handler is
Trace
because (recent
this calls
error does it. plus
latest):
File "<stdin>" , line 1 , in <module>
NameError: name 'Print' is not defined
Exceptions
>>> print( "Hello World" )
Hello World
We will try to read the user's input. Enter the first line below and press the Enter key. When your computer asks you to enter,
press [ctrl-d] on a Mac or [ctrl-z] with Windows and see what happens. (If you are using Windows and neither option works,
you can try [ctrl-c] in the command prompt to generate a KeyboardInterrupt error instead.)
Python throws an error called EOFError which basically means that it encountered an end-of-file symbol (which is represented
>>> s = input ('Enter something ->')
by ctrl-d)
Enter when it didn't
something ->expect to see(most
Traceback it. recent last
call): File "<stdin>", line 1, in <module>
EOFError
Exception Handling
We can handle exceptions using try..except statement. Basically, we put our usual statements inside the try block and all our
error handlers in the except block.
attempt :
text = input ( 'Enter something ->' )
except EOFError:
print( 'Why did you EOF me?' ) except
KeyboardInterrupt:
print( You have canceled the operation. )
88
Exceptions
the rest :
print( 'You entered {}' . format (text))
Production:
How# does
Pressit ctrl
work+ d
$pythonexceptions_handle.py
We Enter
place all statements
something ->that
Whycan
didraise
youexceptions/errors
EOF me? inside the try block and then place handlers for the appropriate
errors/exceptions in the except clause/block. The except clause can handle a single specified error or exception, or a
# Press ctrl + c
parenthesized list of errors/exceptions. If no error or exception names are provided, it will handle all errors and exceptions.
$pythonexceptions_handle.py
Enter something -> ^ C You canceled the operation.
Note that there must be at least one except clause associated with each try clause. Otherwise what's the point of having a test
block?
$ python exceptions_handle.py
Enter something -> No
If any error or exception
exceptions Entered is
Nonot handled, the default Python handler is called, which simply stops the program from running and
exceptions
prints an error message. We've seen this in action before.
You can also have an else clause associated with a try..except block. The else clause is executed if no exception is thrown. In the
following example, we will also see how to get the exception object so we can retrieve additional information.
Exception generation
You can raise exceptions using the raise statement by providing the name of the error/exception and the exception object to be
thrown.
The error or exception that may be raised must be a class that must directly or indirectly be a derived class of the exception.
class.
attempt :
text = input ( 'Enter something ->'
) If len (text) < 3 :
raise ShortInputException ( len
(text), 3 ) # Other work can continue as
usual here
except EOFError:
print( 'Why did you EOF me?' ) except
ShortInputException as ex:
89
Exceptions
the rest :
print( "No exception was raised." )
Production:
$ python
In the except clause, we mention the error class to be stored as the variable name to hold the corresponding error/exception
exceptions_raise.py Enter
object. This is analogous to parameters and arguments in a function call. Within this particular exception clause, we use the
something -> abc
length and at least the fields of the exception object to print an appropriate message to the user.
Production:
import sys
import time
$
f python
= exceptions_finally.py
Programming
None is fun
Press
try : ctrl + c now
^C!!fYou canceled
= open reading )
( "poem.txt" the file.
# Our usual file reading
language True time :
line =
f.readline() If
len (line) ==
0 :
break
print(line, end
= '' )
sys.stdout.flush
()
print( "Press ctrl + c now" )
# To make sure it runs during a sleep
time( 2 )
except IOError:
print( "The file poem.txt could not be
found" ) except KeyboardInterrupt:
print( "You have canceled reading the file." )
90
Exceptions
We do the usual file reading stuff, but we've arbitrarily introduced sleeping for 2 seconds after printing each line using the
sleep time function to make the program run slowly (Python is very fast by nature). When the program is still running,
press
Notice that the KeyboardInterrupt exception is thrown and the program exits. However, before the program exits, the finally
clause is executed and the file object is always closed.
Note that a variable that is assigned a value of 0 or None or a variable that is an empty sequence or collection is considered False
by Python. That's why we can use if f: in the above code.
Also note that we use sys.stdout.flush() after print so that it prints to the screen immediately.
Save as exceptions_using_with.py :
Howwith
doesopen
it work
( "poem.txt" )
as F: per line in F:
The output should be the same
print(line, end as in the
= '' ) previous example. The difference here is that we are using the open function with the con
declaration: we let the file closing be done automatically with open.
What happens behind the scenes is that there is a protocol used by the with statement. Gets the object returned by the
open statement, let's call it "the file" in this case.
It always calls the file. enter function before starting the code block below it and always calls the file. Exit
So the code we would have written in a block should finally be automatically taken care of by the exit method. This is what
helps us avoid having to use explicit try..finally statements repeatedly.
Further discussion of this topic is beyond the scope of this book, so see PEP 343 for a full explanation.
Summary
We have discussed the use of try..except and try..finally statements. We have seen how to create our own exception types and
also how to raise exceptions.
91
Standard Library
Standard Library
The Python standard library contains a large number of useful modules and is part of every standard Python installation. It is
important to become familiar with the Python standard library, as many problems can be solved quickly if you are familiar with
the variety of things these libraries can do.
We will explore some of the commonly used modules in this library. You can find full details of all the modules in the Python
standard library in the 'Library Reference' section of the documentation that comes with your Python installation.
CAUTION: If you find the topics in this chapter too advanced, you can skip this chapter. However, I highly recommend
returning to this chapter when you feel more comfortable programming with Python.
sys module
The sys module contains system-specific functions. We have already seen that the sys.argv list contains the command line
arguments.
Suppose we want to check the version of Python software being used, the sys module gives us that information.
How>>>
does it work
import sys
>>> sys.version_info
Thesys.version_info
sys module has a version_info
(major = 3 tuple that =gives
, minor 6 , us the version
micro information. The
= 0 , releaselevel first entry, isserial
= 'final' the main
= 0version.
) We can
>>> sys.version_info.major ==
extract this information for use.
3 true
Module login
What if you wanted to have some debug messages or important messages to store somewhere so you could check if your
program has been running as you would expect? How do you "save somewhere" these messages? This can be achieved using
the registration module.
Save as stdlib_logging.py :
import os
import
platform
import Login
logging.basicConfig (
92
Standard Library
level = logging.DEBUG,
format = '%(asctime)s:%(levelname)s:%(message)s'
, filename = log_file,
filemode = 'w' ,
)
Production:
The$cat command
python is used on the command
stdlib_logging.py Log line to read the 'test.log' file. If the cat command is not available, you can open the
tofile
test.log /Users/swa/test.log
instead in a text editor.
How$ does
cat /Users/swa/test.log
it work
2014-03-29 09:27:36,660: DEBUG: Start of program
First, we check which operating system we are using by checking the string returned by platform.platform() (for more
information, see import platform; help (platform)). If it is Windows, we find out the startup disk, the startup folder and the name
of the file where we want to store the information. Putting these three parts together, we get the complete location of the file. For
other platforms, we need to know only the user's home folder and get the full file location.
We use the os.path.join() function to join these three parts of the location. The reason to use a special function instead of
simply adding the strings is because this function will ensure that the entire location matches the format expected by the
operating system. Note the join() method we use here which is part of the OS module is different from the string
We configure the logging module to write all messages in a particular format to the file we have specified.
Finally, we can put messages that are intended for debugging, information, warning or even critical messages. Once the
program has run, we can check this file and we will know what happened in the program, although no information was shown
to the user running the program.
The best way to further explore the standard library is to read Doug Hellmann's excellent book. Python Module of the Week series
(also available as a book ) and reading the Python Documentation .
Summary
We have explored some of the features of many modules in the Python standard library. It is highly recommended to browse the
Python Standard Library documentation to get an idea of all the modules available.
93
Standard Library
Below we will cover various aspects of Python that will make our tour of Python more complete.
94
Furth
er
Further
So far we have covered most of the various aspects of Python that you will use. In this chapter, we will cover some more
aspects that will make our knowledge of Python more complete.
Note>>>
thatdef
using a, b = <some expression>
get_error_details (): interprets the result of the expression as a tuple with two values. This also
... return ( 2 , 'details' )
means
...that the fastest way to swap two variables in Python is:
>>> errnum, errstr = get_error_details()
>>>
>>> a =25 ; b = 8
errnum
>>> a,
errstr
b (
'details'
5 ,
8 )
>>> a, b = b, a
Special methods
There are certain methods, such as the init and del methods, that have special meaning in classes.
Special methods are used to imitate certain behaviors of built-in types. For example, if you want to use the x[key] indexing
operation for your class (just like you use it for lists and tuples), then all you have to do is implement the getitem() method and your
job is done. If you think about it, this is what Python does for the list class itself!
Some useful special methods are listed in the following table. If you want to know all the special methods, see the manual .
This method is called just before the newly created object is returned for use.
of (oneself)
Called just before the object is destroyed (which has unpredictable timing, so avoid using this)
str (self)
Called when the less than operator (<) is used. Similarly, there are special methods for all operators (+, >, etc.)
get object (self, key)
95
Furth
er
len (me)
Called when the built-in len() function is used for the sequence object.
Note that the single statement is used in place and not as a separate block. Although you can use this to make your program
>>> flag = True
smaller,
>>> IfI strongly recommend
flag: print avoiding
( 'Yes' ) this shortcut method except for error checking, mainly because it will be much easier to
add ...
an extra declaration if you are using proper indentation.
Yeah
Lambda forms
A lambda statement is used to create new function objects. Essentially, the lambda takes a parameter followed by a single
expression. Lambda becomes the body of the function. The new function returns the value of this expression.
Production:
points = [{ 'X' : 2 ,
'y' : 3 },
{ 'X' : 4 , 'y' : 1 }]
Howpoints.sort(key
does it more_lambda.py
$python work = lambda self:
self[ 'y'
[{'y': 1, ]) print(points)
'x': 4}, {'y': 3, 'x': 2}]
Note that a list's sort method can take a key parameter that determines how the list is sorted (usually we only know the
ascending or descending order). In our case, we want to do a custom sort, and for that we need to write a function. Instead of
writing a separate def block for a function that will be used only in this place, we use a lambda expression to create a new
function.
List Comprehension
List comprehensions are used to derive a new list from an existing list. Suppose you have a list of numbers and you want to get a
corresponding list with all numbers multiplied by 2 only when the number itself is greater than 2. List comprehensions are ideal
for such situations.
ribbon = [ 2 , 3 , 4 ]
listtwo = [ 2 *I for I in listone if i > 2 ]
96
Furth
er
Production:
How$python
does it more_list_comprehension.py
work
[6, 8]
Here, we derive a new list by specifying the manipulation to perform (2 * i) when some condition is met (if i > 2). Please note
that the original list remains unchanged.
The advantage of using list comprehensions is that it reduces the amount of boilerplate code required when we use loops to
process each element of a list and store it in a new list.
Because we have a * prefix in the args variable, all additional arguments passed to the function are stored in args as a tuple. If a
>>> def powersum ( power, * arguments ):
** prefix instead, additional parameters would be considered key/value pairs of a dictionary.
... '' 'Returns the sum of each argument raised to the specified power.' ''
... total = 0
... for I in arguments:
The
...
...
assertion statement
total + = pow (self, power)
full return
...
The>>>
assertion statement
powersum 2 , 3is,used
4 ) to assert that something is true. For example, if you are very sure that you will have at least one
25 in a list that you are using and you want to verify it, and raise an error if it is not true, then the assertion statement is
element
>>> powersum 2 , 10 )
ideal100
in this situation. When the assertion statement fails, an AssertionError is raised. The pop() method removes and returns
the last element in the list.
The>>>
statement
mylistshould be used with
= [ 'Article' ] caution. Most of the time, it is better to catch exceptions, either handle the problem or display
>>> assert len (mylist) >= 1
an error message to the user and then exit.
>>>
mylist.pop()
'Item'
>>> assert len (my list) > = 1
Trace (recent calls plus
latest):
97
Furth
er
Decorators
Decorators are a shortcut to apply wrapper functions. This is useful for "tweaking" functionality with the same code over and over
again. For example, I created a retry decorator for myself that I can apply to any function and if any exception is thrown during a
run, it is retried, up to a maximum of 5 times and with a delay between each retry. This is especially useful for situations where
you are trying to make a network call to a remote computer:
Production:
time import sleep from
functools import wraps
import log
$python more_decorator.py
logging.basicConfig()
Write to a database or make a network call, etc.
log = logging.getLogger( "rever" )
This will be automatically retried if an exception is
thrown. ERROR: retry: 1/5 attempt failed: (('Some bad
value',), {}) Traceback (most recent last call):
def rever ( F
File "more_decorator.py", line 14, in
):
wrapper_function return f (* args, ** kwargs)
@ wrappers
The file
(f) "more_decorator.py", line 39, in
save_to_database
def raises
wrapper_function ValueError(arg)
( *args, **kwargs ):
ValueError: Some bad =
MAX_ATTEMPTS value
5
Write toperattempt
a databaseinordistance
make a network
( 1 , call, etc.
MAX_ATTEMPTS + 1 ): try :
return f (*args, **kwargs)
except Exception:
log.exception( "Attempt %s/%s failed: %s" ,
attempt,
MAX_ATTEMPTS,
(args, kwargs))
sleep ( 10 * attempt)
log.critical "All %s attempts failed: %s" ,
MAX_ATTEMPTS,
(arguments,
kwargs)) return wrapper_function
counter = 0
@review
def save_to_database ( arg ):
print( "Write to a database or make a network call, etc." )
print( "This will be retried automatically if an exception is
thrown." ) global counter
counter += 1
# This will throw an exception on the first call
# And it will work fine on the second call (i.e. a
retry) If counter < 2 :
raise ValueError(arg)
98
Furth
er
See:
Library "Six"
Porting to Python 3 Redux by Armin
Python 3 Experience by PyDanny
Official Django Guide to Migrating to Python 3
Discussion on What are the advantages of Python 3.x?
Summary
We have covered a few more features of Python in this chapter and however, we have not covered all the features of Python.
However, at this stage, we've covered most of what you'll use in practice. This is enough to get you started with any program you
are going to create.
99
Whats
Next
Whats Next
If you have read this book carefully until now and have practiced writing many programs, then you must have been familiar with
Python. You've probably created a few Python programs to try things out and also to exercise your Python skills. If you haven't
already, you should. The question now is 'What's next?'
Create your own command line address book program with which you can browse, add, modify, delete or search your
contacts such as friends, family and colleagues and their information such as email address and/or number of phone. The
details must be stored for later retrieval.
This is pretty easy if you think about it in terms of all the things we've encountered so far. If you still want instructions on how
1
to proceed, here's a hint .
Once you can do this, you can claim to be a Python programmer. Now, immediately send me an email thanking me for this great
book ;-). This step is optional but recommended. Also, please consider purchasing a print copy to support the continued development
of this book.
Implement the replace command . This command will replace one string with another in the list of provided files.
The replace command can be as simple or sophisticated as you want, from simple string substitution to searching for patterns
(regular expressions).
Next projects
If you find the above programs easy to create, look at this complete list of projects and try writing your own programs:
https://github.com/thekarangoel/Projects#numbers (the same list is also on Martyr2's Mega Projects List ).
See also:
Example code
The best way to learn a programming language is to write a lot of code and read a lot of code:
Python Cookbook is an extremely valuable collection of recipes or tips on how to solve certain types of problems using
Python. This is a must read for all Python users.
Python Module of the Week is another excellent must-read guide for Standard Library .
Advice
The Hitchhiker's Guide to Python!
The Elements of Python Style
Python Overview
"Writing Idiomatic Python" eBook (paid)
100
Whats
Next
Videos
Full Stack web development with Flask
PyVideo
Tutorials
Hidden Python Features
What's the one Python code snippet/trick/etc you wish you knew when learning Python?
Complete List of Python Tutorials from Awaretek
Discussion
If you have a Python problem and don't know who to ask, then the python-tutor list is the best place to ask your question.
Make sure you do your homework by trying to solve the problem yourself first and ask intelligent questions .
News
If you want to know what's latest in the world of Python, follow the official Python Planet .
Install libraries
There are a lot of open source libraries in the Python Package Index that you can use in your own programs. To install and
Create a website
Learn Flask to create your own website. Some resources to get you started:
Graphics software
101
Whats
Next
Suppose you want to create your own graphical programs using Python. This can be done using a GUI (graphical user interface)
library with its Python bindings. Bindings are what allow you to write programs in Python and use libraries that are written in C or
C++ or other languages.
Kivy
http://kivy.org
PyGTK
This is the Python link for the GTK+ toolkit, which is the foundation on which GNOME is built. GTK+ has a lot of
quirks in use, but once you get comfortable, you can create GUI applications quickly. The Glade signer graphical
interface is indispensable. The documentation hasn't improved yet. GTK+ works fine on GNU/Linux but its Windows
port is incomplete. You can create both free and proprietary software using GTK+. To get started, read the PyGTK
Tutorial .
PyQt
This is the Python binding for the Qt toolkit, which is the foundation on which KDE is built. Qt is extremely easy to use
and very powerful, especially because of the Qt Designer and the amazing Qt documentation. Py Qt is free if you want to
create open source (GPL'ed) software and you need to purchase it if you want to create proprietary closed source
software. Starting with Qt 4.5, you can also use it to create non-GPL software. To get started, read about PySide .
wxPython
These are the Python bindings for the wxWidgets toolkit. wxP ython has a learning curve associated with that.
However, it is very portable and runs on GNU/Linux, Windows, Mac, and even embedded platforms. There are many
IDEs available for wxPython, including GUI designers as well as SPE (Stani's Python Editor) and the wxGlade GUI
Builder. You can create free and proprietary software using wxPython. To get started, read the wxPython tutorial .
Unfortunately, there is no standard GUI tool for Python. I suggest you choose one of the above tools based on your situation. The
first factor is whether you are willing to pay to use any of the GUI tools. The second factor is whether you want the program to
run on Windows only or on Mac and GNU/Linux or all of them. The third factor, whether GNU/Linux is a platform of choice, is
whether you are a KDE or GNOME user on GNU/Linux.
For a more detailed and complete analysis, see page 26 of 'The Python Papers, Volume 3, Issue 1' (PDF) .
Various implementations
Typically, a programming language consists of two parts: the language and the software. A language is how you write
something. Software is what actually runs our programs.
We have been using CPython software to run our programs. It is known as CPython because it is written in the C language and is
the classic Python interpreter.
There is also other software that can run your Python programs:
Jython
A Pyt hon implementation that runs on the Java platform. This means that you can use Java libraries and classes from the
Python language and vice versa.
IronPython
A Python implementation that runs on the .NET platform. This means that you can use .NET libraries and classes from
102
Whats
Next
A Python implementation written in Python! This is a research project to make it faster and easier to improve the interpreter
since the interpreter itself is written in a dynamic language (as opposed to static languages such as C, Java or C# in the
three implementations above).
There are also others like CLPython - a Python implementation written in Common Lisp and Brython which is an implementation
on top of a JavaScript interpreter which could mean you can use Python (instead of JavaScript) to write your web browser
programs ("Ajax" ).
Each of these implementations has its specialized areas where they are useful.
Summary
We have reached the end of this book but, as they say, this is the beginning of the end! You are now an avid Python user and no
doubt ready to solve many problems using Python. You can start automating your computer to do all kinds of previously
unimaginable things or write your own games and much more. So get started!
1. Create a class to represent the person information. Use a dictionary to store person objects with their name as the key.
Use the pickle module to store objects persistently on your hard drive. Use the dictionary's built-in methods to add, delete,
103
Appendix: FLOSS
Appendix: FLOSS
NOTE: Please note that this section was written in 2003, so some of this will seem strange to you :-)
"Free/libre and open source software", in short, SILK FLOJA is based on the concept of community, which in turn is based on
the concept of sharing and, in particular, the exchange of knowledge. FLOSS are free to use, modify and redistribute.
If you have already read this book, then you are already familiar with FLOSS as you have been using Python all the time and
Python is an open source software.
Here are some FLOSS examples to give an idea of the kinds of things sharing and building a community can create:
Linux : This is a FLOSS OS kernel used in the GNU/Linux operating system. Linux, the kernel, was pioneered by Linus Torvalds
when he was a student. Android is based on Linux. Any website you use these days will primarily run on Linux.
Ubuntu : This is a community-driven distribution, sponsored by Canonical and is the most popular GNU/Linux distribution
today. It allows you to install a large number of available FLOSS and all this in an easy to use and easy to install way. Best of all,
you can reboot your computer and run GNU/Linux from the CD. This allows you to fully test the new operating system before
installing it on your computer. However, Ubuntu is not completely free software; Contains proprietary drivers, firmware and
applications.
LibreOffice : This is a great community-developed and driven office suite with a writer, presentation, spreadsheet, and drawing
components, among other things. You can even open and edit MS Word and MS PowerPoint files with ease. It runs on almost
all platforms and is completely free, open source and open source software.
Mozilla Firefox : This is the best web browser. It's incredibly fast and has earned critical praise for its sensible and impressive
features. The concept of extensions allows you to use any type of plugin.
Infectious mononucleosis : This is an open source implementation of the Microsoft .NET platform. It allows creating and
running .NET applications on GNU/Linux, Windows, FreeBSD, Mac OS and many other platforms as well.
Apache Web Server : This is the popular open source web server. In fact, it is the most popular web server on the planet! It
runs almost more than half of the websites out there. Yes, it's true: Apache runs more websites than all the competition
(including Microsoft IIS) combined.
VLC Player : This is a video player that can play anything from DivX to MP3 to Ogg to VCD and DVD to... who says open
source isn't fun? ;-)
This list is only intended to give you a brief idea: there are many more excellent FLOSS, such as Perl language, PHP language,
Drupal content management system for websites, PostgreSQL database server, racing game TORCS, KDevelop IDE, Xine... the
movie player, the VIM editor, the Quanta+ editor, the Banshee audio player, the GIMP image editing program,... This list could go
on forever.
For the latest news from the world of FLOSS, visit the following websites:
MY GOD!
Ubuntu! Web
Upd8
DistroWatch
Planet Debian
Explore GitHub
Code Triage
SourceForge Fresh
Meat
104
Appendix: FLOSS
So, go ahead and explore the vast, free and open world of FLOSS!
105
Appendix: About
Appendix: Colophon
Almost all of the software I used in creating this book is SILK FLOJA .
Initially, I was using KWord to write the book (as explained in the history lesson ).
Adolescence
Later, I switched to DocBook XML using Kate, but found it too tedious. So I switched to OpenOffice, which was great with the
level of control it provided for formatting and PDF generation, but produced very sloppy HTML from the document.
Eventually, I discovered XEmacs and rewrote the book from scratch in DocBook XML (again) after I decided this format was
the long-term solution.
On the sixth draft, I decided to use Quanta+ to do all the editing. The standard XSL stylesheets that came with Fedora Core 3
Linux were being used. However, I had written a CSS document to color and style the HTML pages. I had also written a
rudimentary lexical analyzer, in Python of course, that automatically provides syntax highlighting to all program listings.
For the seventh draft, I was using MediaWiki as the basis of my setup. I used to edit everything online and readers can
read/edit/discuss directly within the wiki website, but I ended up spending more time fighting spam than writing.
For the ninth draft, I switched to AsciiDoc format and used Emacs 24.3 , Tomorrow's Theme , Fira Mono Font and adoc mode
to write.
Now
2016: I got tired of several minor rendering issues in AsciiDoctor, like ++ in C/C++ would disappear and it was hard to keep
track of how to escape such small things. Additionally, I had become reluctant to edit the text due to the complex Asciidoc
format.
For the tenth draft, I switched to writing in Markdown + GitBook format, using the Spacemacs Editor .
November 2020: Since Gitbook abandoned its open source software, it has migrated to Honkit, a community-maintained fork
of Gitbook's legacy .
106
Appendix: Revision History
Then, I started looking for a good book on Python. I couldn't find any! I found some O'Reilly books, but they were either too
expensive or seemed more like a reference manual than a guide. So, I settled for the documentation that came with Python.
However, it was too short and small. Gave a good idea about Python, but it wasn't complete. I managed because I had previous
programming experience, but it wasn't suitable for beginners.
About six months after my first contact with Python, I installed the (then) latest Red Hat 9.0 Linux and was playing with KWord.
I got excited and suddenly had the idea to write some things in Python. I started writing a few pages, but it quickly turned into
30. Then I got serious about making it more useful in book form. After many rewrites, it has reached a stage where it has become
a useful guide for learning the Python language. I consider this book to be my contribution and tribute to the open source
community.
This book started out as my personal notes on Python and I still think of it the same way, although I've put a lot of effort into
making it more enjoyable for others :)
In the true spirit of open source, I have received many constructive suggestions, criticism, and feedback from enthusiastic readers,
which has helped me greatly improve this book.
Book status
The book needs the help of its readers, like you, to point out any part of the book that is not good, understandable, or just plain
wrong. Please write to the main author or the respective translators with your comments and suggestions.
November 6, 2020
Migrated from abandoned GitBook to community-maintained Honkit, a fork of GitBook legacy
4.0
August 3, 2013
Rewritten using Markdown and Markdown Mode by Jason Blevins
2.0
107
Appendix: Revision History
March 9, 2004
More typo fixes, thanks to many enthusiastic and helpful readers.
1,00
March 8, 2004
After tremendous feedback and suggestions from readers, I made major revisions to the content along with typo
corrections.
0,99
January 5, 2004
Changes in some examples.
0,91
108
Appendix: Revision History
0,90
109
Appendix: Translations
Translations
There are many translations of the book available in different human languages, thanks to many tireless volunteers!
If you would like to help with these translations, check out the list of volunteers and languages below and decide whether you
want to start a new translation or help on existing translation projects.
Arabic
Below is the link for the Arabic version. Thanks to Ashraf Ali Khalaf for translating the book, you can read the full book online at
http://www.khaledhosny.org/byte-of-python/index.html or you can download it from sourceforge.net for more information see
http: //itwadi.com/byteofpython_arabi .
Azerbaijani
Jahangir Shabiyev ([email protected]) has volunteered to translate the book into Azerbaijani. Translation is in progress at
https://www.gitbook.com/book/jahangir-sh/piton-sancmasi
Brazilian Portuguese
There are two translations at various levels of completion and accessibility. The older translation is now missing/lost, and the
newer translation is incomplete.
Samuel Dias Neto ([email protected]) did the first Brazilian Portuguese translation (previous translation) of this book
when Python was at version 2.3.5. This is no longer publicly accessible.
Rodrigo Amaral ( [email protected] ) has volunteered to translate the book into Brazilian Portuguese, (most recent
translation) which is yet to be completed.
Catalan
Moises Gomez ([email protected]) has volunteered to translate the book into Catalan. Translation is in progress.
Moisès Gómez - I am a developer and also a programming teacher (normally for people with no prior experience).
Some time ago I needed to learn how to program in Python, and Swaroop's work was really helpful. Clear, concise and
complete enough. Just what I needed.
After this experience, I thought that other people in my country could also benefit from it. But the English language can be
a barrier.
So why not try to translate it? And I did it for an older version of BoP.
In my country there are two official languages. I selected the Catalan language assuming that others would translate it into
the more widespread Spanish.
Chinese
110
Appendix: Translations
In 2017, which is after 11 years, Mo Lun ([email protected]) retranslated the book from the beginning based on Version 4.0. And the
translation is stored on GitHub and Gitbook. He is still following this translated edition and ready to fix it if there are any errors or
errors in the translated database.
Mo Lun says:
I am an ordinary journalism student from CYU, Beijing. And in fact, I am an absolute newbie to Python programming
when I start translating this book. Initially, it was just a whim, but when I did this work, I realized that a decision triggered
by interest had driven me to go this far.
With the help of my predecessors' translations and the wealth of information provided by the developed Internet, and with
the help of my friends, I prudently presented this translation edition. I just hope that my translation work helps other
newcomers learn Python.
At the same time, I am always waiting for my translation of comments and suggestions, and ready to change or improve
this superficial work.
I am a postgraduate in Wireless Telecommunication Graduate School, Beijing University of Technology, China PR. My
current research interest focuses on synchronization, channel estimation and multi-user detection of multi-carrier CDMA
system. Python is my main programming language for daily simulation and research work, with the help of Python
Numeric, actually. I learned Python only half a year before, but as you can see, it's really easy to understand, easy to use,
and productive. Just like what is claimed in Swaroop's book, 'It's my favorite programming language now'.
'A Byte of Python' is my tutorial for learning Python. It is clear and effective in getting you into a Python world in the
shortest time possible. It's not too long, but it efficiently covers almost all the important things in Python. I think 'A Byte
of Python' should be highly recommended for beginners as their first Python tutorial. I only dedicate my translation to the
potential millions of Python users in China.
Traditional Chinese
Fred Lin ([email protected]) has volunteered to translate the book into traditional Chinese.
It is available at http://code.google.com/p/zhpy/wiki/ByteOfZhpy .
An interesting feature of this translation is that it also contains the executable Chinese Python sources along with the original
Python sources.
Fred Lin: I work as a Network Firmware Engineer at Delta Network and am also a contributor to the TurboGears web
framework.
As a Python evangelist (:-p), I need material to promote the Python language. I found that 'A Byte of Python' hit the sweet
spot for both novice and experienced programmers. 'A Byte of Python' elaborates the essential elements of Python in an
affordable size.
The translation was originally based on the simplified Chinese version, and many rewrites were soon made to adapt to the
current wiki version and reading quality.
111
Appendix: Translations
The recent traditional Chinese version also included Chinese python executable sources, which is achieved with my new
project 'zhpy' (python in Chinese) (released since August 07).
zhpy (pronounce (ZH ?, or zippy) builds a layer on top of python to translate or interact with python in Chinese (traditional or
simplified). This project is mainly aimed at education.
French
Gregory ([email protected]) has volunteered to translate the book into French.
Gérard Labadie ([email protected]) has finished translating the book into French.
This translation was then moved to markdown format, updated to match the latest version of the book, and posted to GitBook
by Romain Gilliotte ([email protected]).
German
Lutz Horn (lutz.h [email protected]), Bernd Hengelein ([email protected]) and Christoph Zwerschke ([email protected]) have
volunteered to translate the book into German.
I am 32 years old and I have a degree in Mathematics from the University of Heidelberg, Germany. I currently work as
software engineer on a publicly funded project to build a web portal for all things IT in Germany. The main language I use as
a professional is Java, but I try to do as much as possible with Python behind the scenes. Especially text parsing and
conversion are very easy with Python. I'm not very familiar with GUI toolkits, as most of my programming deals with web
applications, where the user interface is built using Java frameworks like Struts. I'm currently trying to make more use of
Python's functional programming features and generators. After taking a look at Ruby, I was very impressed with the use of
blocks in this language. I generally like the dynamic nature of languages like Python and Ruby, as it allows me to do things
that aren't possible in more static languages like Java. I've been looking for some kind of introduction to programming,
suitable for teaching a complete non-programmer. I found the book “How to Think Like a Computer Scientist: Learning with
Python” and “Dive into Python”. The first one is good for beginners, but longs to translate it. The second is not suitable for
beginners. I think 'A Byte of Python' ranks very well among these, as it is not too long, written to the point, and at the same
time detailed enough to teach a novice. In addition to this, I like DocBook's simple structure, which makes translating text
from one generation to output in various formats a charm. The first one is good for beginners, but longs to translate it. The
second is not suitable for beginners. I think 'A Byte of Python' ranks very well among these, as it is not too long, written to
the point, and at the same time detailed enough to teach a novice. In addition to this, I like DocBook's simple structure,
which makes translating text from one generation to output in various formats a charm. The first one is good for beginners,
but longs to translate it. The second is not suitable for beginners. I think 'A Byte of Python' ranks very well among these, as it
is not too long, written to the point, and at the same time detailed enough to teach a novice. In addition to this, I like
DocBook's simple structure, which makes translating text from one generation to output in various formats a charm.
Lutz and I will do the German translation together. We've just started on the introduction and preface, but we'll keep you
posted on the progress we make. Ok, now some personal things about me. I'm 34 years old and have been playing with
computers since the 1980s, when the "Commodore C64" ruled kindergartens. After studying computer science, I started
working as a software engineer. I currently work in the field of medical imaging for a major German company. Although
C++ is the main language I (have to) use for my daily work, I am constantly looking for new things to learn. Last year I fell
in love with Python, which is a wonderful language, both for its possibilities and its beauty. I read somewhere on the net
about a guy who said he likes Python, because the code looks very beautiful. In my opinion, you are absolutely right. At
112
Appendix: Translations
the time I decided to learn Python, I noticed that there is very little good documentation available in German. When I came
across your book, the spontaneous idea of a German translation crossed my mind. Fortunately, Lutz had the same idea and
now we can divide the work. I hope for a good cooperation!
113
Appendix: Translations
Greek
The Ubuntu C Greek ommunity trans said book in Greek , for use in our online asynchronous Python lessons that take place on our
forums. Contact @savvasradevic for more information.
Indonesian
Daniel ([email protected]) is translating the book into Indonesian at
Italian (first)
Enrico Morelli ([email protected]) and Massimo Lucci ([email protected]) have volunteered to translate the book
into Italian.
Massimo Lucci and Enrico Morelli - we are working at the University of Florence (Italy) - Department of Chemistry. I
(Massimo) as a service engineer and system administrator for nuclear magnetic resonance spectrometers; Enrico as a
service engineer and systems administrator for our CED and parallel/cluster systems. We have been programming in
Python for about seven years, we had experience working with Linux platforms for ten years. In Italy we are responsible
and administrators of www.gentoo.it website for the distribution of Gentoo / Linux and www.nmr.it (now under
construction) for Nuclear Magnetic Resonance and Congress Organization and Management applications. That's all! We're
impressed by the clever language used in your book and believe this is essential to bringing Python to new users (we're
thinking hundreds of students and researchers working in our labs).
Italian (second)
An Italian translation has been created by Calvina Bice and colleagues at http://besthcgdropswebsite.com/translate/a-byte-of-
pitón/ .
Japanese
Shunro Dozono ([email protected]) is translating the book into Japanese.
Korean
Epsimatt (2019)
Epsimatt has started a new Korean translation:
Elderly
Jeongbin Park ([email protected]) has translated the book into Korean - https://github.com/pjb7687/byte_of_python
114
Appendix: Translations
I am Jeongbin Park, and I am currently working as a Biophysics and Bioinformatics researcher in Korea.
A year ago, I was looking for a good tutorial/guide for Python to present to my colleagues, because the use of Python in
such research fields is becoming inevitable as the user base is growing more and more.
But at that time, only a few Python books are available in Korean, so I decided to translate your ebook because it seems
like one of the best guides I've read.
Currently, the book is almost completely translated into Korean, except for some of the text in the introductory chapter and
the appendices.
Mongolian
Ariunsanaa Tunjin ([email protected]) has volunteered to translate the book into Mongolian.
Norwegian (Bokmål)
Eirik Vågeskar is a high school student at Sandvika videregående skole in Norway, a blogger and is currently translating the book
into Norwegian (Bokmål).
Eirik Vågeskar : I always wanted to program, but since I speak a small language, the learning process was much more
difficult. Most tutorials and books are written in very technical English, so most high school graduates won't even have the
vocabulary to understand what the tutorial is about. When I discovered this book, all my problems were solved. "A Byte of
Python" used simple, non-technical language to explain a programming language that is just as simple, and these two things
make learning Python fun. After reading half of the book, I decided it was worth translating. I hope that the translation will
help people who have found themselves in the same situation as me (especially young people), and maybe help spread
interest in the language among people with less technical knowledge.
Polish
Dominik Kozaczko ([email protected]) has volunteered to translate the book into Polish. The translation is in progress
and its main page is available here: Ukąś Pythona .
Update : The translation is complete and ready as of October 2, 2009. Thanks to Dominik, his two students, and his friend for
their time and effort!
Portuguese
A translation of this book into Portuguese has been completed by Artur Weber ([email protected]) (as of February
21, 2018) at https://www.homeyou.com/~edu/introducao .
Artur Weber : My students study at the Polytechnic Faculty of the Ecological University of the city of Curitiba (Brazil)
and some of them are interested in different jobs.
While writing academic and course papers, they always look for interesting articles and pages. I also do my best to find
interesting materials that can be the source of your university papers.
115
Appendix: Translations
I found the materials on your site useful for some of my students who are writing articles based on Python programming.
Actually, that is why I made the decision to make a Portuguese translation so that my students who do not know English
read interesting articles in their native language (in Portuguese).
Romanian
Paul-Sebastian Manole ([email protected]) has volunteered to translate this book into Romanian.
Paul-Sebastian Manole - I am a second year Computer Science student at Spiru Haret University, here in Romania. I'm
more of a self-taught programmer and decided to learn a new language, Python. The web told me there was no better way
to do it than reading "A Python Byte". That's how popular this book is (kudos to the author for writing such an easy-to-
read book). I started to like Python, so I decided to help translate the latest version of Swaroop's book into Romanian.
Although I might be the one with the first initiative, I'm just a volunteer, so if you can help, join me.
Russian
A Russian translation has been completed by Vladimir Smolyar ([email protected]) at http://wombat.org.ua/AByteOfPython/ .
Ukrainian
Averkiev Andrey ( [email protected] ) has volunteered to translate the book into Russian, and perhaps Ukrainian (time permitting).
Serbian
"BugSpice" ([email protected]) has completed a Serbian translation:
Slovak
Albertio Ward ([email protected]) has translated the book into Slovak at http://www.fatcow.com/edu/python-swaroopch-sl/
:
We are a non-profit organization called "Translation for Education". We represent a group of people, mainly students and
teachers, from the Slavic University. There are students from different departments here: linguistics, chemistry, biology,
etc. We try to find interesting posts on the Internet that may be relevant to us and our university classmates. Sometimes we
find items ourselves; other times our teachers help us choose the material to translate. After obtaining permission from the
authors, we translate the articles and publish them on our blog, which is available and accessible to our colleagues and
friends. These translated publications often help students in their daily study routine.
Spanish
Alfonso de la Guarda Reyes ( [email protected] ), Gustavo Echeverría ( [email protected] ), David
Crespo Arroyo ( [email protected] ) and Cristian Bermudez Serna ( [email protected] ) have offered
themselves as volunteers to translate the book into Spanish.
116
Appendix: Translations
I work as a software engineer in Argentina. I mainly use C# and .Net technologies at work, but strictly Python or Ruby in
my personal projects. I was introduced to Python many years ago and was immediately hooked. Not long after learning
Python I discovered this book and it helped me learn the language. Then I offered to translate the book into Spanish. Now,
after receiving some requests, I started translating "A Python Byte" with the help of Maximiliano Soler.
I am a Telecommunications Engineering student at the University of Antioquia (Colombia). Months ago, I started learning
Python and found this wonderful book, so I volunteered to get the Spanish translation.
Swedish
Mikael Jacobsson ( [email protected] ) has volunteered to translate the book into Swedish.
Turkish
Türker SEZER ( [email protected] ) and Bugra Cakir ( [email protected] ) have volunteered to translate the book into Turkish.
"Where is the Turkish version? Okusak Bitse".
117
Appendix: Translation
Procedures
Translation instructions
1. The full source for the book is available at https://github.com/swaroopch/byte-of-python .
2. Please fork the repository .
3. Next, browse to the repository on your computer. You need to know how to use Git to do that.
4. Read the Honkit Documentation , esp. the sales section .
5. Start editing the .Maryland files to translate to your local language.
6. See INSTALL.md on how to generate the website, PDF, EPUB.
118
Feedback
Feedback
The book needs the help of its readers, like you, to point out any part of the book that is not good, understandable, or just plain
wrong. Please write to the main author or the respective translators with your comments and suggestions.
119