0% found this document useful (0 votes)
123 views

Future - Python The Complete Manual - 16th Edition 2023

Uploaded by

Eric Kwong
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
123 views

Future - Python The Complete Manual - 16th Edition 2023

Uploaded by

Eric Kwong
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 134
Python The Complete Manual The essential handbook for Python users MARA AD hi hR Rae PARADA OD AAAAAAAAAMAA A A AAAAMAAAAAAAAA A AAAAAMAAAMAAA A AAAAAMAAAMAAA A he AAAAAMAAAAAAA A AAAAAAALAAAAA 4 db AAAAAMAAAAAAAA A AAAAAAA A 4 AAAAMAAAA A AAAAMAA A he er 4AAA 4A 4AMAA 4A AAhA sa AAA A AAAAdAhd badd dd Welcome to Python The Complete Manual Python is a versatile language and its rise in popularity is certainly no surprise Its similarity to everyday language has made ita perfect companion for the Raspberry Pi, which is often a first step into practical programming. But don't be fooled by its beginner-riendly credentials - Python has plenty of more advanced functions. In this new edition, you wil earn how to program in Python, discover amazing projects to improve your understanding, and find ways to Use Python to enhance your experience of computing, Youll also create fun projects including programming a Space Invaders clone and teaching your Raspberry Pi to multi-task. Let's get coding! Python The Complete Manual Future PLE Quay House, The Ambury ath, BAL ILA, Eaitorat Compiles by Aiden Dalby & Adam Markiewicz ead of Arta Design Greg Whitaker Esitrial rectordon Whit Managing Drector Grainne MeKenna Photography ‘All copyrights and trademarsaare recognised and respacteck Advertising edt packs are avalableon request ‘Commercial Director Clare Dove Intemational Head of Pint Licensing Rachel Shaw Teensingeafuturenetcom Circulation ood of Nevstrade Tm Mathers Production Hood of Production Mark Constance Preducton Project Manager Matthew Eglinton Aasertsing Production Manager Joanne Crosby Digital Editions Controller Jason Hudson Prosuction Managers Keely Miler, Nola Cokely, ‘Vivienne Calvert, Fran Twentyman Distributed by Marketer, Church Place Canary Wharf Landon, EU SHU ‘ewvimarketorcecouk Tet C203 787 9001 Python The Complete Manual Fifteenth Edtion (CMBS6SS) FUTURE Connectors Wide foe e 26 Make web apps Master this starter project Build an app for Android Take your appson the move 50 Python tips Aselection of handy tips Work with Python 50 58 64 72 Replace your shell Say goodbye to Bash Scientific computing Discover NumPy’s power Python for system admins How to tweak your settings Scrape Wikipedia Start using Beautiful Soup Create with Python 80 Tictactoewith Kivy Programa simple game 86 MakeaPongclone Enhance your game skills aa | 88 Programa Space Invaders clone Have fun with Pivaders 94 Space Invaders clone 2 Continue making Pivaders Get started with On 8 Masterdass Discover the basics of Python Use Python with Pi 100 106 no 14 120 Using Python on Pi Optimise your code Use Python in Minecraft Produce fantastic creations Handle multiple task Learn to multi-task with your Raspberry Pi Create a Pi-powered virtual reality setup Use Python-VRZero Find and check your phone Discover andlog Bluetooth devices Python is a great programming language for both beginners and experts. It is designed with code readability in mind, making it an excellent choice for beginners who are still getting used to various programming concepts. The language is popular and has plenty of libraries available, allowing programmers to get a lot done with relatively little code. You can make all Kinds of applications in Python: you could use the Pygame frarnework to write simple 2D games, you could use the GTK libraries to create a windowed application, or you could try something a little ore ambitious lke an app such as creating one using Python's ; Bluetooth and Input libraries to capture the input from a USB keyboard and ~ relay the input events to an Android phone. A For this tutorial we're going to be using Python 2 since that is the A version that is most likely to be installed on your Linux distribution, 4 Inthe following tutorials, you'l leam how to create popular games using @ { te SN Pythi Well also sh how to add sound and Alt. a oN ees fell also show you how to add sound and Al to o¢9 Se I ma og, Get started with Python Getting started Hello World Let's get stuck in, and what better way than with the programmer's bestfriend, the Hello World’ application! Start by opening a terminal. its current working directory will be your home directory. I's probably a good idea to make a directory for the files that well be creating in this tutorial, rather than having then loose in your home directory. You can create a directory called Python using the command mkdir Python, Youtl then want to change into that directory using the command cd Python, The next step isto create an empty file using the command ‘touch’ followed by the filename. Our expert used the command touch hello_world py. The final and most important part of setting up the files making it executable. This allows us to run code inside the hello_ world,py fle. We do this with the command chmod +x hello_world py. Now that we have our file set up, we can go ahead and open it up in nano, or alternatively any text editor of your choice. Geciit is a great editor with syntax highlighting support that should be available on any distribution. Youll be able to install it using your package manager if you don't have it already, I Ciianetian-taptop ~18 mkdir Python [liam@liam-laptop ~]$ cd Python/ I Cliam@liam-laptop Python]$ touch hello_world.py [Liam@liam-laptop PythoniJ$ chmod +x hello_world.py I Criametiam-taptop Pythons nano hello_world.py ur Hello World program is very simple, it only needs two lines, The fist line begins with a‘shebang’ (the symbol #! ~ also known Get started with Python Getting started as a hashbang) followed by the path to the Python interpreter. The program loader uses this line to work out what the rest of the lines need to be interpreted with. If youre running this in an IDE like IDLE, you don't necessarily need to do this. “The code that is actually read by the Python interpreters only a single line. Were passing the value Hello World to the print function by placing it in brackets immediately after we've called the print function. Hello World is enclosed in quotation marks to indicate that it is a literal value and should not be interpreted as source code. As we would expect, the print function in Python prints any value that gets passed toit from the console. You can save the changes you've just made to the file in nano using the key combination Ctrl+O, followed by Enter. Use Ctr}+X to exit nano. H usr/bin/env python2 H printcHelto World”) You can run the Hello World program by prefixing its filename with / —in this case youd type: Shello_world py I Cliam@liam-laptop Python]$ ./hello_world.py B tetto World Variables and data types A variable s @ name in source code that is associated with an area in memory that you can use to store data, which isthen called upon throughout the code. The data can be one of many types, including: Ter Cesc Float Rees eer eed Corse ey Sc aS cl Wo Br) ‘A variable is associated with an area in memory that you can use to store data” Getting started Get started with Python ‘As well as these main data types, there are sequence types (technically, asstring isa sequence type but is so commonly used we've classed it asa main data type) ited Ceres cubeeicce en Pen eee cen es Cece cis ees tuple would be used for something like a co-ordinate, containing an xand y value stored as a single variable, whereas a list is typicelly used to store larger collections, The data stored in a tuple is immutable because you aren't able to change values of individual elements in a tuple. However, you can do so ina list. It will also be useful to know about Python’ dictionary type. A dictionary is a mapped data type. It stores data in key-value pairs. This means that you access values stored in the dictionary using that value's corresponding key, which i cfferent to how you would do it with alist. In a list, you would access an element of the ist using that element's index (a number representing where the element s placed in the list). Let’s work on a program we can use to demonstrate how to use variables and different data types. I's worth noting at this point that you don't always have to specify data types in Python, Feel free to create this file in any editor you like. Everything will work just fine as long as you remember to make the file executable. Were going to call cours variables py. Interpreted vs compiled languages ted to machine oRtaaan: Te) aero cl Full code listing The following line creates an integer variable called hello_int with the # value of 21, Notice how itdoesn't need to goin uotatton marks The same principals true of Boolean values We create a tuple in the following way And alistin this way You could also create the same lstin the following way Get started with Python Getting started #V/usr/bin/env python2 4#We create a variable by writing the name of the variable we want followed# by an equals sign, which is followed by the value we want to store in thee variable. For example, the following line creates a variable called hello_str, containing the string Hello World, hello_str = “Hello World” hello_int = 21 hello_bool = True hello_tuple = (21, 32) hello_list = [“Hello,”, “this”, “is”, “a”, List") 4 This list now contains 5 strings. Notice that there are no spaces# between these strings so if you were to join them up so make a sentence # you'd have to add a space between each element. hello_list = list. hello_list.append(“Hello,”) hello_list.append(“this") hello_list.append(“is") hello_list.append(“a") hello_list.append("list”) ww r ) following lines use the appendt function ofthe ist type toad elements tothe list This way of using af list sit really very useful when working with stings you know ofin advance, butit canbe useful when working with dynamic data such as user input. Thislist, will overwrite the firstlist without any waning ¢ Getting started Get started with Python We might as well as wet are using the same variable name as the create dictionary previous lst while we're at it Notice how weve hello_dict = { “first_name” : “Liam”, aligned the colons “last_name” below to make the “Fraser”, code tidy “eye_colour” : “Blue” } # Let's access some elements inside our collectionst Well start by changing the value of the last string in our hello_list and# add an. exclamation mark to the end. The"list’string is the Sth element # in the list. However, indexes in Python are zero-based, which means the # first element has an index of 0 Notice that there - print(hello_list(4]) pes nae cee hello_list{4] += * exclamation marks ee ¥ The above line is the same as print the element hello_list[4] = hello_list[4] + “!” print(hello_list[4]) Remember = that tuples are print(strhello_tuplefa)) immutable, — We can't change the value of those elements although we Uke we just did with the list can access the # Notice the use of the str function above to elements of them explicitly convert the integer tke so # value inside the tuple toa string before printing it Let's create a sentence using - the data in our __| print(hello_dict["first_name"] +""+ hello_ hello_dict dict(“last_name"] +"has" + hello_dictl"eye_colour’} +" eyes”) Amuch tidier way Cf doing this would = Betouse Pythons print(“(0}{1}has {2} eyes“formatthello_ sting formatter [| dictt’first_name"], hello_dict("last_name"), hello_dict{*eye_colour'))) Get started with Python Getting started Indentation in detail tation SCCM ec eae ir ae Tener ne editor Control structures In programming, a control structure is any kind of statement that can change the path that the code execution takes. For example, a control structure that decided to end the program if a number was less than 5 would look something like this: #1/usr/bin/env python2 import sys # Used for the sys.exit function int_condition = 5 if int_condition < 6: sys.exit(“int_condition must be >= 6") else: print(“int_condition was >= 6 - continuing”) The path that the cade takes will depend on the value of the integer int_condition. The code in the ‘i’ block will only be executed if the condition is true. The import statement is used to load the Python system library; the latter provides the exit function, allowing you to exit the program, printing an error message. Notice that indentation (in this case four spaces per indent) is used to indicate Sea which statement a block of code belongs to. 'f' statements are probably the most commonly used control structures. Other control “The path the code takes will depend on the value of the integer int_condition’ Getting started Get started with Python structures include: the following items, which you should be aware of when using Python: For statements, which allow you to iterate over items in collections, or to repeat a piece of code again a certain number of times; = While statements, a loop that continues while the condition istrue. Wete going to write a program that accepts user input from the ser to demonstrate haw control structures work Wete calling tt constructpy. The for loop is using a local copy of the current value, which means any changes inside the loop won't make any changes affecting the list. On the other hand however, the ‘while’ loop is directly accessing elements in the list, so you could change the list there should you want to do so. We wil talk about variable scope in some more detail later on in the article. The output from the above program is as follows: [liamélian-Laptop Python]$ ./ construct.py How many integers? acd You must enter an integer (liamélian-Laptop Python]$ ./ construct.py How many integers? 3 Please enter integer 1: t You must enter an integer Please enter integer 1: 5 Please enter integer 2: 2 Please enter integer 3: 6 Using a for loop 5 2 6 Using a while loop 5 2 6 “The ‘for’ loop uses a local copy, so changes in the loop won't affect the list” Get started with Python Getting started Full code listing ‘#1/ust/bin/env python # We're going to write a program that will ask the user to input an arbitrary # number of integers, store them ina collection, {and then demonstrate how the Henne # collection would be used with various control integers we want in thelist structures. import sys # Used for the sys.exit function target_int = raw_input(“How many integers? “) By now, the variable target_int contains a string representation of ‘# whatever the user typed. We need to try and convert that to an integer but 4 be ready to # deal with the error ifit’s not Otherwise the program will crash, try: lee io ste te) target_int = int(target_int) integers except Valuefrror: sys.exit(“You must enter an integer”) ints = listo) Ce. These are used L to keep track ofhow many L count =? oe. integers we curently have Getting started Get started with Python ifthe above succeeds then isint will be set to true:isint True By now, the user has given up or we have alistfiled with integers. We can loop through these ina couple of ways. The fist iswith a forloop # Keep asking for an integer until we have the required number while count < target_int: new_int raw_input(“Please enter integer {0}: “.format(count + 1)) isint = False try —f new.int = int(new.int) except print(“You must enter an integer") # Only carry on if we have an integer. IF not, welllloop again # Notice below | use ==, which is different from =. The single equals isan # assignment operator whereas the double equals is a comparison operator. if isint == True: 4# Add the integer to the collection ints.append(new_int) # Increment the count by 1 count #= 1 print(“Using a for loop") for value in ints: print(str(value)) # Orwith a while loop: print(“Using a while loop”) # We already have the total above, but knowing Get started with Python Getting started the len function is very # useful total = len(ints) count = @ while count < total: print(str(intsfcount])) count += 1 More about a Python list Functions and variable scope Functions are used in programming to break processes down into smaller chunks. This often makes code much easier to read. Functions can also be reusable if designed in a certain way. Functions can have variables passed to them. Variables in Python are always passed by value, which means that a copy of the variable is passed to the function that is only valid in the scope of the function. Any changes made to the original variable inside the function will be discarded. However, functions can also return values, so this isn't an issue. Functions are defined with the keyword def, followed by the name of the function. Any variables that can be passed through are put in brackets following the function's name, Multiple variables are separated by commas. The names given to the variables in these brackets are the ones that they will have in the scope of the function, regardless of what the variable that's passed to the function is called. Let's see this in action. The output from the program opposite is as follows: “Functions are defined with the keyword def, then the name of the function” Getting started Get started with Python We are now outside of the scope of the modify_string function, as we have reduced the level of indentation ———— 7 The test string won't be changed in this code However, we ccan call the function lke this #l/ust/bin/env python? # Below is a function called modify_string, which accepts a variable # that willbe called original in the scope of the function. Anything # indented with 4 spaces Under the function definition isin the # scope. def modify_string(original): original += “ that has been modified.” # At the moment, only the local copy of this string has been modified def modify_string_return(original): original += “ that has been modified.” # However, we can return our local copy to the caller. The function ends as soon as the return statement is used, regardless of where it # is in the function, return original test_string = “This is a test string” modify_string(test_string) print(test_string) test_string = modify_string_ return(test_string) print(test_string) # The function’s return value is stored in the variable test string, # overwriting the original and therefore changing the value that i # printed, lliam@liam-laptop Python|$ /functions_and. scope.py This isa test string Thisis a test string that has been modified, Scope is an important thing to get the hang of otherwise it can get you into some bad habits. Let's write a quick program to demonstrate this. t's going to have a Boolean variable called cont, which will decide ifa number will be assigned to a variable in an if statement. However, the variable hasn't been defined anywhere apart from in the scope ofthe if statement. Well finish off by trying to print the variable. Get started with Python Getting started ‘#Y/ust/bin/env python2 cont = False ifcont var = 1234 printivar) In the section of code above, Python will convert the integer toa string before printing it. However, it's always a good idea to expicitly convert things to strings — especially when it comes to concatenating strings together. you try to use the + operator on a string and an integer, there wil be an error because it's not explicitly clear what needs to happen. The + operator would usually add two integers together. Having said that, Python’ string formatter that we demonstrated earlier is a cleaner way of doing that. Can you see the problem? Var has only been defined in the scope of the ifstatement. This means that we geta very nasty error when we try to access var. {liameliam-laptop Python|s /scope-py Traceback (most recent call last) File*/scope.py' line 8, in print var Namefrror:name’var'is not defined fF cont is set to True, then the variable will be created and we can access itjust fine. However, ths is a bad way to do things. The correct way is to initialize the variable outside of the scope of the if statement. syusrbinlenv python2 a cont = False if cont y 2 var= 1234 ifvar =o: printivar) Getting started Seis Get started with Python The variable var is defined in a wider scope than the ifstatement, and can still be accessed by the ifstatement. Any changes made to var inside the ifstaternent are changing the variable defined in the larger scope. This example doesnt realy do anything useful apart from illustrate the potential problem, but the worst-case scenario has gone from the program crashing to printing a zero. Even that doesn't happen because we've added an extra construct to test the value of var before printing it. “Google, or any other search engine, is very helpful if you are stuck with anything, or have an error message you can't work out how to fix" eee Bee ieee eee nana a Get started with Python Getting started Coding style Its worth taking a littl time to talk about coding style. It’s simple to write tidy code, The key is consistency. For example, you should always name your variables in the same manner. It doesn't matter if you want to use camelCase or use underscores as we have. One crucial thing is to use self-documenting identifiers for variables. You shouldn't have to guess what.a variable does. The other thing that goes with this isto always comment your code. This will help anyone else who reads your code, and yourselfin the future. It’s also useful to put a brief summary at the top of a code file describing what the application does, or a part of the application ifit's made up of multiple files. Summary This article should have introduced you to the basics of programming in Python. Hopefully you are getting used to the syntax, indentation and general look and feel of a Python program. The next step is to lea how to come up with a problem that you want to solve, and break it down into small steps that you can implement in a programming language. Google, or any other search engine, is very helpful. If you are stuck with anything, or have an error message you can’t work out how to fix, stick it into Google and you should be a lot closer to solving your problem. For example, if we Google ‘play mp3 file with python, the first link takes us to a Stack Overflow thread with a bunch of useful replies. Don't be afraid to get stuck in - the real fun of programming is solving problems one manageable chunk at a time. Introducing Python — Pythonessentials Lay the foundations and build your knowledge NSM Cuno t lpi pon era edsse Mn Rur a aie syoke see) irises) Mee nenge lee iNee ie o sigu ils ge) systems (p.32) and the worldwide web (p.26). These easy 10- follow tutorials will help you to cement the Python language that you've learned, while developing a skill that is very helpful in the current technology market. Welllfinish up by giving you 50 essential Python tips (p.40) to increase your knowledge and Ta Python essentials Introducing Python What you'll need... Python 2.7: itpsiiwwrpytbonrgitownload/ releoses27 Django version 1.4: tps eran dangopeojectcon Make web apps with Python Make web apps with Python Python provides quick and easy way to build oplications, including web apps. Find out how to it to builc ‘ure-complete web app Python is known for its simplicity and capabilities. At this point it is so advanced that there is nothing you cannot do with Python, and conqueting the web is one of the possibilities. When you are using Python for web development you get access to a huge catalogue of modules and community support ~ make the most of them. Web development in Python can be done in many different ways, right from using the plain old CGI modules to utilising fully groomed web frameworks, Using the latter is the most popular method of building web applications with Python, since it allows you to build applications without worrying about al that low-level implementation stuff. There are many web frameworks available for Python, such as Django, TurboGears and Web2Py, For this tutorial we will be using our current preferred option, Django. The Django Project portable and can be integrated with ‘nei ther Django sites with very tte effort. magazine issue tracker H's django adnin.py startproject ludissueTracker OT me seseeiringyfictues | Arie cectoy wl rested tocteatenew Djangoproects. _Thiswill also act as the oot of your Let's create one forourissuetracker —_—_ development web server that comes project here with Django. Under the project in Django, a projectrepresentsthe directory you wilfin the folowing site andits settings. An application,on items. theother hand, represents aspectic -_- manage.py:ython script to work with feature ofthe site ike blogging or your project tagging, The benefit ofthis approach is__ludlssueTracker: A python package thatyour Django application becomes @directory with _init__py le) for Make web apps with Python your project. This package isthe one Containing your project’ settings and configuration data ludissueTracker/settings py: Thisfile contains the configuration options for the project. ludissueTracker/urs py: Ths ile contains various URL mappings. wsgippy: An entry-point for WSG- compatible web servers to serve your project. Only useful when you are deploying your project. For this tutorial we wont be needing it, Configuring the Django project 0 Before we start working Con the application, let's configure the Django project, as per our requirements EditludlssueTrackersettings py as follows (only pars requiring modification are shown: Database Settings: We willbe Using SOLite3 as our database system here NOTE: Red text indicates new code or Updated code. ‘default’: { I “ENGINE: {jango.db, backends. slites’, ‘NAME’: ludsite. db3, Path settings Django requires an absolute path for directory settings. But we want to be able to ‘pass in the relative directory teferences. In order todo that we will add a helper Python function. Insert the following code at the top of the settings. py file: import os Hl der getabspath(x): return os,path.join(os. path.abspath(os.path. dirmane(_file_)), *) Now update the path options: ecode Bf teecate_oirs = ( sgetabspath(‘tenplates') BE septa root = getabspath(‘nedia’) Bi vepra_ur. = ‘/nedia" Now we will need to enable the ‘admin interface for our Django site, Ths is a neat feature of Django ‘which allows automatic creation of an admin interface ofthe site based con the data model. The admin interface can be used to add and manage content for a Django site Uncomment the following line BE InsTaLLeD_aPPs = ( H‘ajango.contrib.auth’, ‘django.contrib. contenttypes", ‘django. contrib. sessions’, ‘django.contrib. sites’, “django. contriib.messages' HB ‘jango.contrib, staticfiles’, “django.contrib. admin’, He # ‘django.contrib. adnindocs’, ) Creating ludissues app OB nieservewserserte primary app for oursite, called ludissues. To do that, we will use the manage py script: I python manage.py startapp “When you are using Python for web Introducing Python ludissues We will need to enable this app in the config file as well IE INSTALLED_APPS = ¢ HB ‘django.contrib.adnin’, Sudissues', ) Creating the data model OF Ressteparneve define the data model for our app. Please see the inline comments to understand what is happening here. From djangodb import models: Il We are importing the user authentication module so that we use the built I in authentication model in this app I From django.contrib.auth models import User IE & We would also create an admin interface for our app from django.contrib import admin HA tuple to hold the multi choice char fields H+ First represents the field name the second one repersents the display name TSSUE_STATUS CHOICES = ( Cnew’, ‘New’), accepted’ ’Accepted’), reviewed’ ’Reviewed’), started’ Started’), (closed’,'Closed"), development you get access to a huge catalogue of modules and support” Introducing Python [elas Issue(nodels.Model): TB # owner will be a foreign key to the User model which is already built in Django owner = models.Foreignke y(User, nul =True,blank=True) 4 multichoice with defaulting to “new status = models. CharField(nax_. length=25,choices=ISSUE_ ‘STATUS_CHOICES,default='new') summary = models. TextField() # date time field which will be set to the date time when the record is created opened_on = models. DateTineField(‘date opened’, ‘auto_now_add=True) ‘modified_on = models, DateTimeField(‘date modified’, ‘auto_now-True) def name(self): return self.sunmary. split¢"\n’,1){) IL & Admin front end for the ‘app. We are also configuring some of the He buitt in attributes for the admin interface on I & how to display the list, how it willl be sorted I # what are the search fields etc. class Issuesdmin(adnin, NodelAdmin): date hierarchy = “opened_on’ List filter = (‘status’,’owner’) list_display = Cid’,’n ‘ame’,’status','owner",nodifi ed_on’) search fields = ['description’,'status’] He register our site with ‘the Django admin interface admin.site. Make web apps with Python register(Issue, IssueAdmnin) To have the created data model reflected in the database, un the following command: $ python manage.py synedb Youll be also asked to create a superuser frit: You just installed Django’s auth system, which means you don’t have any superusers defined. Would you like to create one now? (yes/no): yes Enabling the admin site OS Tensesatey enabled, but we need to enable itn the usp fle — this contains the regex-based URL mapping from ‘model to view. Update the ur.py fle asfolows BE from django.conf.urls import patterns, include, url Il from django.contrib import admin adinin.autodiscover() B uripatterns = patterns(", unl¢r’*acinin/”, include(@dnin.site.urls), ) Starting the Django web server Djangoincludesa builtin web server whichis very handy to debug and test Ojango applications Let startit to see how our admin interface works. To stat the web server: Is python manage.py Ifyou do nothave any ertorsin your code, the server should be available ‘on port 8000. To launch the admin interface, navigate your browser to http/flocalhost800dvadmin. You wil be asked to log in here Enter the username and password thatyou created while you were syncing the database After logging in you will notice that allthe apps installed in your pioject are avalable here. We ae only interested in the Auth and Ludlssues app. You can dickthe +Add to add a record, Click the Add button next to Users and adda few users to the ste. ‘Once you have the users inside the system, you can now adda few issues tothe system Home » Ludasues Issues» Add issue Add issue Owner seas: mn ome omar Click the Add button next to sues, Here you will notice that you can enter (Owner Status and Summary for the issue. But what about the opened_on and modified_on field that we “It’s great that the owner field is automatically populated with details of the users inside the site” Make web apps with Python Introducing Python Site administration ~ Recent Actions Soe add 7Change My Actions Users acd Change None avalable Issues Aad 7Change sites add 7Change Select issue to change a defined while modeling the app? Creating the public user include(edmin.site.urls)), They are not here because thay are interface for ludissues > not supposed to be entered by the * This ensures that all the requests wil be User opened_on will automatically [At this point the admin processed by ludissues.ur ist. cevotmssetmerscresars — OZ ineraces orn bt modified_on will automaticaly set weneed a way todisplay the Creating ludissues.url tothe date time on which an issue data that we have added using - ismodified. the admin interface. But theres Another coo thing stat no public interface. Let create aia eee the onmer fields automatically itnow, iy) with the folowing content populated with all the users inside We will have'to begin by W tron django.cont-uris se oti ee import patterns, include, url ‘We have defined our Ist view to Urbspy (udissuetrackerus py laces aesneetesel| show ID name status ovner and I urtpatterns = patterns¢”, Mseceteriaes ‘modified on'in the model. You I Tissues canget to this view by navigating (7° include ludissues. tohttpr/localhost8000/admin/ urls’), + dictionary wi ludissues/ssue/ Be (r*adnins’, Il # dictionary with all the Introducing Python objects in ludissues info = ( ‘queryset':ludissues. objects.all(), 3 If To save us writing lots of python code I # we are using the list_ detail generic view H flist detail is the name of view we are using B urtpatterns = patterns(‘django.views.generic. List detail’, I #issue-list and issue-detail are the tenplate names BE tuhich will be looked in the default tenplate directories Burts object_ List’ info,nane="issue-list"), url(r"*(P LUD Issue Tracker 1 XY" class="sel">View Issues Admin Sites/ar 1
I ‘(% block content %}(% endblock %)
Be Be snem> we are using a Django feature called generic views” Make web apps with Python Introducing Python Jud iss [SES] Adminsite EI per TL) SECT mol 1 Theres aproblemin tat modile, new max 2 Intemet is not able to connect on the mars server. accepted ana 3 galactic federation has some issues with Star Wars accuracy stared samiisher 4 ‘Moving stairs are stuck again. This is the third time it happened today. started dumbledore S Three cells are missing rom solinter cell torch started __samfisher {{variablename # represents a issue.name }} hae Django variable (block ttle 98 represents blocks. Contents ofa block are evaluated bby Django and are displayed. These blocks can be replaced by the chid templates. Now weneed to create the isue_lst him template. This templates responsible for displaying all the issues avaiable nthe system, ludissuetrackerludlssueTracker/ templates/ucissuesssue_lst html BG extends ‘base.html’ %} (block title *WView Issues 1% endblock %} © block content %} te 1 < 1 I I {% for issue in object_list %) 0% endfor %} B
¢{ issue.id I} {{ ((_issue.status yetd> (C_ issue. ‘onner}}
HG endblock % Here we are inheriting the base himifile that we created eater. for issue in object_Ist 96) runson the object sent by the urlspy. Then we are iterating on the object_Ist for issueid and issuename. Now we will crate ssue_detal html. Thistemplate i responsible for displaying the deta view of acase. ludssueTiackerudlsucTracker! ‘templates/udssues/ssue_detal him BE (% extends ‘base.html’ %) HG block title xIssue #( object.id }} ~ (% endblock %} BG block content %} B shaatssue #(( object.id ) {{_object.status }}
i Infornation

Last modified {{ object.modified_on 3} agox/p> B

t

Omer

(¢ object.owner }}

(¢ object.summary }}

HE &% endblock %} ‘And that’s everything! The issue tracker app is now complete and ready to use. You can now point your browser at localhost8000 to start Using the app. Introducing Python Build an app for Android with Python. Build an app for The great thing about Kivy is there are loads of directions ‘we could take it in to do some pretty fancy things, But, were going to make a beeline for one of Kivy’s coolest features - the ability it affords you to easily run your programs on Android Well approach this by frst showing how to make a new app, this time a dynamic Breakout-style game, Welll then be able to compile this straight toan Android APK that you can Use just ike any other Of course, once you have mastered the basic techniques you aren't limited to using any particular kind of app, as even on Android you can make use of all your favourite Python libraries to make any sort of program you like. Once you've mastered Kivy, your imagination is the only limit, IF youre pretty new to Kivy, don't worry, we won't assume that you have any pre-existing knowledge. As long as you have mastered some of the Python in this book so far, and have a fairly good understanding of the language, you shouldn't have any problems following along with this, Before anything else, let's throw together a basic Kivy app (Fig, 01). We've pre-imported the widget types welll be using, which this time are just three: the basic Widget with no special behaviour, the ModalView with Android with Python a pop-up behaviouras used last time, and the FloatLayout as we will explain later. Kivy has many other pre-built widgets for creating GUss, but this time were going to focus on drawing the whole GUI from scratch using Kivys graphics instructions. These comprise either vertex instructions to create shapes (including rectangles lines, meshes, and 50 01) or contextual graphics changes (such as translation, rotation, scaling, eto), and are able to be drawn anywhere on your screen and on any widget type Before we can do any of this welll need a class for each kind of game object, which we're going to pre-populate with some of the properties that welll need later to control them, Remember from last time, Kivy properties are special attributes declared at class level, which (among other things) can be modified via kv language and dispatch events when they are modified, The Game class will be one big widget containing the entire game. We've specifically Build an app for Android with Python made ita subclass of FloatLayout because this special layout is able to position and size its children in proportion to its own position and size ~ so no matter where we run it or how much we resize the window it wil place all the game objects appropriately. Next we can use Kivy’s graphics instructions to draw various shapes on our widgets. Wellljust demonstrate simple rectangles to show their locations, though there are many more advanced options you might lke to investigate. In a Python file we can apply any instruction by declaring it on the canvas of any widget, an example of which is shown in Fig, 03. This would draw a red rectangle with the same position and size as the player at its moment of instantiation — but this presents a problem, unfortunately, because the drawing is static, When we later go on to move the player widget. the red rectangle will stayin the same place, while the widget will be invisible when itis ints real position. We could fx this by keeping references to our canvas instructions and repeatedly updating their properties to track the player, but there's actually an easier way to do all ofthis -we can use the Kivy language we introduced last time. Ithas a special syntax for drawing on the widget canvas, which we can.use here to draw each of our widget shapes: : canvas: Color: rgba: 1, 1, 1, 1 Rectangle: pos: self.pos size: self.size : canvas: Color: rgb: 1, 0.55, 0 Rectangle: pos: self.pos size: self.size red Rectangle(pos=self.pos, sizesself.size) # or without with syntax, self [Above Running the app shows ourcoloured blocks on the serean but they all oveap! We cantiathat easly You probably noticed we had one of the Block's Color instructions refer to its colour property. This means that we can change the property any time to update the colour of the block, or in this case to give each block a random colour (Fig. 04) Now that each of our widgets has a graphical representation, let's now tell our Game where to place them, so that we can start up the app and actually see something there, class Game(FloatLayout): def setup_blocks(self): for y_jump in rango(S): for x_jump in range(10): block = Block(pos_ hint={ x’ 0.05 + 0.094x_ jump, 'y': 0.05 + 0.094y_ jump) self. blocks. append(block) self.add_ widget(block) less BreakoutApp(pp): def build(elf): g = Game() g.setup_blocks() return g Here we create the widgets we want then use add_widget to add them to the graphics tree. Our root widget on the screen is an instance of Game and every block is added to that to be displayed. The only new thing in there is that every Block has been given a pos_hint. All widgets have this special property, and itis used by FloatLayouts like our Game to set their position proportionately to the layout. ‘The dictionary is able to handle various parameters, but in this case and 'y give x and y Block position as a relative fraction of the parent width and height. You can run the app now, and this time it will add 50 blocks to the Game before displaying it on the screen, Each should have one of the three possible random colours and be positioned in a rid, but youll now notice their sizes haven't been manually set so they all overlap. We can fix this by setting their size_hint properties ~ and let's also. Build an app for Android with Python take this opportunity to do the same for the other widgets as well (Fig. 05). This takes care of keeping all our game widgets positioned and sized in proportion to the Game containing them, Notice that the Player and Ball use references to the properties we set earlier, so welllbe able to move them by just setting these properties and letting kv language automatically update their positions. The Bal also uses an extra property to remain square rather than rectangular, just because the alternative would likely look alittle bitodd. Weve now almost finished the basic graphics of our app! All that remains isto add a Ball and a Player widget to the Game. : ball: the_ball player: the_player Ball: id: the_ball Player: ic: the_player You can tun the game again ‘now, and should be able to see all the graphics working properly. Nothing moves yet, but thanks to the FloatLayout everything should remain in proportion if you resize the game/window. Now we just have to add the game mechanics. For a game like this you usually want to run some update function many times per second, updating the widget positions and carrying out game logic —in this case collisions with the ball Fig. 06) The Clock can schedule any function at any time, either once or repeatedly. A function scheduled at interval automatically receives the time since its last call (dt here), which welve passed through to the ball and player vie the references we created in kv language. I's good practice to scale the update (eg ball distance moved) by this dt, so things remain stable even if something interrupts the clock and updates don't meet the regular 1/60s you want. Atthis point we have also added the first steps toward handling keyboard input, by binding to the kivy Window to call ammethod ofthe Player every time a key is pressed. We can then finish off the Player class by adding this key handler along with touch/mouse input. class Player(Wideet): def on_touch_down(self, touch): self.direction = ( ‘right’ if touch.x > self.parent. : size_hint: 0.09, 0.05 # canvas part Player>: size_hint: 0.1, 0.025 int: {x2 self. position, # all>: pos_hint: {'x': self.pos_ hint_x, ’: self.pos_hint_y) size_hint: None, None proper_sii in(@.034self.parent. height, 0.034self.parent.width) size: self.proper_size, self.proper_size # ... Canvas part from kivy.clock import Clock from kivy.core.window import Window from kivy.utils import platform class Game(FloatLayout): def update(self, dt): self.ball. update(dt) Not ed yet self.player. update(dt) # Not defined yet def start(elf, xargs): Clock. schedule. interval(self.update, 1./60.) def stopGelf): Clock. unschedule(self. update) ce? reset(self): for block in self blocks: self.remove_ widget (block) self.blocks = [] self.setup_ blocks() self.ball.velocity = [random.random(), 0.5] self.player. position = 0.5 cles BreakoutApp (sop): def build(elf): Build an app for Android with Python Game() if platform) |: ‘android’: Window. bind(on_key_down=g.player. on_key_down) Window. bind(on_key_up=g.player.on_ key_up) g.reset() Clock.schedule_ once(g.start, return g class Ball(Widget) def update(self, dt): self,pos_hint_x + self velocity(a] * dt self,pos_hint_y += selfvelocityti] * dt if self.right > self.parent.right: # Sour from right self. velocity] = -1 * abs(elf. velocityta) if self.x < self. parent.x: # Bounce from left self. velocity(3] = —abs(self. velocityt7) if self.top > self.parent.top: # Bounce from top self. velocity[i] = -1 * abs(elf. velocityt1]) if selfy < self. # Lose at bottom self.parent. # Not implemented yet self.bounce_from_ player(self.parent.player) parent.y: Losec) def bounce_ from_player(self, player): if self. collide_widget(player): self, velocityti] = abs(self. velocityCi]) self. velocityl’] += ( 1 * — Gelf.centerx - player.center_x) / player.width)) © lo aos GameEndPopup("iorialView): message StringProperty() game = ObjectProperty() clas Game(\\idlzet): def lose(self): self. stop() GameEndPopup( message=" [color=#*f0000]You Jose![/color]', game=self).open() def winGelf): # Not called yet, but we'll ed it later self.stop( GameEndPopup(, message='[color=#00ff00]You win![/color]', game=self).open() Introducing Python BoxLayout: orientation: ‘vertical’ Label: text: root. message font_size: 60 markup: True halign: ‘center’ Button: size_hint_y: None height: sp(82) text: ‘Play again?’ font_size: 60 on_release: root.game.start(); root. dismiss() Here you will be needing some basic dependencies, which can be installed with ease just by using your distros normal repositories. The main ones to use are OpenJDK7, zip, an up-to-date Gython, and Git.fyou are using a 64bit distro you wil abo be in need of 32-bit compatibility Ibraries for zi, libstdc++, as well aslibgcc. You can then go on and download and install Buidozer: Introducing Python Putting your APK Uae) Py Orestes eo Cetera 2pk Build an app for Android with Python. “Check through the whole file just to see what's available, but most of the default settings will be fine” git clone git://github.con/ kivy/buildozer cd buildozer sudo python2.7 setup.py ‘install When youte done with that part you can then goon and navigate toyour kivy app, and youll have ‘to name the main code file ‘main. py, this is the access point that the Android APK will expect. Then: buildozer init This creates a ‘buildazerspec’ file, a settings file containing all the information that Bulldozer needs to create your APK, from the name and version to the specific Android build options. We suggest that you check through the whole file just to see what's available but most of the default settings will be fine, the only thing we suggest changing is ig. 11) There are various other options you will often want to set, but none are really all that vital right now, so you're able to immediately tell Buildozer to build your APK and get going! buildozer android debug. This will take some time, so be patient and it will work out fine, When you first run itt will download both the Android SOK and NDK, which are large (at least hundreds of megabytes) but vital to the build. twill also take time to build these and to compile the Python components of your APK. Alotof this only needs to be done once, as future builds wil take a couple of minutes ifyou change the buildozerspec, or just few seconds if youve only changed your code. The APK produced is a debug ‘APK, and you can install and use it There are extra steps if you want to digitally sign it so that it can be posted on the Play store. ‘This init hard, and Buldozer can do some of the work, but check the documentation online for full details, ‘Assuming everything goes fine (it should), your Android APK will be ina newly created ‘bin’ directory with the name ‘KivyBreakout-0.1-debugapk’ You can send it to your phone any way you lke (eg emai), though you may need to enable application installation from unknown sources in your Settings before you can install it Build an app for Android with Python self.parent.do_ layout() self.parent.destroy_ blocks(self) Game(FloatLayout): def destroy_blocks(self, ball): for i, block in enumerate (self.blocks): if ball. collide_widget(block): y_overlap ball. top - blocky if ball. velocity[i] > else block.top - ball.y) / block size_hint_y x overlap =¢ ball. right - block.x if ball. velocity[2] > 0 else block.right - ball.x) / block.size_hint_x if x overlap < y_overlap: ball.velocity[2] *= 4 else: ball.velocity[1] «= a self. remove_widget(block) self.blocks. opti) if len(eelf. blocks) self. wing) return title = Kivy Breakout package.name = breakout. fullscreen = 0 Jog_level = 2 Above Yourgame shoulda on any modern Anold device. youcan even ula lease ‘version and publish oan app tore Introducing Python eae score Ecos eee eee ai tee erie Sen Cre then you Sees ae ty er ne Perro Perce he tosubmity Mercere, eee reo ir Sees eee eat Cae Introducing Python: 50 Python tips i 50 Python tips Python is a programming language that lets you work more quickly and integrate your systems more effectively. Today, Python is one of the most popular programming languages in the open source space. Look around and you will find it running everywhere, from various configuration tools to XML parsing. Here is the collection of 50 gems to make your Python experience worthwhile. rR ec} Running Python scripts. OT rreserteunecsstens youcan run Python scripts from the commandline. Is python mypyprog.py Running Python programs from Python interpreter OD mertoniseectie interpreter makes ft easy to ‘ty your fist steps in programming and using alPython commands. You just ssue each command atthe command prompt >>),one by cone and the answerisimmediate Python interpreter canbe started with the command: Is python B kunaleubuntu:~$ python [Python 2.6.2 (release26- maint, Apr 19 2009, 01:56:41) {60c 4.3.3] on linuxz Type “help”, “copyright”, “credits” or “License” for nore information. >>> Inthisarticle, allthe code starting at the >>> symbolis to be given at the Python prompt. Itis also important to remember that Python takes tabs very seriously —s0 fyou are receiving any error that mentions tabs, correct the tab spacing. Dynamic typing OB 2a cerarsonersaaty typed languages, you must specify the data type of te function return value and each function argument. On the other hand, Python isa dynamically typed language. In Python you will never have to explicitly specify the data type of anything you use. Based on what value you assign, Python will automatically keep track of the data type internally Python statements 4 entssscartoe cums to separate statements, and ‘acolon and indentation to separate code blocks. Most of the compiled programming languages, such as C and G+, use semicolons to separate staterents and curly brackets to separate code blocks. = and = operators 0 Python uses comparison and assignment. Python does not support inline assignment, so there'sno chance of accidentally assigning the value when you actually want to compareit. Concatenating strings O62" strings >> print ‘kun'val™ kunal The __init O7 resttanctnne soon asan object of aclass is instantiated. The method is useful to do any initialization you want to do with your object. The —init__method isanalogousto a Constructor in G+, C# or Java Example: class Person: def _init_(self, name): self.name = name def sayHi(eelt): print ‘Hello, my name , selfinane Person(‘Kunal”) p.saykiO Output: I G-sre/python $2 python initmethod.py [Hello, my name is Kunal method Modules OB Bieeeezroser: manageable as they growin size you may want to make them into several ies, Python allows you to put multiple function definitionsinto a le and use them asa module that can be imported. These fles must havea. py extension however, Example: I # File my_function.py nin, max = b, 2 return min, max Module Usage Bi import my_function Module defined names oon: “The builtin function ‘i can be used to find out which names a module defines. It returns a sorted list of stings I> inoort tine >> dir(time) doc ‘name’, ‘accept2dyear’, ‘altzone’, ‘asctine’, ‘clock’, ‘tine’, ‘daylight’, ‘gmtime’, ‘Localtime’, ‘mktime’, ‘sleep’, ‘strftime’, ‘strptime’, ‘struct_time’, ‘time’, ‘timezone’, ‘tzname’, ‘tzset’Jfile’] Module internal documentation TO rmcersseeners documentation (if available) of a module name by looking at doc. Example: [>>> import time >>> print time.clock._.doc__ I clock() -> floating 50 Python tips point nunber ‘This example retums the CPU time or real time since the start of the process or since the fst call to clock0, This has just as much precision as the system records do, Passing arguments toa Python script Tiitensauacces hater you have passed toa script while caling it The commandline” ‘content i stored inthe sysargy lst. import sys H print sys.arev Loading modules or commands at startup [Duce oss redetines modules or commands atthe startup of ‘any Python script by using the environment variable SPYTHONSTARTUP You can set environment variable SPYTHONSTARTUP to afile which contains the instructions load necessary modules or commands Converting a string to date object TB rmsnatrehacton 'DateTime'to.comerta stingtoa date object. Example: I From Datetime import DateTime dateobj = DateTine(string) Converting a string to date object [Arrrenenetatsio sting in the following ways. ‘Ist method: Hl >> mylist = ('spam’, ‘ham’, Introducing Python ‘eggs! [>> print +, ‘joinglist) BE spam, ham, eges 2nd methods B >> print \n'joingylist) pam ham Hezes Tab completion in Python interpreter TB rmemaezaue ‘completion inside Python interpreter by adding these lines to your pythonrc fle (or your fle for thon to ead on startup) import rlconpleter, readline I readline.parse_and bind(‘tab: complete") This will make Python complete partially typed function, method and variable names when you press the Tab key. Python. documentation tool 1 ‘You can pop upa graphical interface for searching the Python documentation using the command Bs pydoc -¢ You will need python-tk package for this to work, “Today, Python is certainly one of the most popular programrnin languages to found in the open source space” Introducing Python 50 Python tips Accessing the Python Converting from integer Detecting system documentation server to binary and more platform Target nnTPsever DQ Pvrenpoideseaytouse DA Tooscuepovor spec on the given port on the: functions — bind), hex) and functions, itis very useful to be local machine. This will give you a oct) — to convert from integer to binary, able to detect the platform on which nice-looking access to all Python decimal and octal format respectively. ‘the Python interpreters running, You documentation, including third-party Example: can use ‘sysplatform to find out the module documentation. B >> bina current platform. I'S pydoc -p “eb11000" Example: >>> hex(24) On Ubuntu Linux Python development Hf ons" >> import sys canvas H>> oct(24) I >> sys.platform “030° “Linux2” . ‘On Mac OS X Snow Leopard 1 There are plenty of toolstohelp ~~ Converting any [>> import sys ‘with Python development. charset to UTF-8 BE > sys.platform Here are a few important ones: eso cetenbnelioeneacere sree “darwin? IDLE: The Python builtin IDE, with axtecompletion function grature pq Youcansethe folowing Disabling and enabling popup hela and file editing function to convert any charset a IPython: Another enhanced Python toUTF-8. garbage collection shell with tab-completion and B data decode(“input_charset_ . other features. here”).encode(‘utf-8') 25 craimejouay Eric3: A GUI Python IDE with want to enable or disable autocompletion, class browser builtin. Removing the garbage collector function shell and debugger. i i atruntime. You can use the ‘ac’ WingIDE:Commercalythonine —-Auplicates from lists ___ module to enable or disable the with fee licence avalable to open- garbage collection. source developers everywhere, QD Domeriowmoesinicses Example: froma lis, ust putevery >>> import gc elementintoa dictas akey for >> gc.enable eel AMANO cme witnrone'esvaueiandthen Hl " check dictkeys0 >>> gc.disable Executing at Python I from operator import setiten " mmap(setitem, (4,)¥len(1), 1 9 You can use ‘atexit’ module to ‘ i)) Using Cbased modules ‘execute functions at the time of return d.keys() Python interpreter termination for Dettet Deter ane Example: chi TH cef sumo: Do-whileloops DErerthen modus print@+5) ship with counterpart Ti def messageQ: 2 3 Since Python has no do-while ‘C modules. Using these C print(“Executing Now”) ‘ordo-untillogp constructs et), modules will give a significant TH import atexit ‘you can use the following method to performance boost in your I atexit.register(sum) achieve similar results: complex applications, EE atexit register(message) while True: Example: Output: TH do_somethingd) H crickle instead of BE Executing Now if condition): Pickle, cStringIO instead 9 1 break of Stringlo Calculating maximum, minimum and sum D7 urustte following built- in functions ‘max: Returns the largest element in the list. ‘min: Retuins the smallest element in the ls. sum: This function returns the sum Of all elements in the Ist. Itaccepts an optional second argument: the value tostart with when summing (defaults 00). Representing fractional numbers DB incininsunce cn ve created in Python using the following constructor: I Fraction((nunerator C,denominator]]) Performing math operations 29 erat mode roves a plethora of mathematical functions. These functions work on integer and float numbers, except complex numbers. For complex numbers, a separate module is used, called cath. For example: [ nath.acos(x): Return are cosine of x. Bi nath.cos(): Returns cosine of x. EE nath.factorial(x) : Returns x factorial. Working with arrays The ray’ module provides BO ireicenrwoyts toro inyour programs. The array’ module defines the following type: B array(typecode [, 50 Python tips initializer) ‘Once you have created an array object, say myarray you can apply a fbunch of methods to it. Here area few important ones: Bi nyarray.count@): Returns the number of occurrences of x ina. B nyarray.extend(x): Appends x at the end of the array. B ayarray.reverse(): Reverse the order of the array. Sorting items Brains: it very easy to keep lists in any possible order. You can use the following functions to order lists I bisect.insort(list, item [, Jow C, high) Inserts iter into lst in sorted order. f item is already in the lst, the new entry isinserted to the right of any existing entries there. I bisect.insort_left(list, item C, low C, highl]) Inserts item into list in sorted order. Ifitem is already within thelist the ‘new entry is inserted tothe left of any existing entries. Using regular expression-based search BD ete morte aes tvery easy 10 use regxp-based searches. You can use the function ‘research! with aregexp-based expression. Check out the example included below. Example: >> import re >>> s = ‘Kunal is a bad boy” [>> if research(‘x", 9) print “Match!” # char Literal B Match! H>> if research(‘teaz, 5): print “Match!” # char class # match either at-sign or Introducing Python capital letter BE match! BH >> if re.search("\d", 5): print “Match!” # digits class Working with bzip2 (.bz2) compression format 33 You can use the module 'bz2’ 10 read and write data using the bzip2 compression algorithm, H bzz.conpress() For bz2 compression Bl bz2.decompress() decompression Example: IDs File: bz2-exanple.py import be? Bvessace = “Kunal is 2 bad For bz2 I conpressed_message = bz2. compress (MESSAGE) IH deconpressed_message = bz2. decompress(compressed_message) print “original:”, repr (MESSAGE) print “compressed message:”, repr(compressed_ message) print “decompressed message:”, repr (decompressed_message) Output: I isre/python $:1 python bz2- example. py original: ‘Kunal is a bad I compressed message: “BISIAVESY \xcA\xOFG\X9B\. 00\ x00\x02\x15\x802\x00\x00\ 0848 x82 \xQ0"\Q0\xBe\x84\r\x030\ xa2\xb@\xd6s\xa5\xb3\x19\x00\xF8\ XBB\xS2)\xC2\xB4\x86_2<\xc0" I decompressed message: ‘Kunal is a bad boy’ "There are tools to ra develop Python" wit

You might also like