The Python Book 2Nd Edition
Total Page:16
File Type:pdf, Size:1020Kb
NEW OVER 2 HOURS PythonThe OF VIDEO TUTORIALS The ultimate guide to coding with Python Over 20 incredible projects Learn to use Python t1SPHSBNHBNFTt(FUDSFBUJWFXJUI1J Welcome to PythonThe Python is an incredibly versatile, expansive language which, due to its similarity to everyday language, is surprisingly easy to learn even for inexperienced programmers. It has seen a huge increase in popularity since the release and rise of the Raspberry Pi, for which Python is the officially recognised programming language. In this new edition of The Python Book, you’ll find plenty of creative projects to help you get to grips with the combination of your Raspberry Pi and Python’s powerful functionality, plus lots of tutorials that focus on Python’s effectiveness away from the Raspberry Pi. You’ll learn all about how to code with Python from a standing start, with our comprehensive masterclass, then go on to complete tutorials that will consolidate your skills and help you to become fluent in the language. You’ll learn how to make Python work for you with tutorials on coding with Django, Flask, Pygame and even more useful third-party frameworks. Get ready to become a true Python expert with the wealth of information contained within these pages. PythonThe Imagine Publishing Ltd Richmond House 33 Richmond Hill Bournemouth Dorset BH2 6EZ +44 (0) 1202 586200 Website: www.imagine-publishing.co.uk Twitter: @Books_Imagine Facebook: www.facebook.com/ImagineBookazines Publishing Director Aaron Asadi Head of Design Ross Andrews Production Editor Alex Hoskins Senior Art Editor Greg Whitaker Assistant Designer Steve Dacombe Printed by William Gibbons, 26 Planetary Road, Willenhall, West Midlands, WV13 3XT Distributed in the UK, Eire & the Rest of the World by Marketforce, 5 Churchill Place, Canary Wharf, London, E14 5HU Tel 0203 787 9060 www.marketforce.co.uk Distributed in Australia by Network Services (a division of Bauer Media Group), Level 21 Civic Tower, 66-68 Goulburn Street, Sydney, New South Wales 2000, Australia Tel +61 2 8667 5288 Disclaimer The publisher cannot accept responsibility for any unsolicited material lost or damaged in the post. All text and layout is the copyright of Imagine Publishing Ltd. Nothing in this bookazine may be reproduced in whole or part without the written permission of the publisher. All copyrights are recognised and used specifically for the purpose of criticism and review. Although the bookazine has endeavoured to ensure all information is correct at time of print, prices and availability may change. This bookazine is fully independent and not affiliated in any way with the companies mentioned herein. The Python Book Second Edition © 2016 Imagine Publishing Ltd ISBN 9781785462382 Part of the bookazine series PythonThe Contents 8 Get started Work with Python Create with Python with Python Master the basics the right way 74 Python for professionals 108 Build tic-tac-toe with Kivy Use your coding skills at work Program noughts and crosses 16 50 essential 82 Make extensions for XBMC 112 Create two-step authentication commands Enhance XBMC with this tutorial Use Twilio for safe authentication The commands you need to know 88 Scienti c computing 116 Program a Space Invaders clone Get to grips with NumPy Make the basic Pivaders game 92 Instant messaging 120 Add animation and sound Get chatting using Python Enhance your Pivaders game 98 Replace your shell 124 Make a visual novel Use Python for your primary shell Program a book-style game 102 Python for system admins 128 Pygame Zero Python essentials How Python helps system administration Turn your ideas into games 26 Code rock, paper, scissors Put basic coding into action 82 116 32 Program a hangman game Use Python to make the classic game 38 Play poker dice Test your luck and your coding 44 Create a graphical interface Add interface to your projects 50 Bring graphics to games Add images to simple games 92 124 56 Build an app for Android Make your own app with Kivy 62 Making web apps Use Python to create online apps 66 50 Python tips Essential knowledge for Python users 6 The Python Book 136 170 66 50 Python Web development Use Python with Pi 136 Develop with Python tips 160 Programming in Python on Why Python is perfect for the web Raspberry Pi 142 Create dynamic templates Learn how to optimise for Pi Use Jinja, Flask and more 164 Turn Raspberry Pi into a 146 Build your own blog “Get to grips stop-motion studio Begin developing your blog with Python, and Learn how to optimise for Pi 150 Deliver content to your blog 168 Send SMS with Pi Add content to your site master highly Send text messages for free 154 Enhance your blog 170 Build an LED Matrix Complete your blog with add-ons versatile code” Use Pi to control light sequences The Python Book 7 Get started with Python Always wanted to have a go at programming? No more excuses, because Python is the perfect way to get started! ython is a great programming language for libraries to create a windowed application, or you could Pboth beginners and experts. It is designed with try something a little more ambitious like an app such code readability in mind, making it an excellent as creating one using Python’s Bluetooth and Input choice for beginners who are still getting used to libraries to capture the input from a USB keyboard and various programming concepts. relay the input events to an Android phone. The language is popular and has plenty of libraries For this guide we’re going to be using Python 2.x since available, allowing programmers to get a lot done with that is the version that is most likely to be installed on your relatively little code. Linux distribution. You can make all kinds of applications in Python: In the following tutorials, you’ll learn how to create you could use the Pygame framework to write popular games using Python programming. We’ll also simple 2D games, you could use the GTK show you how to add sound and AI to these games. 8 The Python Book Get started with Python The Python Book 9 Get started with Python Hello World Variables and data types Let’s get stuck in, and what better way than with the A variable is a name in source code that is associated with an programmer’s best friend, the ‘Hello World’ application! Start area in memory that you can use to store data, which is then by opening a terminal. Its current working directory will be your called upon throughout the code. The data can be one of many home directory. It’s probably a good idea to make a directory for types, including: the fi les we’ll be creating in this tutorial, rather than having them loose in your home directory. You can create a directory called Python using the command mkdir Python. You’ll then want to Integer Stores whole numbers change into that directory using the command cd Python. The next step is to create an empty fi le using the command Float Stores decimal numbers ‘touch’ followed by the fi lename. Our expert used the command Boolean Can have a value of True or False touch hello_world.py. The fi nal and most important part of String Stores a collection of characters. “Hello setting up the fi le is making it executable. This allows us to run World” is a string code inside the hello_world.py fi le. We do this with the command chmod +x hello_world.py. Now that we have our fi le set up, we can go ahead and open it up in nano, or any text editor of your As well as these main data types, there are sequence types choice. Gedit is a great editor with syntax highlighting support (technically, a string is a sequence type but is so commonly used that should be available on any distribution. You’ll be able to we’ve classed it as a main data type): install it using your package manager if you don’t have it already. List Contains a collection of data in a specifi c order [liam@liam-laptop ~]$ mkdir Python [liam@liam-laptop ~]$ cd Python/ Tuple Contains a collection immutable data in a [liam@liam-laptop Python]$ touch hello_world.py specifi c order [liam@liam-laptop Python]$ chmod +x hello_world.py [liam@liam-laptop Python]$ nano hello_world.py A tuple would be used for something like a co-ordinate, containing an x and y value stored as a single variable, whereas Our Hello World program is very simple, it only needs two lines. a list is typically used to store larger collections. The data The fi rst line begins with a ‘shebang’ (the symbol #! – also known stored in a tuple is immutable because you aren’t able to as a hashbang) followed by the path to the Python interpreter. change values of individual elements in a tuple. However, you The program loader uses this line to work out what the rest of the can do so in a list. lines need to be interpreted with. If you’re running this in an IDE It will also be useful to know about Python’s dictionary like IDLE, you don’t necessarily need to do this. type. A dictionary is a mapped data type. It stores data in The code that is actually read by the Python interpreter is only key-value pairs. This means that you access values stored in a single line. We’re passing the value Hello World to the print the dictionary using that value’s corresponding key, which is function by placing it in brackets immediately after we’ve called different to how you would do it with a list.