Kickstart to Python 3 (Extract)

Page 1

books

Kickstart to Python 3 An Ultra-Rapid Programming Course

Ashwin Pajankar



Kickstart to Python 3 An Ultra-Rapid Programming Course

● Ashwin Panjakar


● This is an Elektor Publication. Elektor is the media brand of Elektor International Media B.V.

PO Box 11, NL-6114-ZG Susteren, The Netherlands Phone: +31 46 4389444

● All rights reserved. No part of this book may be reproduced in any material form, including photocopying, or

storing in any medium by electronic means and whether or not transiently or incidentally to some other use of this publication, without the written permission of the copyright holder except in accordance with the provisions of the Copyright Designs and Patents Act 1988 or under the terms of a licence issued by the Copyright Licencing Agency Ltd., 90 Tottenham Court Road, London, England W1P 9HE. Applications for the copyright holder's permission to reproduce any part of the publication should be addressed to the publishers.

● Declaration

The Author and Publisher have used their best efforts in ensuring the correctness of the information contained in this book. They do not assume, and hereby disclaim, any liability to any party for any loss or damage caused by errors or omissions in this book, whether such errors or omissions result from negligence, accident, or any other cause. All the programs given in the book are Copyright of the Author and Elektor International Media. These programs may only be used for educational purposes. Written permission from the Author or Elektor must be obtained before any of these programs can be used for commercial purposes.

● British Library Cataloguing in Publication Data

A catalogue record for this book is available from the British Library

● I SBN 978-3-89576-486-8 ISBN 978-3-89576-487-5

Print eBook

● © Copyright 2022: Elektor International Media B.V. Prepress Production: D-Vision, Julian van den Berg

Elektor is part of EIM, the world's leading source of essential technical information and electronics products for pro engineers, electronics designers, and the companies seeking to engage them. Each day, our international team develops and delivers high-quality content - via a variety of media channels (including magazines, video, digital media, and social media) in several languages - relating to electronics design and DIY electronics. www.elektormagazine.com

●4


Contents Chapter 1 • Introduction to Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 1.1 History of Python Programming Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 1.2 Installing Python on various platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.2.1 Installation on Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.2.2 Installation on Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.3 IDLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 1.4 Script Mode of Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 1.5 Python IDEs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 1.6 Python Implementations and Distributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 1.7 Python Package Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Chapter 2 • Built-in Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 2.1 IPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 2.2 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 2.3 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 2.4 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 2.5 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Chapter 3 • Strings, Functions, and Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 3.1 Strings in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 3.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 3.3 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 3.3.1 Indirect Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Chapter 4 • Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 4.1 Objects and Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 4.1.1 Everything is an Object in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 4.2 Getting Started with Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 4.2.1 Docstrings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 4.2.2 Adding attributes to a class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 4.2.3 Adding a method to the class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 4.2.4 Initializer method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

●5


Kickstart to Python 3 4.2.5 Multiline Docstrings in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 4.3 Modules and Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 4.3.1 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 4.3.2 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 4.4 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 4.4.1 Basic Inheritance in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 4.4.2 Method Overriding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 4.4.3 super() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 4.5 More Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 4.5.1 Multiple Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 4.5.2 Method Resolution order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 4.6 Abstract class and method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 4.7 Access Modifiers in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 4.8 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 4.8.1 Method Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 4.8.2 Operator Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 4.9 Syntax Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 4.10 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 4.10.1 Handling Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 4.10.2 Handling Exceptions by types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 4.10.3 else block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 4.10.4 Raising an Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 4.10.5 finally clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 4.10.6 User-Defined Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 Chapter 5 • Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 5.1 Introduction to Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 5.1.1 Jupyter Notebook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 5.2 Linked Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 5.2.1 Doubly Linked List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 5.3 Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 5.4 Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

●6


5.4.1 Double Ended Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 5.4.2 Circular Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 Chapter 6 • Turtle Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 6.1 History of Turtle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 6.2 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 6.3 Exploring Turtle methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 6.4 Recipes with Turtle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 6.5 Visualizing Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 6.6 Multiple Turtles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Chapter 7 • Programming animations and games . . . . . . . . . . . . . . . . . . . . . . . . 112 7.1 GettIng Started with Pygame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 7.2 Recursion with Pygame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 7.3 Sierpinski Triangle by Chaos Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 7.4 Simple animation with Pygame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 7.5 Snake Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 Chapter 8 • Working with files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 8.1 Handling plaintext file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 8.2 CSV Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 8.3 Handling Spreadsheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 Chapter 9 • Image Processing with Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 9.1 Digital Image Processing and Wand Library . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 9.2 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 9.3 Image Effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 9.4 Special Effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 9.5 Transformations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 9.6 Statistical Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 9.7 Color Enhancement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176

●7


Kickstart to Python 3 9.8 Image Quantization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 9.9 Threshold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 9.10 Distortions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 9.11 Affine Transformations and Projections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 9.11.1 Arc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 9.11.2 Barrel and Barrel Inverse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 9.11.3 Bilinear Transformation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 9.11.4 Cylinder and Planar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 9.11.5 Polar and Depolar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 9.11.6 Polynomial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 9.11.7 Shepards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 Chapter 10 • A few useful topics in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 10.1 Command Line Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 10.2 Worldcloud . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207

●8


Chapter 1 • Introduction to Python

Chapter 1 • Introduction to Python I hope that you have glanced through the table of contents of the book. If not, then I request you do as it will present a fair idea to the readers about the contents of this chapter. If you are not a total beginner to Python, you may find this chapter very basic. However, if you are new to Python or computer programming, you will find this chapter very useful. We will begin our journey with small and easy steps in this chapter. We will learn the following topics in this chapter: • • • • • • •

The history of Python Programming Language Installing Python on various platforms IDLE Script Mode of Python Python IDEs Python Implementations and Distributions Python Package Index

After this chapter, we will be comfortable with the basics of Python and running simple Python programs.

1.1 History of Python Programming Language Python is an interpreted, high-level, and general-purpose programming language. It was created with the intention of easily readable code. Python code can be characterised by English Language-like syntax. It is easy to read and comprehend for a person who has just started learning to program. It borrows a lot of features from other programming languages. Python programming language is heavily influenced by ABC which was developed at Centrum Wiskunde & Informatica (CWI). ABC itself influenced was heavily by SETL and ALGOL 68. The principal author of Python is Guido Von Rossum. He used to work with the ABC programming language at CWI. He was given the title of Benevolent Dictator for Life (BDFL) by the Python Community. The idea of Python programming language was conceived in the late 1980s as a successor to the ABC programming language. Guido also borrowed the system of modules from Modula-3. He started implementing the language in 1989. Version 0.9.0 was published at alt.sources in February 1991. Version 1.0 was published in 1994. Python 2.0 was released in October 2000. In December 2008, a new (and backward incompatible) version of the Python programming language, known as Python 3, was released. On January 1, 2020, Python 2 support ended and is no longer developed. Now the only version is Python 3. It is under active development and supported by the Python Software Foundation. We will be using Python 3 for all demonstrations in the book. Whenever I mention Python, I mean Python 3.

●9


Kickstart to Python 3

1.2 Installing Python on various platforms In this section, we will learn how to install Python 3 on Windows and Linux. Python supports a wide variety of operating systems. However, the most commonly used Operating systems for development with Python are Windows and Linux. I will therefore explain Python 3 with these two platforms.

1.2.1 Installation on Linux Almost all major distributions of Linux come with Python 2 and 3 installed. Python 2 interpreter is the binary executable python and Python 3 interpreter is the binary executable python3. I am using a Debian Linux variant Raspberry Pi OS with a Raspberry Pi 4 as my preferred Linux platform for Python development. Open the terminal emulator of your Linux distribution and run the following command: pi@raspberrypi:~ $ python3 -V

It will show the following output, Python 3.7.3

1.2.2 Installation on Windows It is very easy and straightforward to install Python on a Windows computer. We have to visit Python's homepage on the internet located at www.python.org. If we hover the mouse pointer over the Downloads section, the website automatically detects the Operating system and shows the appropriate download file. Click on the button saying Python 3.9.7. This version number will change in the future but the process is the same. Once you click on the button, it will download a windows executable setup file to your user's Downloads directory on your computer. It detects the architecture of your computer and downloads the relevant file. For instance, I have an x86 64-bit Windows computer. It downloaded the file python-3.9.7-amd64.exe. The screenshot of the www.python.org is shown in Figure 1-1 as follows:

● 10


Chapter 1 • Introduction to Python

Figure 1-1: Python Setup Download for Windows Now, open the setup file and it will launch an installation program. NOTE: You can open the file by clicking the downloaded file in your browser. You can also find the file's physical location by going through the downloads option in your browser. It will point to a location in the Downloads directory of your Windows user. The setup program window is shown in the screenshot in Figure 1-2 as follows:

Figure 1-2: Python Installation program Check all the checkboxes and click on the Customize installation option. It will open the next screen for the installation as shown in Figure 1-3 as follows:

● 11


Kickstart to Python 3

Figure 1-3: Options for the installation Click the Next button and it will take you to the screen shown in Figure 1-4:

Figure 1-4: Options for the installation Check all the options and click the Install button. It will then ask for administrator credentials. Enter the credentials and it will start installing Python and other relevant programs to your Windows computer. Once the installation completes, it shows the following screen (Figure 1-5):

● 12


Chapter 1 • Introduction to Python

Figure 1-5: Installation Success message Before we begin celebrating, we need to verify a few things. Open the command prompt of windows (cmd) and run the following command: C:\Users\Ashwin>python -V

The output is as follows, Python 3.9.7 Congratulations! We have installed Python 3 on your Windows computer.

1.3 IDLE Python Software Foundation has developed an integrated development environment (IDE) for Python. It is christened as 'IDLE' which stands for Integrated Development and Learning Environment. It comes with the Python setup when we install it on Windows. On Linux distributions, we have to install it separately. For Debian and derivatives, run the following command on the command prompt (Terminal emulator): pi@raspberrypi:~ $ sudo apt-get install idle -y

It will install IDLE on your Linux distribution. Let's work with IDLE. We can find it by typing IDLE in the Windows search bar. We can find it in the Linux Menu. In Linux, we can launch it from the command prompt by running the following command, pi@raspberrypi:~ $ idle &

● 13


Kickstart to Python 3

The IDLE window looks like this (Figure 1-6):

Figure 1-6: IDLE In the menubar, under the menu item Options, we can find the option Configure IDLE where we can set the font size and other details (Figure 1-7),

Figure 1-7: IDLE Configuration Options Change the font and size as per your choice and click the Apply and OK buttons respectively. Now, let's try to understand the interactive mode of Python. When invoked, the Windows IDLE shows interactive mode. We can use it to run Python statements directly without sav-

● 14


Chapter 1 • Introduction to Python

ing them as a file. The Python statements are fed directly to the interpreter and the output is immediately displayed in the same window. If you have ever worked with the command prompt of the OS then it is almost the same. Interactive mode is usually used to run single statements or short blocks of code. Let's try running a simple statement: >>> print("Hello World!")

This produces the following result and prints it in the same window: Hello World! The cursor returns to the prompt and is ready to fetch the new command by the user. This way we have run our first Python statement. We can exit the interpreter by running the command exit() in the interpreter. Alternatively, we can press CTRL + D to exit. We can also invoke the interactive mode from the command prompt by running the commands python on Windows and python3 on the Linux command prompt.

1.4 Script Mode of Python Python interactive mode is good for single-line statements and small blocks of code. However, it does not save the statements as programs. This can be done in scripting mode. In the Python interpreter of IDLE under the menu File in the menubar, choose New File. Type in the following code into this: print("Hello World!")

From the menu File in the menubar, choose Save. It will open the window Save As. Save it in the location of your choice. The IDLE automatically adds the *.py extension to the end of the filename. Then click menu Run from the menubar and click Run Module. This will execute the program and display the output in the IDLE's interactive mode window as shown below (Figure 1-8).

Figure 1-8: Python Script Output

● 15


Kickstart to Python 3

Another way to execute the program is to run it from the command prompt. To run the program in the command prompt, navigate to the directory where the program is stored and then run the following command in Windows: C:\ Python Book Project\Code\Chapter01>python prog01.py

This produces the following output: Hello World! In Linux, the command is as follows: pi@raspberrypi:~ $ python3 prog01.py

There is another way to run the program in Linux by running the following command: pi@raspberrypi:~ $ which python3

This returns the location of the Python 3 interpreter: /usr/bin/python3 Now let's add the following line of code to the Python code file we created: #!/usr/bin/python3

Thus the entire code file will look like below: #!/usr/bin/python3 print("Hello World!")

Now let's change the file permissions of the Python program file. Assuming that we saved the file with the name prog01.py, run the following command: pi@raspberrypi:~ $ chmod +x prog01.py

This way we have changed the permissions of the file and made it executable. We can run the file as follows: pi@raspberrypi:~ $ ./prog01.py

Note that we prefixed the filename with ./. This produces the following output: Hello World!

● 16


Chapter 1 • Introduction to Python

We added the first line so the operating system shell knows what interpreter to use to run the program. These are a few ways we can run Python programs.

1.5 Python IDEs Until now, we have used IDLE for Python programming. We can also use other editors and IDEs. On the Linux command line, we can use editor programs like vi, vim, and nano. The vi editor comes with most Linux distributions. We can install the other two on Debian (and derivative distributions) using the following command: pi@raspberrypi:~ $ sudo apt-get install vim nano -y

We can also use a plaintext editor like Notepad on Windows or Leafpad on Linux. We can install Leafpad editor on Debian and other distributions using the following command: pi@raspberrypi:~ $ sudo apt-get install leafpad -y

Raspberry Pi OS (my preferred Debian derivative) comes with the Thonny, Geany, and Mu IDEs. We can install them on other Debian derivatives with the following command: pi@raspberrypi:~ $ sudo apt-get install thonny geany mu-editor -y

If you are more comfortable with Eclipse, there is a nice plugin known as Pydev. This can be installed from the Eclipse Marketplace.

1.6 Python Implementations and Distributions The program that interprets and runs a Python program is known as a Python interpreter. The one that comes with Linux by default and is provided by Python Software Foundation is known as CPython. Other organizations have created Python interpreters that adhere to Python standards. These interpreters are known as Python implementations. Just as C and C++ have many compilers, Python has many implementations of interpreters. Throughout the book, we will use the standard CPython interpreter that comes with Linux by default. The following is the partial list of the other popular alternative implementations of the Python interpreter: 1. 2. 3. 4. 5.

IronPython Jython PyPy Stackless Python MicroPython

Many organizations bundle the Python interpreter of their choice with many modules and libraries and distribute it. These packages are known as Python distributions. We can get a list of Python implementations and distributions at the following URLs:

● 17


Kickstart to Python 3

https://www.python.org/download/alternatives/ https://wiki.python.org/moin/PythonDistributions https://wiki.python.org/moin/PythonImplementations

1.7 Python Package Index Python comes with a lot of libraries. This is known as the "Batteries included" philosophy of Python. Many more libraries are developed by many third-party developers and organizations. Based on your work profile, you may these libraries useful in carrying out intended tasks. All such third-party libraries are hosted at the Python Package Index. This is located at https://pypi.org/. We can search for the library on this page. Python comes with the utility known as pip. Pip is a reverse acronym. It means that the expansion of the term has the term itself. Pip means pip installs packages or pip installs python. It is a package management tool that installs Python packages, coming as a command-line utility. We can check its version by running the following command on the command prompt (cmd and terminal emulator) of the operating system: pi@raspberrypi:~ $ pip3 -V

It will print the currently installed version of pip. If we wish to see the list of currently installed packages we need to run the following command: pi@raspberrypi:~ $ pip3 list

It will return the list of all the packages already installed. NOTE: All pip-related commands are the same on Windows and Linux. If we wish to install a new library, we can search for it in PyPI. We can install a new package as follows: pi@raspberrypi:~ $ pip3 install numpy

This will install the NumPy library on the computer. We will use this utility throughout the book to install required third-party packages.

Summary In this chapter, we went through the history of the Python Programming language and its installation on Windows and Linux. We also saw how to use the Python interpreter and how to write and execute Python scripts in various ways. We had an overview of IDLE and also looked at various other IDEs for Python. Finally, we learned how to use pip, the package manager of Python. The next chapter will be much more hands-on. We will learn how to write programs with built-in data structures.

● 18


Chapter 2 • Built-in Data Structures

Chapter 2 • Built-in Data Structures In the previous chapter, we installed Python 3 on various platforms. We wrote a simple introductory program and learned how to run it in various ways. We also learned how to work with the interpreter (interactive) mode. This chapter was introductory and was not very heavy on programming. This chapter is a little bit more focused on programming (also known as coding). We will be introduced to various built-in data structures in Python. We will be focusing on the following topics in detail: • • • • •

IPython List Tuple Set Dictionary

Following this chapter, we will be comfortable with IPython and built-in data structures in Python.

2.1 IPython IPython means Interactive Python Shell. It is a program that provides us with more facilities than python's built-in interactive shell. We have to install it separately using the following command: pi@raspberrypi:~ $ pip3 install ipython

The command is the same for Windows and macOS. If you are installing it on a Linux distribution (like me), you may see the following message in the installation log: The scripts iptest, iptest3, ipython, and ipython3 are installed in '/ home/pi/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. This means we need to add the mentioned directory location to ~/.bashrc and ~/.bash_ profile files. We have to add the following line to both the files (so it works for login and non-login shells): PATH=$PATH:/home/pi/.local/bin

It will show a similar message for Windows too. We have to add the path of the directory mentioned in the installation log to the PATH variables (User and System variables, both) in Windows too.

● 19


Kickstart to Python 3

Once we change the path, we have to close and re-invoke the command line utilities of the operating systems. After this, run the following command: pi@raspberrypi:~$ ipython3

This will launch the IPython for Python 3 in the command prompt. The command is the same for Windows and other platforms. Figure 2-1 is the screenshot of an IPython session in progress on a Windows desktop computer:

Figure 2-1: IPython session in progress We can use IPython like this to write small programs. So, let's roll.

2.2 Lists We can store more than one value in lists. Lists are a built-in feature of Python. We do not have to install or import anything when using lists. List elements are enclosed in square brackets and separated by commas. But lists are in no way linear data structures as we can also have a list of lists. We will see more about the list of lists later when we are comfortable with the basics. Lists are mutable, meaning we can change them. Let us see a few examples of lists and associated built-in routines for the same. Open IPython on the command prompt of your operating system and follow the code: In [1]: fruits = ['babana', 'pineapple', 'orange']

This will create a list. Now, we can print it on the console in two ways: In [2]: fruits

This produces the following output: Out[2]: ['babana', 'pineapple', 'orange']

● 20


Chapter 2 • Built-in Data Structures

We can also use the built-in print function as follows: In [3]: print(fruits)

The following is the output: ['banana', 'pineapple', 'orange'] A list is an ordered data structure, meaning that the members of the lists are stored and retrieved in a particular order. We can use this to our advantage to retrieve the elements of the lists. The very first element has an index of 0. If the size of the list is n, the last element is indexed as n-1. This is similar to the indices of an array in C, C++, and Java. If you have programmed before with these programming languages, you will find this scheme of indexing familiar. We can retrieve the elements of the lists by using the combination of the name of the list and the index of the element. The following is an example: In [4]: fruits[0] Out[4]: 'banana' In [5]: fruits[1] Out[5]: 'pineapple' In [6]: fruits[2] Out[6]: 'orange'

We can also use negative indices. -1 refers to the last element and -2 refers to the last but one element. The following is the example: In [7]: fruits[-1] Out[7]: 'orange' In [8]: fruits[-2] Out[8]: 'pineapple'

If we try to use an invalid index, we see the following results: In [9]: fruits[3] --------------------------------------------------------------------------IndexError

Traceback (most recent call last)

<ipython-input-9-7ceeafd384d7> in <module> ----> 1 fruits[3] IndexError: list index out of range In [10]: fruits[-4] --------------------------------------------------------------------------IndexError

Traceback (most recent call last)

● 21


Kickstart to Python 3

<ipython-input-10-1cb2d66442ee> in <module> ----> 1 fruits[-4] IndexError: list index out of range

We can retrieve the length of the list as follows: In [12]: len(fruits) Out[12]: 3

We can also see the data type of the list as follows: In [13]: type(fruits) Out[13]: list In [14]: print(type(fruits)) <class 'list'>

As we can see in the output, the class of the variable is list. We will learn about this in detail in the fourth chapter of this book. We can use the constructor list() to create a list: In [15]: fruits = list(('banana', 'pineapple', 'orange')) In [16]: fruits Out[16]: ['banana', 'pineapple', 'orange']

We can retrieve the range of the elements from the lists follows: In [17]: SBC = ['Raspberry Pi', 'Orange Pi', 'Banana Pi', 'Banana Pro', 'NanoPi', 'Arduin ...: o Yun', 'Beaglebone'] In [18]: SBC[2:5] Out[18]: ['Banana Pi', 'Banana Pro', 'NanoPi']

In this example, we are retrieving the elements indexed with 2, 3, and 4. Also, consider the following example: In [19]: SBC[2:] Out[19]: ['Banana Pi', 'Banana Pro', 'NanoPi', 'Arduino Yun', 'Beaglebone']

This way we can retrieve the elements from index 2 and onwards. In [20]: SBC[:2] Out[20]: ['Raspberry Pi', 'Orange Pi']

● 22


Chapter 2 • Built-in Data Structures

And this way we can retrieve all elements before index 2. We can also use negative indices to retrieve multiple elements as follows: In [21]: SBC[-4:-1] Out[21]: ['Banana Pro', 'NanoPi', 'Arduino Yun']

We can also use the if construct to check if an element exists in the list as follows: In [23]: if 'Apple Pie' in SBC: ...:

print('Found')

...: else: ...:

print('Not Found')

...: Not Found

We can change an item in the list as follows: In [25]: SBC[0] = 'RPi 4B 8GB'

We can also insert an item into a list at an index as follows: In [36]: SBC.insert(2, 'Test Board')

The item at index 2 in this list is shifted one position forward. The same is true for the rest of the items. We can append an item to the list as follows, In [38]: SBC.append('Test Board 1')

This will add the item to the end of the list. We can also use extend operation with lists. This adds one list to the end of another list. In [39]: list1 = [1, 2, 3]; list2 = [4, 5, 6]; In [40]: list1.extend(list2) In [41]: list1 Out[41]: [1, 2, 3, 4, 5, 6]

We can remove an item from the list as follows: In [43]: SBC.remove('Test Board')

● 23


Kickstart to Python 3

We can use two different approaches to remove the item at a specified index. Both the approaches are demonstrated below: In [44]: SBC.pop(0) Out[44]: 'RPi 4B 8GB' In [46]: del SBC[0]

If we specify no index, it will pop (meaning remove and return) the last item: In [47]: SBC.pop() Out[47]: 'Test Board 1'

We can remove all elements from the list as follows: In [48]: SBC.clear()

We can also delete an entire list as follows, In [49]: del SBC

If we try to access the list now, it will return an error as follows: In [50]: SBC --------------------------------------------------------------------------NameError

Traceback (most recent call last)

<ipython-input-50-69ed78d7b4fc> in <module> ----> 1 SBC NameError: name 'SBC' is not defined

We will now understand how to use the lists with loops. Create a list as follows: In [51]: fruits = ['apple', 'banana', 'cherry', 'pineapple', 'watermelon', 'papaya']

We can use the for loop construct as follows, In [52]: for member in fruits: ...: ...: apple banana cherry pineapple watermelon papaya

● 24

print(member)


Chapter 2 • Built-in Data Structures

The following code also produces the same result: In [53]: for i in range(len(fruits)): ...:

print(fruits[i])

...: apple banana cherry pineapple watermelon papaya

We can also use the while loop as follows: In [54]: i = 0 In [55]: while i < len(fruits): ...:

print(fruits[i])

...:

i = i + 1

...: apple banana cherry pineapple watermelon papaya

Before proceeding further, I want to cover an important feature. We have worked with examples of many lists. Most of the lists we worked with are lists of character strings. A couple are lists of numbers. We can also have lists of other data types. The following are examples: In [56]: l1 = [1.2, 2.3, 3.4] In [57]: l2 = ['a', 'b', 'c'] In [58]: l3 = [True, False, False, True, True, False]

Here we created lists of floats, characters, and Boolean values respectively. We can also create a list of mixed types as follows: In [59]: l4 = [1, 'Test', 'a', 1.2, True, False]

● 25


Kickstart to Python 3

We can sort a list as follows: In [60]: fruits.sort() In [61]: fruits Out[61]: ['apple', 'banana', 'cherry', 'papaya', 'pineapple', 'watermelon']

We can also sort a list in reverse order as follows: In [62]: fruits.sort(reverse = True) In [63]: fruits Out[63]: ['watermelon', 'pineapple', 'papaya', 'cherry', 'banana', 'apple']

As an exercise, sort numeric and boolean lists. We can copy a list into another as follows: In [64]: newlist = fruits.copy()

We saw earlier that the routine extend() can join two lists. We can use the addition (+) operator to join two lists as follows: In [65]: l1 + l2 Out[65]: [1.2, 2.3, 3.4, 'a', 'b', 'c']

We can use the multiplication operator with lists as follows, In [66]: l1 * 3 Out[66]: [1.2, 2.3, 3.4, 1.2, 2.3, 3.4, 1.2, 2.3, 3.4]

2.3 Tuples Tuples are similar to lists. We have to use brackets while creating them. Their difference with lists is that they are immutable, meaning once they are created, they cannot be modified. Let's see a simple example as follows, In [1]: fruits = ('apple', 'grape', 'mango') In [2]: fruits Out[2]: ('apple', 'grape', 'mango') In [3]: print(type(fruits)) <class 'tuple'>

The indexing, looping, and concatenation (the + operator) for tuples are the same as lists. As tuples are immutable, we cannot directly change any information stored in the tuples. However, we can convert them to lists and then assign the changed list to any tuple. See the following example:

● 26


Chapter 2 • Built-in Data Structures

In [4]: temp_list = list(fruits) In [5]: temp_list.append('papaya') In [6]: fruits = tuple(temp_list) In [7]: fruits Out[7]: ('apple', 'grape', 'mango', 'papaya')

In the example above, we demonstrated the usage of the routine tuple(). This way, we can use all the routines of lists cleverly to work with tuples. Let's see the demonstration of the method count() to count how many times a particular member element occurs in the tuple: In [8]: test_tuple = (2, 3, 1, 3, 1, 4, 5, 6, 3, 6) In [9]: x = test_tuple.count(3) In [10]: print(x) 3

2.4 Sets Lists and tuples are ordered data structures and both allow duplicate values. Sets are different than both as they are unordered and hence do not allow duplicate values. Sets are defined using curly brackets. The following is an example of simple sets: In [12]: set1 = {'apple', 'banana', 'orange'} In [13]: set1 Out[13]: {'apple', 'banana', 'orange'} In [14]: set2 = set(('apple', 'banana', 'orange')) In [15]: set2 Out[15]: {'apple', 'banana', 'orange'} In [16]: print(type(set1)) <class 'set'>

We cannot use indexes to retrieve the elements of any set, as sets are unordered. But we can use loop constructs for and while. Try this as an exercise. We can add new items with the routine add() as follows: In [17]: set1 Out[17]: {'apple', 'banana', 'orange'} In [18]: set1.add('pineapple') In [19]: set1 Out[19]: {'apple', 'banana', 'orange', 'pineapple'}

● 27


Kickstart to Python 3

We can use the routines remove() or discard() to remove an item from any list as follows: In [20]: set1.remove('banana') In [21]: set1.discard('apple')

Both the routines raise errors if we try to remove non-existent items. Let's see a few set methods. First, we will see how to compute the union of two sets. Let's create sets for this: In [22]: set1 = {1, 2, 3, 4, 5} In [23]: set2 = {3, 4, 5, 6, 7} In [24]: set3 = set1.union(set2) In [25]: set3 Out[25]: {1, 2, 3, 4, 5, 6, 7}

Here, we store the union in a new set. A slight alternate approach stores the union in the first set as follows, In [29]: set1.update(set2) In [30]: set1 Out[30]: {1, 2, 3, 4, 5, 6, 7}

We can also remove all elements in a set as follows: In [31]: set3.clear()

The routine copy() works in the similar way to list. Let's compute the difference as follows: In [32]: set3 = set1.difference(set2) In [33]: set3 Out[33]: {1, 2}

This example returns a new output set. We can remove the matching elements from one of the sets using this: In [34]: set1.difference_update(set2) In [35]: set1 Out[35]: {1, 2}

We can compute intersection as follows: In [37]: set3 = set1.intersection(set2) In [38]: set3 Out[38]: {3, 4, 5}

● 28


Chapter 2 • Built-in Data Structures

We can check if a set is a subset of another set as follows: In [39]: set2 = {1, 2, 3, 4, 5, 6, 7, 8} In [40]: set1.issubset(set2) Out[40]: True

Similarly, we can check if a set is a superset of another set: In [41]: set2.issuperset(set1) Out[41]: True

We can also check if two sets are disjoint (do not have any common elements) as follows: In [42]: set1 = {1, 2, 3} In [43]: set2 = {4, 5, 6} In [44]: set1.isdisjoint(set2) Out[44]: True

We can compute the symmetric difference between two sets as follows: In [45]: set1 = {1, 2, 3} In [46]: set2 = {2, 3, 4} In [47]: set3 = set1.symmetric_difference(set2) In [48]: set3 Out[48]: {1, 4}

We can also compute union and intersection with operators | and s as follows: In [49]: set1 | set2 Out[49]: {1, 2, 3, 4} In [50]: set1 & set2 Out[50]: {2, 3}

2.5 Dictionaries Dictionaries are ordered, changeable, and do not allow duplicates. Dictionaries in Python 3.6 are unordered. Dictionaries from Python 3.7 are ordered. The items are stored in dictionary in key:value pairs and can be referred to by using the name of the key. Let's create a simple dictionary as follows: In [52]: test_dict = { "fruit": "mango", "colors": ["red", "green", "yellow"]}

We can access the items of the dictionary using the keys as follows: In [53]: test_dict["fruit"] Out[53]: 'mango'

● 29


Kickstart to Python 3

In [54]: test_dict["colors"] Out[54]: ['red', 'green', 'yellow']

We can retrieve keys and values as follows: In [55]: test_dict.keys() Out[55]: dict_keys(['fruit', 'colors']) In [56]: test_dict.values() Out[56]: dict_values(['mango', ['red', 'green', 'yellow']])

We can update a value as follows: In [60]: test_dict.update({"fruit": "grapes"}) In [61]: test_dict Out[61]: {'fruit': 'grapes', 'colors': ['red', 'green', 'yellow']}

We can add into the dictionary as follows: In [62]: test_dict["taste"] = ["sweet", "sour"] In [63]: test_dict Out[63]: {'fruit': 'grapes', 'colors': ['red', 'green', 'yellow'], 'taste': ['sweet', 'sour']}

We can also pop items: In [64]: test_dict.pop("colors") Out[64]: ['red', 'green', 'yellow'] In [65]: test_dict Out[65]: {'fruit': 'grapes', 'taste': ['sweet', 'sour']}

We can also pop the last inserted item: In [66]: test_dict.popitem() Out[66]: ('taste', ['sweet', 'sour'])

We can also delete an item, In [67]: del test_dict["fruit"] In [68]: test_dict Out[68]: {}

● 30


Chapter 2 • Built-in Data Structures

We can also delete a dictionary as follows: In [69]: del test_dict In [70]: test_dict --------------------------------------------------------------------------NameError

Traceback (most recent call last)

<ipython-input-70-6651ddf27d40> in <module> ----> 1 test_dict NameError: name 'test_dict' is not defined

We can loop through dictionaries using for and while loop constructs. Try doing this as an exercise.

Summary In this chapter, we learned the basics of sets, tuples, lists, and dictionaries in Python. Together, these are known as collections in Python. In the next chapter, we will learn the basics of strings, functions, and recursion.

● 31


Index

Index @abstractmethod

58

Flip Effect Floral pattern Floyd Steinberg method fps (frame per second) Fractal

170 98 181 125 108

G Gaussian noise Geany get_rect() GNU Octave

160 17 122 149

H Hexagonal spiral H-Fractal

104 108

I IDLE ImageMagick Inheritance IPython issubclass()

13 150 51 19 52

K key:value Koch Snowflake

29 107

80 10 183

A Affine Transformation Animation Animations Append mode Arc Argument

191 121 112 142 192 37

B Barrel Barrel Inverse Basic Inheritance blit() Bouncing ball Chaos Game Character Circular buffer Classes CMYK images CPython CSV Files Customize installation Cylinder

193 193 52 122 124 120 34 84 44 162 17 143 11 195

D Data Structures Debian Deque Digital Image Processing Dithering draw.line() Drawing circles

69 13 78 149 185 116 95

L LIFO Linux Local Adaptive Threshold M Modularity Multiline Docstrings

47 46

E Eclipse Marketplace Edge Detection Exceptions exit()

17 157 62 15

N Nano Notepad

17 17

F False Fibonacci Trees

33 104

O Object-Oriented OOP open()

42 42 139

● 207


Kickstart to Python 3

openpyxl Ordered data structure

145 21

P Pip Planar Polymorphism Polynomial Pop print() Pygame Pygame library Python Documentation Strings Python IDE Python interpreter Python Package Index Python Setup Python Software Foundation Raspberry Pi OS

18 195 59 197 77 32 112 121 44 17 15 18 11 9 10

R Recursion remove() Root Mean Square Rotational blur Running

29 28 175 155 70

S Sierpinski Triangle Smoothing filter Snake speed() Spreadsheets Stack statistic() Strings super() Syntax Errors

120 158 130 97 145 77 171 32 54 62

T Thonny Threshold Tkinter Tuples Turtle TypeError

17 182 90 26 90 64

● 208

W Wand Wand Library Wave Effect Worldcloud WSAD keys

149 149 168 200 130

Z Zigzag function

102


books books

Kickstart to Python 3 An Ultra-Rapid Programming Course This book serves as the very first step to for novices to learn Python programming. The book is divided into ten chapters. In the first chapter, readers are introduced to the basics of Python. It has the detailed instructions for installation on various platforms such as macOS, Windows, FreeBSD, and Linux. It also covers the other aspects of Python programming such as IDEs and Package Manager. The second chapter is where the readers get an opportunity to have a detailed hands-on with Python programming. It covers a group of built-in data structures popularly known as Python Collections. The third chapter covers the important concepts of strings, functions, and recursion. The fourth chapter focuses on the Object-Oriented Programming with Python. The fifth chapter discusses most commonly used custom data structures such as stack and queue. The sixth chapter spurs the creativity of the readers with Python’s Turtle graphics library. The seventh chapter explores animations and game development using the Pygame library. The eighth chapter covers handling data stored in a variety of file formats. The ninth chapter covers the area of Image processing with Wand library in Python. The tenth and the final chapter presents an array of assorted handy topics in Python.

Ashwin Pajankar holds a Master of Technology degree from IIIT Hyderabad, and has over 25 years of programming experience. He started his journey into programming and electronics with the BASIC programming language and is now proficient in assemblylanguage programming, C, C++, Java, Shell Scripting, and Python. Further technical experience includes single-board computers such as the Raspberry Pi, Banana Pro, and Arduino.

The entire book follows a step-by-step approach. The explanation of the topic is always followed by a detailed code example. The code examples are also explained in suitable detail and they are followed by the output in the form of text or screenshot wherever possible. Readers will become comfortable with Python programming language by closely following the concepts and the code examples in this book. The book also has references to external resources for readers to explore further. A download of the software code, and links to tutorial videos can be found on the Elektor website.

Elektor International Media BV www.elektor.com


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.