You are on page 1of 148

The best programming guide money can buy!

Learn how to program the easy and fun way

฀ ฀ ฀
฀ ฀ ฀ ฀ ฀

฀ ฀ ฀฀

Learn how to program the easy and fun way

uk Phone +44 ( 0 )1225 442244 Fax +44 ( 0 )1225 732275 All contents copyright © 2016 Future Publishing Limited or published under licence. Online enquiries: www. 'VUVSF1VCMJTIJOH-JNJUFE DPNQBOZOVNCFS JTSFHJTUFSFEJO&OHMBOEBOE8BMFT3FHJTUFSFEPGmDF3FHJTUFSFEPGmDF2VBZ)PVTF 5IF"NCVSZ #BUI #"6" All information contained in this publication is for information only and is. Bath. Future 4UPDL&YDIBOHF Managing Phone: 020 7429 4000 Future Publishing Limited Quay House. neither Future nor its employees. Future plc is a public Chief executive .uk 2 East Poultry Avenue. No part of this magazine may be reproduced. BA1 1UA. UK www. ART EDITOR Mike Saunders. Future Photo Studio MANAGEMENT MARKETING CIRCULATION MARKETING MANAGER TRADE MARKETING MANAGER EDITORIAL DIRECTOR Richard Stephens Juliette Winyard Paul Newman Phone +44(0)7551 150984 GROUP ART DIRECTOR Steve Gotobed PRINT & PRODUCTION LICENSING PRODUCTION MANAGER SENIOR LICENSING & Mark Constance SYNDICATION MANAGER Matt Ellis PRODUCTION CONTROLLER matt. correct at the time of going to press. Jonni Bidwell Efrain Hernandez-Mendoza EDITOR-IN-CHIEF Graham Barlow IMAGES ThinkStock. You are advised to contact manufacturers and retailers directly with regard to the price and other details of products or services referred to in this publication.myfavouritemagazines. The Ambury.futureplc. you automatically grant Future a licence to publish your submission in whole or in part in all editions of the magazine. London EC1A EDITORIAL TEAM CONTRIBUTORS EDITOR Les Pounder.JMMBI#ZOH5IPSOF We are committed to using only magazine paper company quoted Non-executive chairman Peter Allen XIJDI JT EFSJWFE GSPN XFMM NBOBHFE  DFSUJmFE on the London &KLHIÀQDQFLDORIÀFHU1FOOZ-BELJO#SBOE forestry and chlorine-free manufacture. Mayank Sharma. although every care is Vivienne Calvert Phone +44(0)1225 442244 SUBSCRIPTIONS PRINTED IN THE UK BY UK reader order line & enquiries: 0844 848 2852 William Gibbons on behalf of Future. on tablet recycling site. All rights reserved. WorldMags. Ben Everard.myfavouritemagazines. Future cannot accept any responsibility for errors or inaccuracies in such information. Any material you submit is sent at your risk and. stored. Magazines Joe McEvoy TZNCPM'653  Publishing and its paper suppliers have been www.ellis@futurenet. Apps and websites mentioned in this publication are not under our control. If you submit unsolicited material to us. as far as we are aware. transmitted or used in any way without the prior written permission of the publisher. & smartphone and in print. We are not responsible for their contents or any changes or updates to them. either through group and leading digital www. We encourage you to recycle Future is an award-winning international media this magazine. Neil Mohr Graham including licensed editions worldwide and in any physical or digital format throughout the world. agents or subcontractors shall be liable for loss or damage. Overseas reader order line & enquiries: +44 (0)1604 251045 Distributed in the UK by Seymour Distribution Ltd. We reach more than 57 million international consumers a month your usual household recyclable and create world-class content and advertising waste collection service or at solutions for passionate consumers online.


the gatekeepers to we all can access operating systems. move on to more than Cool Britannia – jump forward to advanced topics. coders the ideal guide to start coding. We’ll Back then. Thanks to have suddenly become a new generation of open free software. Combine the huge development tools. then access steam the world hasn’t seen since the everything you need freely online. cool devices. pushing coding to the fore of education. exciting and fun. So Brit invented the web. apps and tools. newbie looking to take your first steps into business start-ups and the coding world. smartphone software with confidence and really the learning journey as enjoyable as or laptop – see page 146 for more get to know how to use it possible for you details on this offer How are we doing? Email techbookseditor@futurenet. Editor Made Simple books are designed Break instructions down into Teach you new skills you can take to get you up and running quickly easy-to-follow steps so you won’t with you through your life and apply with a new piece of hardware or be left scratching your head over at home or even in the workplace software. a Brit designed what are you waiting for? Get coding! the Raspberry Pi. It’s an exciting journey! Coding is the new cool. We’ll show you how to get up and running and you’ve got a head of technological with a Linux system. these new realms. With the internet So no matter if you’re looking to relive driving a new world of those heady ’80s coding days or are a information exchange. A exciting and easy-to-follow projects. coding craze of the early and let us know if we’ve lived up to our promises! WorldMags. explain how you can use today. and Britain is firmly Neil Mohr. you hold in your hands online gaming. We won’t bombard you what to do next with jargon or gloss over basic Make it easy for you to take our principles. it was more Code Britannia explain the Coding Made Simple | 5 . but we will… Help you discover exciting new advice everywhere with you by things to do and try – exploring giving you a free digital edition of Explain everything in plain English new technology should be fun and this book you can download and take so you can tackle your new device or our guides are designed to make with you on your tablet. such as the Raspberry Pi. Coding is easy. and Britain is again firmly at the the Raspberry Welcome! Learning to code will change the way you think about the world. and provide you with heart of a web and coding revolution. compilers and the interest in learning how to create and programming languages needed to create control these worlds with the surge of professional programs. WorldMags.

................................................................................................................................................................................................................. 10 Get coding in Linux Mint .......................................... 48 Using loops ................................................................................................................. 52 Common mistakes ................................................................................................................... 16 Join the Coding Academy .................................................. 54 6 | Coding Made Simple WorldMags............... 40 Recursion ...........................................32 Functions and objects ............................................................................... 50 Compilers ......................................................................................................................................................... 36 Variables ............................................................ 34 Conditionals ........ 46 Integers ........... 38 Program structure Contents Get coding Get started with Linux .............................................................................................................................................................................................................................................................................................................................................................................................................................................................. 44 Sorting algorithms ................................................................................................................. WorldMags................................................................................................................................................................................... 19 How to use an IDE ............... 28 Coding basics Lists ......................................................................................................

.................................... Raspberry Pi Getting started 82 .........64 UNIX programs part 1 ....................................................................................... Further coding Data types 58 ................................................................................. 134 Twitter scanner ................ More data types .......................................................... 128 Sound filters ..................................................................... 110 2048 in Minecraft ........................................................................................0 primer ...................................................................................................................................... 108 Image walls in Minecraft ............................................66 UNIX programs part 2 .............................................................................. Python 3................... Starting Scratch 84 .......................................................................................................................................................................................................................... 124 Image filters ........................... Using files ............................................................................................................................... Persistence 76 ......................................................................................................................................................................................................................................................................................................................................................................................................................... 102 Hacking Minecraft .................................................................................................................................... 138 Build a GUI ........ 114 Coding projects Python 3................. Further Scratch 88 ............................................ Coding with IDLE 92 ................................. Modules 74 ...............................................................................................................................................................................................................................................................................................60 Abstraction 62 .......................................................... Advanced sorting ........................................................................................................ Coding Made Simple | 7 ............ Databases 78 ..................................68 UNIX programs part 3 70 ...0 on the Pi 98 ............................. 142 WorldMags............................................................................................................................................................................................................................................................ 120 Build a Gimp plug-in ................................................................................................................................................................................................................................................................................................................................................................................................ Python on the Pi 94 .......................................... .net WorldMags. Get coding! Everything you need to start coding today Get started with Linux Coding Made Simple | 9 ... 19 How to use an IDE...................................... 28 WorldMags.................................... 10 Get coding in Linux Mint ...................WorldMags.................. 16 Join the Coding Academy ......

We recommend that walkthrough shows you how to create a live desktop. 10 | Coding Made Simple WorldMags. You don’t have to – the code works you use a version (known as a distro) called image that you can boot and run from either a on Windows or Mac OS X – but Linux comes Linux Mint. There’s a That’s the beauty of Linux – it’s built by don’t want to. you’re used to its slightly different interface how to run Mint within VirtualBox on top of All the coding projects in this bookazine are and way of working. notice that most of the screens dodgy sites. you’ll from a central GET STARTED WITH LINUX It runs on most desktop and laptop PCs. it won’t damage PC dual-booting with Windows. you don’t even have to install anything if you Windows or Apple Mac OS X. The walkthrough opposite explains by thousands of coders around the world. there are three options: run Linux in there are different car VirtualBox. while the next based on someone running Linux on their really is to get along with. you’ll find how easy it Windows (or Mac OS X). No scouting round running on your PC. WorldMags. it’s free and you don’t even need to install it. just run a command or fire up a It’s not scary. run it off a DVD or manufacturers or makes of USB drive.” likely to cause any damage. It’s just your PC and you don’t even We’re only going to look at the first two as they’re the least that Linux happens to be free because it’s developed have to install anything. or install it on your TV. Just as geeks for geeks to do geeky things. If you currently have a Windows good reason for that: they’re . operating system that can run your PC or Mac. Let’s look at Linux! A s you read through this Coding with many languages built in or ready to install you can get hold of Mint and then get it up and Made Simple bookazine. it won’t damage your PC and don’t look like Microsoft software centre to get what you need. and we’re going to look at the ways DVD or a USB flash drive. there’s more than one “It’s not scary. Once PC.

we recommend 2048. you’re free to try you’ll need around 20GB of spare drive space have an 8GB PC. start VirtualBox. because core servers to websites. we think you’ll developers. Once dynamic hard drive and download Choose Ubuntu and the bits should match the A prompt asks for a disc. that. and there are literally hundreds out after all. not all maintained. 4096 is best. It had it also comes from GNU. you should enable 3D acceleration choose Linux and call it ‘Mint’. in the virtual machine’s settings under installed. there’s the Software Center. I f you’ve never tried Linux. As long as In the Linux VirtualBox 1 Get VirtualBox 2 Create a machine 3 Start virtual Mint Head to www. commands.linuxmint. It is not only the too cumbersome. contribute back to the community. You should also know that Linux designed and created by developers. Locate the Mint ISO Virtual Box 5 for your operating system. The upshot of this history is that there’s a Linux is free software. anyone can take it and 97% of the world’s supercomputers. click New Machine. the key weakness of be surprised at how easy it is to use. programs in /bin and /usr/bin that come from WorldMags. click Start to get going. which is less here. you’re willing to seek out help yourself and short. Under file you downloaded and click Start. So just about any time created most of the basic tools needed by a you do anything on your computer – every time computer of the early 1980s – compilers. when it’s Top tip makes. the key way of getting new tools and all the programming development tools you The GNU of GNU/Linux The GNU project (GNU stands for ‘GNU’s Not GNU. getting programs by downloading them from This is one of the reasons why Linux has opt for the MATE edition. but we suggest 32GB just in case. he had a kernel without the tools to run GNU aspect. once and much more – but did not have No wonder the GNU die-hards get upset a usable kernel (some would say its kernel. which A big reason why Linux makes such a good viruses and malware. but No matter which tutorial you follow. It is worth mentioning Torvalds started tinkering with his small project that no one really denies the importance of the in 1991. the remained so secure (it’s not infallible) but graphically demanding. You also need the all the rest as default settings. apart from the Mint to the virtual machine. in the past you’ve been used to maintained by the distro’s creators. GNU when we refer to our operating system as Hurd. you’ll a very welcoming and rich development hundreds nonetheless. introduction of the Windows Store has at least people downloading dodgy software is a key centralised where software comes from and way that machines become infected. and allocate 16MB of memory. unless you Getting apps repository of software. need a copy of the Linux Mint Cinnamon distro. there and everywhere. ecosystem waiting for you. being used widely in science and industry. Mint ISO file from www.virtualbox. With Up and running removed the worry of getting infected by Linux Mint. More recently. When Linus Linux and not GNU/Linux. be ISO you downloaded. these are called distros for So it’s not such a bad thing to understand. Click Next. The default is 8GB. but if you Mint starts and. The fact is that with gives you access to hundreds of programs and development platform is that it was created by Linux.php programs has always been from a central and download the 32-bit build. available on all Linux platforms. Install it and be aware Memory. you’ll find there – not all good. and how good a development platform it Linux has been its lack of ease of use (Mint is an exception to that rule) but Coding Made Simple | 11 . For extended use. Finish and in which case get With Windows. from its use is going to come at the bottom of the to-do Unlike Windows and Mac OS X. file and directory manipulation software is being run at some level. If you have an older or slower machine. calling the OS Linux rather than on it. glibc is the core C library used in Linux and Unix’) predates Linux by several years. alongside powering list. ease of What’s a distro? runs the majority of the internet. WorldMags. and wealth of the most advanced tools freely effectively create their own OS to distribute. In many ways. Head to www. is still not that usable). The two were put together and GNU/Linux GNU/Linux has far more to do with convenience was born – an operating system using the Linux and laziness than politics – the full title is just kernel and the GNU toolset. you type a command or click an icon – GNU text editors.linuxmint. protected and know your system is 64-bit. Linux that Windows or OS X. You can leave it out or use the Install icon to properly install to store the virtual OS file.

running Linux from this. there weren’t any graphical in the same place. the Terminal system called Wine – but the obscure laptop wireless cards can cause remains an efficient way of controlling Linux. graphics driver from your card’s manufacturer. We’re not really here to talk about using Linux commands. following a is. could wish for. you can also install USB drives. the ones you’ll care about – do have graphical Linux – you can run them via a There are a couple of exceptions: certain more interfaces these days. or hold down C on the Mac – suitable USB thumb drive and.linuxmint. as discussed in the you want to create a DVD copy or redo the Usually. Going back to the early days of This largely means things you’re used to in in every detail but there are a few standard computers and Easy ways to run Linux If you’re not a big Linux user. you don’t need to – Linux is flexible enough some PCs boot from a suitable optical disc by similar boot process as discussed above. and take advantage of over 1. such as the command line. www. so computers were controlled set of programs. Linux open-source community issues. virtual versions to versions running off spare and run this – it looks complex.github. then you’ll probably a DVD. Many of them – or all Studio aren’t directly made for drivers. including writing the ISO file to a Mac system. Mint on a USB drive 1 UNetbootin Linux 2 Install Mint 3 Boot and run To run Mint from a USB stick. command it has to offer. manufacturer. To get this to work. and on most types of hardware – from www. The fact is. and we’ll use the process. However. there’s no need to Linux was developed originally in this type Photoshop and development worry about drivers – they’re built into the of environment. The standard way. once settings. The main stumbling block is ensuring of Linux create space alongside Windows and you’ve got your hands on the Select Diskimage and locate the file message says to press F11 or F12 to select the download tool UNetbootin from http:// in the Download folder. DVDs or on low-cost hardware such virtual PC is pretty easy if you stick to the default Linux on your system directly. a VirtualBox walkthrough. as computers were so Windows won’t work the same in Linux. you need to install the dedicated a consistent set of tools and interfaces to such as LibreOffice. That isn’t to say you can’t add based on Terminal use. When you first turn on a PC. 12 | Coding Made Simple WorldMags. Most versions as the Raspberry Pi. The truth pressing F11/F12. you can virtual optical drive. when you first turn on your PC. and we don’t blame you. Linux Mint will now run. menu and click OK to create the drive. Krita and a whole range of You don’t need to know anything about the freely available and The Terminal Terminal to use Linux on a day-to-day . is to burn it to under Storage that you add the ISO file to the make a dual-boot system. open-source products If you’ve heard of Linux. that offer the might fear or just wonder about is a thing However. One key one is interfaces. but creating a For the brave-hearted. This can be called a a Terminal and use the ls command to list a can also download Valve’s Steam gaming client number of different things. WorldMags. resolve problems. Some PCs have their own unetbootin. which you access through text Linux is that it’s not Windows or Mac OS X. on default. It’s not why we’re here but you called the Terminal.github.virtualbox. we would advise you to at least open same capabilities. Adobe Linux is on the whole.700 Linux games system. It is a direct Linux isn’t Windows interface to the operating system and all of its One thing to keep in mind when you first use Drivers tools. it offers has created its own tools performance. Ensure you have the boot (see previous page). then one area you but it’s good to know that it’s there just in case. So big commercial products where are all the drivers? The cool thing with entirely through text commands. that it can be run in a number of ways beside. so all of its core tools are tools such as Microsoft Visual Linux kernel. Install from http://unetbootin. but they’re generally not required. prompt or command-line interface. Gimp. nor does it offer the same move over from Windows. This installs the live correct USB drive selected in the pull-down specific button – consult your manual or disc ISO file directly to your USB drive. but it’s best practice to do this drive. You’ll need the Mint ISO file from or be questions that often crop up when people much slower. then you have a local copy to hand if selects the USB drive as the boot device. and cd to change directory. you need to ensure your PC be ideal. such as Microsoft Office. while if you want maximum 3D gaming and when it comes to troubleshooting. you top of or alongside most other operating Another option is to install VirtualBox from need to use a write tool such as UNetbootin systems. depending on the directory. you first need a The tool can directly download the Mint ISO You can now boot your PC from the USB USB drive at least 4GB in size – 16GB would image for you. There are more options not want to destroy your existing Windows or usually get it to boot from alternative media by available.

older PCs and people who want modern I free software that can be redistributed by absolutely anyone. which aim themselves at different types of users. While it does lean to the more base to start from. com/steamos Ubuntu moved to a more from standard desktop use to server. ease of use and the large software Mageia based on Debian and is a custom OS that base of Ubuntu. SteamOS is created by Valve mouse enough to get it installed and up and running. businesses. took the crown of the most used and often ranked in the top five distros. The choice can be bewildering. to build from scratch. Mint be the sexiest distro on the block but it’s widely www. such as experienced hands-on Terminal types.github. when they’re deemed stable enough. with a program menu and developers and software vendors. a couple of high-quality distros that can be Arch bones distro.debian. as Fedora only gets Arch Linux but without all the easy-to-use distribution that would be suitable these features when they’re stable. Linux distro world is. It might not SteamOS Based on Ubuntu. It technically the father of the it’s the big-business distro stands alongside Ubuntu and Mint for its ease most number of spin-off distros. complete beginners. This https://manjaro. the company behind the PC digital desktop icons. whereas most largely because it’s another corporate. slower computers. from media editing and so many more. as steampowered. here’s our rundown of the major distro groups. Ubuntu are merged into the Red Hat distribution. Software. they Manjaro in the world. As we mentioned above. Red Hat is a billion-dollar business www. worth mentioning because it funds below). this has lead to a proliferation of different versions of the Linux OS appearing. because it’s hardcore Linux geeks to servers. popular distro after it’s super-stable and can be put to many uses. This is Here’s more of modern. excellent way of testing the latest technologies community has taken the base a huge number of spin-offs have been created because Fedora tends to get them before most of Arch and created a pre-built Linux distro that – both official. From its www. Mint offers the simplicity of distribution system called Steam. a paid-for Linux distro. touch-like desktop. and is. including one used by enterprises and corporations. Q WorldMags. also called a rolling- unofficial – because it became such an easy release distro.redhat. enjoy from a box under your TV. Fedora luck with it. home streaming and version that’s known as Cinnamon. Features are tested in Fedora widely known – Linux distro and. The majority are general-use distros. and a more fancy Showing you how fluid the integrating ashes comes a fresh and powerful desktop One of the older distributions It’s highly unlikely you’ll distro. was spun out of the Debian project to create an isn’t as scary as it drives a front for the Steam Big Picture mode. which eventually went bust. Mint orientated distro that www. The Manjaro for anyone and everyone to use. but there are ways of effectively getting the same Linux that you almost have it’s very stable and has complete repositories technology with a freely available distro. those with fancy interfaces. Debian is also come across Red Hat as desktop and complete software library. but A super-advanced version of It’s really designed for servers and experts. science. an example of how Linux is used in a fully Linux users wanted a traditional keyboard/ sponsored project and is much admired by commercial way. This of software. Debian itself can be thought of a bare. the developers easy interface and easy software also has a long-standing pedigree.mageia. A Ubuntu The Fedora project was big advantage is that Arch’s active community www. Coding Made Simple | 13 . www. for older. but with optimised versions www. such as Ubuntu Server. OpenSUSE technical side of distro releases. There are Linux distros tailored to a host of common uses. popular – or at least the most Linux technology.opensuse. Mageia was the store into one experience that you can created off the back of a long. It’s an complexity. because it comes with just freely created by Red Hat as a test of experts delivers the latest builds of software This is arguably the most platform for cutting-edge before anyone else gets them. Over the years. with an easy installation. which offers a powerful but easy-to-use on the awesome OS that’s exactly what you want. SteamOS is installation. It have gone out of their way to try to make it Another business. but it also means you get an http://getfedora. which means that it is also very means you need to be an expert to have any easy to extend. accessible to all levels of users. n the Linux world. is constantly updated. running commercial Linux distro called Debian Red Hat Linux distro guide A tantalising taste of the many different flavours of Linux. too. but also other distros. of the most popular in the world – Ubuntu (see however. so to help you get started if you’re interested in finding out more about Linux. of use yet manages to bring new features.ubuntu.

and Android games and a device. 48% Exclusive access to the Linux Format subscribers- only area – with 1. & On iOroSid! And Bundle £77 For 12 months SAVE Includes a DVD packed with the best new distros. WorldMags. features and reviews. Instant packed full access on your of the hottest Subscribe to Get into Linux today! Choose your Get into Linux today! package Print £63 For 12 months Digital £45 For 12 months Every issue The cheapest comes with way to get Linux a 4GB DVD Format. 14 | Coding Made Simple WorldMags. apps. lot more. Every new issue in print and on your iOS or Android device. Never miss an .000s of DRM-free tutorials. iPhone distros.

The Prices and savings quoted are compared to buying full priced UK print and digital Coding Made Simple | 15 . Offer ends 12/04/2016 WorldMags. NN4 7BF. WorldMags. Northampton. You will receive 13 issues in a Get all the best in FOSS Every issue packed with features. tutorials and a dedicated Pi section. United Kingdom to cancel your subscription at any time and we will refund you for all un-mailed 3 Queensbridge. If you are dissatisfied in any way you can write to us at Future Publishing Ltd. Prices correct at point of print and subject to change. For full terms and conditions please visit: myfavm. Subscribe online today…

File We can access the management. On a standard Linux Mint installation. Besides account is limited. Linux directory hierarchy. we’ll see commands or that we’ve got pathnames. outside of our home directory – it’s all taken care of by Mint’s 16 | Coding Made Simple WorldMags. text directory one level editing and music playing can all be done with not one single up through the . as such. to jump to the very top of the filesystem and see what the view is like from up there. the Firefox root access. right-clicking on things gives the usual and a rather menacing flashing cursor. For example. which lives at /home/user/ in the menu. we can get more information by using the -l (long) option: $ ls -l This shows us file metadata such as permissions. VLC for playing movies. you won’t have to painstakingly transcribe directory. Music done at the done from the command line. The ~ is shorthand context menus. but a # . viz. and so on. playing a video) – from the command line. access to the manipulation and the Transmission BitTorrent client. not least because it stirs up ignore our hungry cursor no . If required. We find ourselves confronted with menu in the bottom-right. WorldMags. you should issue: $ cd / $ ls We see all kinds of tersely named directories. together with the directories of any other users that are on the system (of which there probably none).. there’s a system tray area to which diverse user@host:~$ applets may be added. our user’s directory. it’s a very powerful way to work. Perusing the aforementioned for our home directory. open windows will appear an arcane prompt of the form in the taskbar. and thanks to If we want to see a listing of all the files in the current Get started with Mint and Python Take a crash course in how to use the command line and follow our guide to create your very first Python program. The /etc/ directory houses configuration files. pretty much anything you might be used to $ ls . So if we do click. you can access is granted through the sudo command (take a look quickly access things by typing a few characters into the at https://xkcd. doing in a GUI can be done – or at least instigated (for we will see a listing of the directory /home/ in which we’ll see example. LibreOffice Writer is a more than adequate word processor for almost there’s generally no reason to do anything with the filesystem everybody’s needs. but we recognise /home/ from being there a couple of sentences ago. The $ shows that we do not have including (but not limited to) the LibreOffice suite. root navigating the program groups in the Places menu. web browser.. We can navigate the directory hierarchy using the cd command. If things were arranged differently. which limits the amount of damage we can do. MS-DOS. last modified date and file size.” and a few others. Let us down the spines of many people. But command line-fu. and start doing some long-repressed memories of darker times. don’t worry. Gimp for image Root is the superuser in Linux and. Downloads. It’s compatible with Microsoft Word files. terminal. we use the ls command. which advanced users enjoy manipulating. operator. we would see The idea of working at the command line sends shivers that a root shell has not a $ in its prompt. M int’s Cinnamon desktop (unlike Ubuntu’s Unity) is We shall begin this tutorial by opening the Terminal cosmetically quite similar to Windows: there’s a program from the menu. So if we type that in and lengthy hit Enter. Much “Pretty much anything you might directories for of your day-to-day computing can be be used to doing in a GUI can be Documents. you will find a plethora of pre-installed software. ownership information. In fact. but apart from that. which temporarily elevates our livesearch box.

package manager. home directory at any time simply by calling cd with no All programming begins with simple text files. There isn’t a reasonable notion for attached to your system. lather and repeat >>> ‘hello there. too. So start the Python 3 interpreter by typing: issue a worldly greeting. And readable code is and then press Return to use our existing file. but that doesn’t stop them $ python3 helloworld. messages as a matter of course. Rinse. the moment of truth – let’s see whether we can do it with strings. the /dev/ names. which is not commence departure from nano with being added or multiplied: If all goes to plan. and our worth adopting the newer 3. It’s known as a Read-Evaluate Print Loop based text editor. Your first ever type error – congratulations! Exit For a more thorough look at the command line. This enables us to shortcuts displayed on the bottom for searching (Ctrl+W). unless you’re morally particular program. If you’ve never used a terminal- returned to us. it’s easy to see how directory contains device nodes representing all the hardware such confusion may arise. friend’ with a cup of tea. For example. as is tradition in such matters. but on Linux. in ‘hellohellohello’ which careless typing is punished. The five-minute introduction at http://community. then you might dismayed to learn that the (REPL). a friendly greeting should be displayed.linuxmint. so you may as well try that everything is a file. Disk partitions get names such as subtracting or dividing by strings. But it’s not just numbers that we can add up – command line. press Y to save necessary but does improve readability. We can return to our program and run it. If >>> ‘hello’ * 3 that didn’t happen.3333333333333333 As before.7 by default but it’s Python programs all use the . and we can arguments. So let’s do that to start with. it’s fun to explore and familiarise get confused with actual programming directives or variable yourself with how Linux does its filing. This is so they don’t program and lived to tell the Mint comes bundled with some pretty wallpapers. so attempting to do that sda1 or sdb2. Q WorldMags. WorldMags. welcome to the world of programming. our newly created directory and create our Python script: $ cd ~ $ cd ~/python $ mkdir python $ nano helloworld. enter Python commands and have the results immediately saving (Ctrl+O) and the Mint currently uses the older Python 2. Type the following into nano: >>> 1 / 3 print(‘Hello world’) 0. Then settle down ‘hello there. we’ve had to enclose our string in quotes. It is possible calculator to perform basic arithmetic: to select text and paste it using the middle mouse button. We call them strings because Python can run our program: they are strings of characters. which you peruse by right-clicking the desktop and choosing Change Desktop Background. There are some helpful guidance and a different prompt: >>>.net Coding Made Simple | 17 . Let’s navigate to new directory in which to store our Pythonic labours. satisfied in the knowledge that you wrote a Notice that we enclose strings in quotes. Now We’ve put spaces around each operator. and the primary video card lives in /dev/dri/ results in an error. and then create a use the humble nano editor to create one. Since strings can contain spaces. terse prompted to save any changes). >>> 9 ** 2 Getting Python to print messages to the terminal is easy – 81 we use the print() function. Programmers encounter diverse error card0. now. The nano text editor is pretty easy to $ python3 work with – you can press Ctrl+X at any time to exit (you’ll be We are presented with some version information. We’re going to create our first Python towards Python programming now. but >>> 32 * 63 positioning of the cursor is done with – and only with – the 2016 cursor keys.x series. For example. interpreter is good for trying out code snippets but it’s no use com/tutorial/view/100. we can use it as we would a standard mouse can’t be used as you might expect here. see the the interpreter by pressing Ctrl+D or typing exit() . ’ + ‘friend’ the editing and running stages until it works. is going to opposed. We’re going to focus our attention for proper coding. That said. all from the command line. This is quite a radical idea to extension. Back at the A Good Thing.

net the UK’s best-selling Linux magazine OUT NOW! DELIVERED DIRECT TO YOUR DOOR Order online at or find us in your nearest WorldMags.Get WorldMags. newsagent or bookstore! .myfavouritemagazines.

coding won’t work correctly. learn to code is almost an essential for the open. Promise. If you knowledge is more than useful – it’s an time to pick up. WorldMags. as a don’t know how to Python. access to every language under your friends are going to be being taught in schools. If you’ve always wanted to learn. helps you get more out of the minutes to create a fun game in Coding Made Simple | 19 . Knowing how Linux itself. laughing at you… Knowing a bit of code helps with using So grab our hand and let’s take just a few We’re not being flippant. can open doors to a new career or which languages are right for you and your source fiend. Other than taking a bit of school curriculum and web development. Be it basic Bash scripting or help you troubleshoot why that webpage projects. jump straight in with our quick-start guide. C oding is the new cool. then see how you can tackle the new knowing how to read a bit of PHP. WorldMags. Coding isn’t scary. there’s also no cost and. the sun is just waiting an apt-get away. particularly now that coding is FLOSS user. all essential skill.

7 with: The IDLE development environment is purpose-built for Python. are not defined for strings. age. Most distributions version yet. converting a string to a float. So open up a terminal (LXTerminal in Raspbian) and start Python 2. wherein Python commands can brackets in the print line are only required in example. the looks something like its target type: for interpreter. then the 3-point-something. >>> age = float(age) The last line shows that we can also So we’ll use it to now to introduce some >>> age multiply strings – division and substraction. immediately. Variables in Python are automatically for strings. tacking the latter string on to As you might suspect. of Python installed. ' is '. type(name) and so on.7 yum. if you can’t find an icon for it. If this returns a result that begins with 2.2) is now Python 3. so you can Data types dictate how data is >>> name = 'Methuselah' easily see the changes you have enacted. let’s introduce the idea of variables: interpreter will show you its value. If that fails to produce the goods. but the interpreter number (one with a decimal part) with: 'BetelgeuseBetelgeuseBetelgeuse' is a great way to test smaller code fragments. using the can be quite subtle. however.0') will work. $ python2 -V pygame) and should be able to install it through While the latest release (1. Installing Pygame. ElementaryOS) with apt-get install idle . start at the command line. notably Arch Linux and the the appropriate package manager – pacman compatible. on the other hand. If. then use the Pygame module to make a simple game. Python can also go the other the division operator / works differently if We can assign values to variables. one of its arguments is a float: Installing Python and Pygame If you’re using Raspbian on the Raspberry Pi everything is fine. float(' . characters) and age is an integer (a whole >>> 'Hello ' + 'world' You can exit the interpreter at any point by number). will bundle the IDLE environment with each version be precise) for this tutorial. and use print but this will only work if the original string Both methods start the Python interactive statements to see them. in which we’ll explore the basics of the language.') function str() .9. pressing Enter name is a string (short for a string of the end of the former. Follow the instructions in the box below to check which version of Python you have and install Get with the program T his is going to be a very gentle introduction to programming in Python. Thus: causes Python to display a global greeting. then check Python 2 Users of other distributions will find a similarly chances are that you already have at least one availability with the command: named package (on Arch it’s called python2- (probably two) versions of Python installed. fundamental coding concepts and constructs. so addition works differently the following incantation: versions. Some distros. zypper or whatever. don’t ship the 2. Here the + operator stands for >>> print('Hello World') assigned a type based on their content. Just as division works differently for first Python program. or an Integrated Development – we can transmute age to a floating point >>> 'Betelgeuse' * 3 Environment (like IDLE). So concatenation. but they don’t do any harm and it’s but float('Rumplestiltskin') will not. That we are able to do this is testament to the power of Python and Pygame – much of the tedium inherent in game work is abstracted away and. then command to install Pygame: then go hunting in your distro’s repos. WorldMags. You can check this by typing 'Hello world' pressing Ctrl+D or using the exit() command. Just typing the variable name into the however. Python version by typing: Users of Debian-derived distributions (including try running the commands $ python -V Raspbian on the Pi) should use the following idle or idle2 . start up IDLE and start a command prompt from there by choosing Python 2.7 Shell from the Window menu. >>> str(123) + str(456) For larger programs. Alternatively. in Python 2 >>> print(name. so let’s do that now. you see $ sudo apt-get install python-pygame or any flavour of desktop Linux. and the effects of this >>> age = 930 can convert ints or floats to strings. be typed at the >>> prompt and evaluated Python 3. for the most part we work with intuitive commands. It is here that we will forge our good practice to write. once we’ve covered some elementary programming constructions. 20 | Coding Made Simple WorldMags. Technically.7 to series by default. ' years old. You can install it on $ python2 Ubuntu (or in this case. Check your default pull it in as a dependency. no distributions are shipping this recently released Fedora 22. so we’ll stick with Python 2 (2. Whether on a Raspberry Pi or a larger machine. it makes sense to work in Some types can be coerced to other types '123456' a text editor. change way. them to our hearts’ content. wherever possible. by carefully typing out ambidextrous code that will run in both floats and ints. We represented internally. First. for example. For example.

Iterating over each list item. For this reason. make your move’ prompts. You Only Get One Match. like the humble for loop below. and the second player either with the goal of forming unbroken lines such as always blocking one side of your chooses a colour or places another black and (horizontal. Another type of loop is codeblock and causes our loop to run. perfect player) can force a win if they start. in fact. these are of no consequence. This one. which is friend/other personality with which to play. Entering a blank (even in the absence of any other coding print() line being issued five times – once for line after the print statement ends the knowledge) that some counting is about to each value in the range. or even subtracting energy from all enemies just smitten by a laser strike. We have for now we just need to know that range(5) usually using four spaces. Work by L Victor code modification: just disobey the first few for a beginner tutorial).6000000000000001 Such quirks arise when fractions have a non-terminating binary decimal expansion. The basic rule set as we’ve modify the code to force use of swap2.000 you can play. happen. so you’ll need to find a Allis has shown that a good player (actually a ‘Player x. vertical or diagonal) of length 5. Yet to become a master takes player one to choose colours. opponent’s ‘open three’ line or obstructing a another white counter on the board and allows Traditionally. with the line. when used in the while loop. It could be appending entries to a list. >>> 3/2 WorldMags. 1. big tournaments use a game. table row or enemy manually would be repetitive and make for Coding Made Simple | 21 . but it’s used in some variations. So our variable count is going consistent. it implies to iterate over each of these values. WorldMags. returns a list consisting of a range of following the for construct ‘belong’ to it. If you don’t indent the second variables is a good idea. … print('iteration #'. Python shouts at you. which will give you only the number of decimal places you require. >>> 1. but Such codeblocks need to be indented. The first player years ago. adding up totals for each row in a table. (Besides. why make life hard for yourself?) Sooner or later. features after the first line. in this case. When you hit Enter There are all kinds of Pygame-powered games. on the board. an integer by the looks like [0. count) integers. you’ll run into rounding errors if you do enough calculations with floats. The range() function. 2. Sometimes. though you can introduced a new variable. You are free to but we’ve gone for the smaller 15x15 board years of practice. the prompt changes to … lots of fireworks but limited means of ignition. They can be worked around either by coercing floating point variables to ints. We haven’t included implemented it heavily favours the starting entirely possible to obey this rule without any an AI (that would be somewhat too complicated player (traditionally black). The Alternatively. programmers desire to do almost the same thing many times over. We’ll see this in practice when we program our Gomoku game later. Players take turns to each place a Bovu game with their desktop. We’ll cover lists in just a >>> 1 >>> 3/2. There’s a few things going on here.5 Funny the difference a dot can make. ‘broken four’. when we mean 2. there are plenty of online versions mitigate against this. and KDE users get the similar starting strategy called swap2. Check it out at http://bit. places two black counters and one white one counter on the intersections of a square grid It’s easy to figure out some basic strategies. but it’s worth being aware of them.0 . the board has 19x19 intersections. Going loopy Often. originated in China some 4. because the interpreter knows that a discrete codeblock is coming and the line(s) >>> for count in range(5): isolation. we have loops.2 * 3 0. Python is all about brevity. or using the round() function. Check out the following doozy: >>> 0. Giving sensible names to your the interpreter. Note that we have been lazy here in typing simply 2. 3. hard-to-read code. Rather than iterating over a How to play Gomoku Gomoku is short for gomokunarabe. 4]. To roughly Japanese for ‘five pieces lined up’. which you can verify in use as many as you like so long as you’re name of count .ly/LXF202-onematch.
list, our while loop keeps going over its code 0 up to and including 99, which could equally really only scratching the surface with some
block until a condition ceases to hold. In the well be achieved with range(100) in Python 2. basic graphics and font rendering. We need
following example, the condition is that the However, the concept is more powerful – for a single function, exit() , from the sys
user claims to have been born after 1900 and example, we can get a list of squares using the module so that we can cleanly shut down
before 2016. exponentiation (to the power of) operator ** : the game when we’re done. Rather than
>>> year = 0 >>> squareList = [j ** 2 for j in range(100)] importing the whole sys module, we import
>>> while year < 1900 or year >= 2015: And after that crash course, we’re ready to only this function. The final import line is just
… year = input("Enter your year of birth: ") program our own game. You’ll find all the code for convenience – we have already imported
… year = int(year) at, so it pygame, which gives us access to pygame.
Again the loop is indented, and again you’ll would be silly to reproduce that here. Instead, locals , a bunch of constants and variables.
need to input a blank line to set it running. we’re focusing on the interesting parts, in some We use only those relating to mouse,
We’ve used the less than ( < ) and greater than cases providing an easier-to-digest fragment keyboard and quitting events. Having this
or equal to ( >= ) operators to compare values. that you can play with and hopefully see how it line here means we can access, for example,
Conditions can be combined with the logical evolves into the version in the program. To dive any mouse button events
operators and , or and not . So long as year in and see the game in action, download with MOUSEBUTTONDOWN without
has an unsuitable value, we keep asking. It is and copy it to your home directory, prefixing it with pygame.locals .
initialised to 0, which is certainly less than and run it with:
1900, so we are guaranteed to enter the loop. $ python2 It’s all in the (Py)game
We’ve used the input() function, which returns On the other hand, if you want to see Throughout the program, you’ll notice that
whatever string the user provides. This we some code, open up that file in IDLE or your some variables are uppercase and some are
store in the variable year , which we convert to favourite text editor. Starting at the first line is a not. Those in uppercase are either
an integer so that the comparisons in the reasonable idea… It looks like: from pygame.locals or should be
while line do not fail. It always pays to be as #!/usr/bin/env python2 considered constants, things that do not
prudent as possible as far as user input is This line is actually ignored by Python (as change value over the course of the game.
concerned: a malicious user could craft some are all lines that begin with # ) but it is used by Most of these are declared after the import
weird input that causes breakage, which while the shell to determine how the file should be statements and govern things like the size of
not a big deal here, is bad news if it’s done, say, executed. In this case we use the env utility, the window and counters. If you want to
on a web application that talks to a sensitive which should be present on all platforms, to change the counter colours, to red and blue,
database. You could change 1900 if you feel find and arm the Python 2 executable. For this for example, you could replace the values
anyone older than 115 might use your program. nifty trick to work, you’ll need to make the of WHITE and BLACK with (255,0,0)
Likewise, change 2015 if you want to keep out file executable, which is achieved and (0,0,255) respectively. These variables
(honest) youngsters. from the command prompt (assuming you’ve are tuples (a similar structure to a list, only it
copied the file to your home directory, or can’t be changed), which dictate the red,
The opposite of listless anywhere you have write permission) with: green and blue components of colours.
We mentioned lists earlier, and in the exciting $ chmod +x Next you’ll see a series of blocks
project that follows we’ll use them extensively, You’ll find you can now start the game with beginning with def: – these are function
so it would be remiss not to say what they are. a more succinct: definitions and, as is the case with other
Lists in Python are flexible constructions that $ ./ codeblocks in Python, they are demarcated
store a series of indexed items. There are no Next we have three import statements, by indentation. The initGame() function
restrictions on said items – they can be strings, two of which ( pygame and sys ) are initialises the play area. Here’s a simple
ints, other lists, or any combination of these. straightforward. The pygame module makes version that shows what this function does:
Lists are defined by enclosing a comma- easy work of doing game-related things – we’re WIN_WIDTH = 620
separated list of the desired entries in square GRID_SIZE = (WIN_WIDTH) / 14
brackets. For example: WHITE=(255,255,255)
>>> myList = ['Apple', 'Banana', 'Chinese BLACK=(0,0,0)
Gooseberry'] BGCOL=(80,80,80)
The only gotcha here is that lists are zero- def initGame():
indexed, so we’d access the first item of our screen.fill(BGCOL)
list with myList[0] . If you think too much like a for j in range(15):
human, then 1-indexed lists would make more pygame.draw.line(screen, WHITE, (0, j
sense. Python doesn’t respect this, not even a * GRID_SIZE), (WIN_WIDTH, j * GRID_
little, so if you too think like a meatbag, be SIZE))
prepared for some classic off-by-one errors. pygame.draw.line(screen, WHITE, (j *
We can modify the last item in the list: GRID_SIZE, 0), (j * GRID_SIZE, WIN_
>>> myList[2] = 'Cthulhu' WIDTH))
Lists can be declared less literally – for pygame.init()
example, if we wanted to initialise a list with pygame.display.set_caption(‘LXF Gomoku’)
100 zeroes, we could do: screen = pygame.display.set_mode((WIN_
>>> zeroList = [0 for j in range(100)] WIDTH,WIN_WIDTH))
This is what is known as a list comprehension. initGame()
Another example is Many tense counter-based battles can be pygame.display.update()
>>> countList = [j for j in range(100)] had with your very own self-programmed If you add the three import lines to the
which results in a list containing the integers version of Gomuku. beginning of this, it is actually a perfectly

22 | Coding Made Simple the display, hence the last line. track of the game, we use a two-dimensional
Astute readers will notice that the grid square array (a list of lists) in the variable grid .
overruns ever so slightly at the edges. This This is initialised as all 0s, and when a player
is because drawing 15 equispaced parallel lines makes a move, a 1 or a 2 is entered accordingly.
divides the board into 14, but 620 (our window The first job of the tryCounterPlace() function
size) is not divisible by 14. However, when we is to reconcile the mouse coordinates where
add in some window borders – since we want the user clicked with a pair of coordinates with
to place counters on the edge lines as well – which to index the grid variable. Of course, the
620 turns out to be a very good number, and user may not click exactly on an intersection,
we were too lazy to change it. Although rough so we need to do some cheeky rounding here.
around the edges, it’s still testament to If the player clicks outside of the grid (e.g. if
Pygame’s power and Python’s simplicity that they click too far above the grid, so the y
we can do all this in just a few lines of code. coordinate will be negative) then the function
Still, let’s not get ahead of ourselves – our returns to the main loop. Otherwise, we check
game still doesn’t do anything. that the grid position is unoccupied and if so
Joel Murielle’s graphical Gomoku is
draw a circle there, and update our state array
available from the Pygame website.
Pygame takes all the pain out of working
Finer points grid . A successful move causes our function to
From here onwards, we’ll refer to the actual return a True value, so looking at line 111 in the
with sprites – notorious troublemakers.
code, so any snippets we quote won’t work in code, we see this causes the next player’s turn.
isolation – they’re just there to highlight things. But before that is enacted, by
valid Python program. The initGame() You’ll notice that the FONT variable isn’t the updatePlayer() call at the top of the loop,
function doesn’t do anything until it is called defined with the other constants; this is we call the checkLines() function to see if the
at the last line, by which time we’ve already because we can’t use Pygame’s font support latest move completed a winning line. Details of
initialised Pygame, set our window title, and until after the Pygame’s init() method has how this check is carried out are in the box.
set the window size to 620 pixels. All been called. Let’s look at the main game loop When a winning counter is detected by
variables set up outside of function right at the end of the code. The introductory our state-of-the-art detection algorithm,
definitions – the five all-caps constants at clause while True: suggests that this loop will the winner() function is invoked. This replaces
the beginning and screen – are accessible go on for ever. This is largely correct – we want the text at the top of the screen with a
inside function definitions; they are known to keep checking for events, namely mouse message announcing the victor, and the
as global variables. Variables defined inside clicks or the user clicking the exit button, until gameover loop is triggered. This waits for a
function definitions are called ‘local’ – they the game is done. Obviously, we exit the loop player to push R to restart or rage quit. If a
cease to exist when the function exits, even when the application quits – clicking the restart is ordered, the player order is preserved
if they have the same name as a global button triggers a QUIT event, which we react and, as this is updated immediately before
variable – again, something to be aware of in to with the exit() function from the sys checkLines() is called, the result is that the
your future coding endeavours. The variable package. Inside the main loop, the first thing loser gets to start the next round.
screen refers to the ‘canvas’ on which our we do is call the updatePlayer() function, This is a small project (only about 120 lines,
game will be drawn, so it will be used which you’ll find on line 32. This updates the not a match for the 487-byte Bootchess you
extensively later on. The initGame() text at the top of the screen that says whose go can read about at
function’s first act is to paint this canvas a it is, drawing (‘blitting’) first a solid rectangle so technology-31028787), but could be extended
delightful shade of grey (which you’re very any previous text is erased. in many ways. Graphics could be added,
welcome to change). Then we use a loop Next we loop over the events in the events likewise a network play mode and, perhaps
to draw horizontal and then vertical lines, queue; when the player tries to make a move, most ambitiously, some rudimentary AI could
making our 15x15 grid. None of this artwork the tryCounterPlace() function is called, with be employed to make a single-player mode.
will appear until we tell Pygame to update the mouse coordinates passed along. To keep This latter has already been done…

Reading between the lines
Part of Key Stage 2 involves learning to elements to its right have the same value. In check row positions further right than this
understand and program simple algorithms. Python, it would look like this: because our algorithm will reach out to those
We’ve already covered our basic game flow positions if a potential line exists there. Our
algorithm – wait for a mouse click (or for the for j in range(15): variable idx effectively measures the length of
user to quit), check whether that’s a valid move, for k in range(10): any line; it is incremented using the +=
check if there’s a line of five, and so on. At the pl = grid[j][k] operator, short for idx = idx + 1 .
heart of that last stage lies a naïve, but if pl > 0: The algorithm is easily adapted to cover
nonetheless relevant, algorithm for detecting idx = k vertical and diagonal lines. Rather than four
whether a move is a winning one. while grid[j][idx] == pl and idx < 14: separate functions, though, we’ve been clever
Consider the simpler case where we’re idx += 1 and made a general function lineCheck() ,
interested only in horizontal lines. Then we if idx - k >= 5: which we call four times with the parameters
would loop over first the rows and then the # game winning stuff goes here necessary for each type of line checking. Said
columns of our grid array. For each element, parameters just change the limits of the for
we would check to see that it is non-zero (i.e. Note that the inner loop variable k reaches a loops and how to increment or decrement grid
there is a counter there) and whether the four maximum value of only 9. We do not need to positions for each line direction. Coding Made Simple | 23
Languages: An overview
ne of technology’s greatest curly brackets used by so many other allocate memory as it is required
achievements was IBM’s Fortran languages for containment purposes. Likewise, and free it when it’s no longer
compiler back in the 1950s. It there’s no need to put semicolons at the end of required. Failure to do so
allowed computers to be programmed using every line. Python has a huge number of extra means that programs
something a bit less awkward than machine modules available, too – we’ve seen Pygame, can be coerced into
code. Fortran is still widely used today and, and our favourite is the API for programming doing things they
while some scoff at this dinosaur, it remains Minecraft on the Pi. shouldn’t.
highly relevant, particularly for scientific Unfortunately, 40
computing. That said, nobody is going to Beginner-friendly years of widespread C
start learning it out of choice, and there are Other languages suitable for beginners are usage have told us that
all manner of other languages out there. JavaScript and PHP. The popularity of these this is not a task at which
Traditionally, you have had the choice comes largely from their use on the web. humans excel, nor do we seem
between hard and fast languages – such as JavaScript works client-side (all the work is to be getting any better at it. Informed by
Java, C and C++ – or easy and slower ones, done by the web browser), whereas PHP is our poor record, a new generation of
such as Python or PHP. The fast languages server-side. So if you’re interested in languages is emerging. We have seen
tend to be the compiled ones, where the code programming for the web, either of these languages from Google (Go), Apple (Swift)
has to be compiled to machine code before it languages will serve you well. You’ll also want to and Mozilla (Rust). These languages all
can be run. Dynamic languages are converted learn some basic HTML and probably CSS, too, aim to be comparable in speed to C, but at
to machine code on the fly. However, on some so you can make your program’s output look the same time guaranteeing the memory
level, all programming languages are the same nice, but this is surprisingly easy to pick up as safety so needed in this world rife with
– there are some basic constructs such as you go along. PHP is cosmetically a little malicious actors.
loops, conditionals and functions, and what messier than Python, but soon (as in The Rust recently celebrated its 1.0 release,
makes a programming language is simply how Matrix) you’ll see right through the brackets and maybe one day Firefox will be written
it dresses these up. using it, but for now there are
For those just starting
coding, it’s simply baffling.
“Although any language will by a number of quirks and
pitfalls that users of
Opinions are polarised on what
is the best language to learn
turns impress and infuriate you, traditional languages are
likely to find jarring. For one
first of all, but the truth is that Python has a lot going for it.” thing, a program that is
there isn’t one, though for very ultimately fine may simply
small people we heartily recommend Scratch. and dollar signs. It’s also worth mentioning refuse to compile. Rust’s compiler aims for
Any language you try will by turns impress and Ruby in the accessible languages category. It consistency rather than completeness –
infuriate you. That said, we probably wouldn’t was born of creator Yukihiro Matsumot’s desire everything it can compile is largely
recommend C or Haskell for beginners. to have something as “powerful as Perl, and guaranteed, but it won’t compile things
There is a lot of popular opinion that favours more object-oriented” than Python. where any shadow of doubt exists, even
Python, which we happily endorse, but many Barely a day goes by without hearing about when that shadow is in the computer’s
are put off by the Python 2 versus 3 some sort of buffer overflow or use-after-free imagination. So coders will have to jump
fragmentation. Python has a lot going for it: it’s issue with some popular piece of software. Just through some hoops, but the rewards are
probably one of the most human-readable have a look at All of there – besides memory safety and type
languages out there. For example, you should, these boil down to coding errors, but some are inference, Rust also excels at concurrency
for readability purposes, use indentation in easier to spot than others. One of the problems (multiple threads and processes),
your code, but in Python it’s mandatory. By with the fast languages is that they are not guaranteeing thread safety and freedom
forcing this issue, Python can do away with the memory safe. The programmer is required to from race conditions.

Programming paradigms and parlance
With imperative programming, the order of have its own variables (attributes) and its own is not for the faint-hearted. This very abstract
execution is largely fixed, so that everything code (methods). This makes some things style is one in which programs emphasise
happens sequentially. Our Gomoku example is easier, particularly sharing data without more what they want to do than how they
done largely imperative style, but our use of resorting to lengthy function calls or messy want to do it. Functional programming is all
functions makes it more procedural – global variables. It also effects a performance about being free of side-effects – functions
execution will jump between functions, but toll, though, and is quite tricky to get your head return only new values, there are no global
there is still a consistent flow. around. Very few languages are purely OO, variables. This makes for more consistent
The object-oriented (OO) approach extends although Ruby and Scala are exceptions. C++ languages such as Lisp, Scheme, Haskell
this even further. OO programs define classes, and Java support some procedural elements, and Clojure. For a long time, functional
which can be instantiated many times; each but these are in the minority. Functional programming was the preserve of academia,
class is a template for an object, which can programming (FP) has its roots in logic, and but it’s now popular within industry.

24 | Coding Made Simple

which will provide these additional peripherals. as evidenced by industry consistently reporting difficulties in finding suitably qualified applicants for The FUZE box gives you tech jobs in the UK. It’ll be disappointing if the from the concerned parents and confused particularly like setups such as the FUZE box. then education secretary Michael Gove acknowledged that the current ICT curriculum was obsolete – “about as much use as teaching children to send a telex or travel in a zeppelin”. but rather There are also many free resources on the Speaking of tiny things. the BBC will distribute 20-pin edge connector. Yes. Rightly not to mention a glorious array of Pi cases as though this compilation all takes place on or wrongly. and it’ll plug straight into sensors. Python. The Micro:bit features a web. too. directions in which one can seek help. all-in-one device. and code entered here your progeny hollers at you (that’s what kids do. world. learning the dark example. which connects it Python documentation) are a little dry for about a million ‘Micro:bit’ computers to Year 7 to the Pi or another device. programmed in a number of languages genuinely thrilled that children as young as Coding Made Simple | 25 . the Kano. to stress that the device is in no way intended Linux Format – Coding in the classroom I n September 2014. the Raspberry Pi (see and training for this venture. the more about it at www. then you can get The devices have gravity and motion claiming it is vital for understanding how the one for about £25. mediacentre/mediapacks/microbit. Microsoft on their Master Skills to lesser teachers easy enough to get to grips with. the ICT must be compiled before being downloaded to the Micro:bit. the UK embarked on a trailblazing effort that saw coding instilled in the National Curriculum. clarification on the finer details are sketchy. many private firms will benefit available to protect it from dust and bumps. WorldMags. But there are more wholesome albeit chunkier. You can find out curriculum. and we will enjoy the BBC Newsnight interview with page 82 for more) is another great way to are relieved to hear it will not tie the the then Year of Code HDMI cable and rings that could connect further Learning opportunities possibly a wireless adapter. we’re Ethernet cable to your router is not an option. it’s all too easy to end up in cable. billed as a DIY computer). then. but machines can work in tandem. Coding skills are much sought after. if trailing an sensors or contraptions. They can be Criticism and mockery aside. “Without any coding. If you’re willing to product to its Windows 10 platform. Such a pairing these skills alongside their offspring. SD card. even as we speak. Of For one thing. your telly. Raspberry Pi’s tiny form factor is appealing. The arts of syntax. you’ll need to scavenge a some buttons. but it seems points of recursion and abstraction. to compete with the Raspberry Pi. – a visual programming language. wherein she provide a learning platform. “What’s the plural of mongoose?” and curriculum was ‘as much use as present. despite settle for the older B+ model. amidst the pre-launch hush (though it should be then follows through seeking teaching kids to send a telex’. admits not knowing how to code. when based. Microsoft-provided code editors are all web- Fear now. requiring instead to be programmed 400 ‘Master Teachers’ who could then pass and distributions such as Mint and Ubuntu are from a more capable device. induced tiny hell. The device – indeed the combination WorldMags. they means of communicating with the outside Linux install will provide a great platform to cannot function as standalone computers. have no means of output besides a 5x5 LED will be necessary for the Micro:bit to have a Refurbishing an old machine with a clean array. to compile locally is offered. code editors can’t be used offline or no option kids resulting from the new computing which embed the Pi into a more traditional. When the initiative was announced in 2013. is generously providing the software around the country. Unlike the Raspberry Pi.” available in schools now). and most of this would be spent on training just do just this. Some of them (such as the official new learning regimen. so that the kids. These are even smaller than the Pi. There are five GPIO keyboard. there are many kits available (for including C++. JavaScript and Blocks five are. as well as Bluetooth and world works. everything you need to start The ‘Year of Code’ was launched to much fiddling with registers or making GPIO-based mischief. you’ll always find great but with a heavy rotation of USB devices Micro:bit spokesbods have been keen tutorials monthly in magazines such as thrown in. Far more important was imparting coding wisdom unto the young padawans. though this was slightly quelled as details emerged: a mere pittance was to be added to the existing ICT allocation. We Microsoft servers. All the software you need is free. semantics and symbolism. to coincide with the to complement it. but we’d encourage adults to learn pupils. fanfare. ye parents. At apparently).com. Fans of schadenfreude Besides a stray PC.

If you have the time and some knowledge. for five. at least as far as how governmental blunder. too. Not all of them are going to be thrilled at having to program them. you’ll get a teacher to maintain order and provide defence against any potential pranksters. provides the The Code Club phenomenon is spreading with more on the way. while these days kids expect them to provide a constant barrage of entertainment in the form of six-second cat videos or 140-character social commentary. This kind of community thinking is very much in the spirit of open source. It’s an ambitious introduces core ideas. any entry barrier to getting into coding is fine by us. You can find out more at material. then a term of web design (HTML and CSS). Projects are carefully designed to keep kids interested: they’ll be catching ghosts and racing boats in Scratch. Code Club also provides three specialist modules for teachers whose duty it is to teach the new Computing curriculum. Back then. candidates will be represented as a string of bits. concluding with a final term of grown-up Python six-year-olds. if not entirely obliterates. requires students to learn at least Throughout the The final 11-year-olds and consists of two terms of Scratch programming. All the tutorials are prepared for you and if you can persuade a local primary school to host you. and doing the funky Turtle and keeping tabs on the latest Pokémon creatures in Python. to introduce the idea of formalising .net of the device and the Pi – has a great deal of potential but there exists some scepticism over whether anything like the excitement generated by the 1982 launch of BBC Micro will be seen again. armed with commercial interest and corporate control. Boolean algebra. functions information security – skills the want of which studying Kohonen or Knuth alongside Kant. providing 26 | Coding Made Simple WorldMags. students will coding populace. or binary arithmetic. and data types. and pupils two programming languages and understand also learn the vital skills of online privacy and are learning Python alongside Mandarin. Q Code Clubs There are also over 2. You will require a background check.codeclub. and schools (or other kind venues) worldwide. the scheme will also lead data. Alongside this. such as loops and different types of information can all be project. WorldMags. £100. You’ll now find them as far afield www. They will also necessary to address the skills shortage in learning to use web services and how to gather gain insights into the relationship between this area. to much-needed diversification among the aged 11 to 14. The project materials clubs across the UK. but perhaps such a radical step is variables. computers were new and exciting. The Cortex M0 ARM The first. The second stage (ages 7 to 11) information theory. though. provide space and resources for this noble extracurricular activity. it’s well worth volunteering as an instructor. Algorithms battery-powered Code Club. But anything that lowers. Get with the program The syllabus comprises three Key Stages. Students will also touch on has led to many an embarrassing corporate or then we’ll be thrilled.000 volunteer-run code an access-for-all gateway to coding free from as Bahrain and Iceland.000 courtesy of Google. have already been translated into 14 languages. If it works out. We also look forward to ne’er-do-well students hacking each other’s Micro:bits or engaging them in a collaborative DDOS attack on their school’s infrastructure. With luck. to name but a few. The Code Club syllabus is aimed at 9. covers processor is at the heart of the algorithms in a very general sense. for secondary students hardware and software. will be described in terms of recipes and schedules. The home of technology .

We’re going to look at a more general purpose tool called Now we’ll change up our program slightly.” called name interface’s major containing the string features opposite. ‘Dave’ . We have declared a variable run-through of the quantities that. and you probably realise that the same effect could be achieved just by changing ‘world’ to ‘Dave’ in the original program – but there is something much more subtle going on here. Geany is pretty basic as far as IDEs go – in fact. so we have no need for this. such as IDLE for Python (see page equally well call /usr/bin/python3 directly. going to happen. Our print() function above does our prompting for us. So our Python 3 code should begin: huge project involving complex build processes. which will be used to prompt the user for input. it’s more of a text editor on steroids than an so make our greeting a little more customisable. . You probably knew what was to our python/ directory to select the file. This is why #!/usr/bin/env python3 integrated development environments (IDEs) exist – so that The env program is a standard Linux tool that is always the editing. Before you start. A tab 28 | Coding Made Simple WorldMags. name) $ sudo apt-get Note the space install geany after Hello . Python is terribly fussy about indentation. but it is more than sufficient for this tutorial. linking and debugging can all take accessible from the /usr/bin/ directory. vary. It keeps track of place on a unified platform (and you have a single point at where various programs are installed. vary. We’re going to Geany. Before we go further. unless you have some personal You’ll find Geany in Mint’s repositories. On Mint. running and debugging even The grown-up way to begin Python files is with a directive simple programs can rapidly become painful. you still should be. our shebang could for a particular language. Edit the code IDE. We can test our code by pushing F5 or clicking the py program from before: Select File > Open and then navigate Run button (see annotation). In the terminal window. by show how variables can be used as placeholders. and even if it wasn’t. because this can differ which to direct programming rage).net Get started with IDEs Speed up your programming workflow by using Geany. T he cycle of editing. which level we are at in a nested loop. The input() function can also be given a string argument. it’s worth talking about tabs and spaces. so you can install it grievance) so that it looks like this: either from the Software application or by doing: name = ‘Dave’ $ sudo apt-get update print(‘Hello ’. you need to install Geany from Mint’s repositories. a lightweight integrated development environment. 92). which takes a line of user input and returns that string to our program. input() . and in doing some measures. We can start by opening up our helloworld. So known as a shebang. Variables allow us to abstract away specifics and deal with quantities that. Correctly indenting code makes it easy to demarcate code blocks – lines of code that collectively form a function or loop – so we can see. WorldMags. or whatever characters you can muster. type your name. This is a line that tells the shell how it imagine how ugly things can get when working on a ought to be run. We can elaborate on this concept a little more by introducing a new function. compiling. Change the first line to name = input() and run your code. (keeping the shebang above. and press Return. Some IDEs are tailored wildly from distro to distro. Now start Geany from the “Variables allow us to abstract otherwise the output would look a Places menu. The program took your input and courteously threw it back at you. well. There’s a quick away specifics and deal with bit funny. for example.

case. but just because an editor renders a tab character as this clause – so long as they respect the indentation. space bar eight times. We can put as many lines as we want in editor. we can also use likely to break it. The code we’ve just introduced is first. Python happily works with files that The else block is run when the condition is not met. though. function returns the length of a string. the else block from above can be if name == ‘Agamemnon’: included. The reason Python is fussier than other languages about Note that strings are case-sensitive. Of course. recognition. name) perhaps the PyDev plugin for Eclipse. you’re typing. don’t forget IDLE. If the you choose to do it. Geany opens your recent files in tabs. As well as testing for equality. Code folding Code editor Code folding is de rigueur for any IDE. and keywords are highlighted. but it saves happier with a couple of terminals open – you wouldn’t be the you considerable effort. WorldMags. say. The len() disposal to illustrate this. So if you’re working on a more involved. Tabs By default. When the program finishes or breaks. represents a fixed amount of white space decided by the text greeting is issued.. which is packaged with Python – highly readable – we use the == operator to test for equality we cover it in the Raspberry Pi chapter on page 92. If you want to else: check out something more advanced. we wish you good luck with your condition is met (ie Agamemnon is visiting). We need some more coding concepts at our the greater than ( > ) and less than ( < ) operators. you can study any output or error messages here before closing it. Let’s start with the if conditional. Python eight spaces. multi-file project. Or maybe you’re It can be hard to get used to the autotabbing. So just adding a random indent to your code is of our program. Q WorldMags. so someone called these matters is because indentation levels actually form part agamemnon would not be recognised as an old acquaintance of the code. variables and imports in the current The Geany interface Run button The Run button (or F5) will save and execute your Python program in a terminal. – in this use tabs or spaces. see PyCharm or print(‘Hello ’. Clicking on the + or . However and use a colon to indicate a new code block is starting. Agamemnon uses it. so long as they’re consistent. Also. print(‘Ah. together with the line on which they are declared. noting that Geany print(‘My what a long name you have’) automatically indents your code after the if and else Now anyone whose name is 10 characters or more gets statements. if that behaviour is still desired. related code is just one click away.will reveal or collapse Geany is good at guessing the language the block of code on the adjacent line. so we could instead Suppose we want our program to behave differently when make our if statement: someone named. too. Clicking will take you straight there. Symbols The Symbols tab lists all the functions.) There are many other IDEs besides Geany.. my old Coding Made Simple | 29 . the program behaves exactly as it had done before. that doesn’t make it equivalent to pushing the knows that they all should be run when the condition is met. then a special continued adventures in Linux and coding. The main area where you enter or edit code. Replace the last if len(name) > 9: line of our code with the following block. .net WorldMags.

...................32 Functions and objects .................................................................................. 40 Recursion .................................................................................................................................................................. 52 Common mistakes Coding basics Now you have the tools........ it’s time to grasp the basics of coding Lists ......................... 34 Conditionals ....................................................... 46 Integers .......................................... 38 Program structure ...... 48 Using loops .......................................................................................... 44 Sorting algorithms .................. 54 Coding Made Simple | 31 ........................................... 36 Variables ......................................................................................... 50 Compilers ........................

for instance. any particular concept. “baked beans”] peculiarities of your chosen language. the process a trip to the supermarket. And that’s on top of the syntax and >>> shoppinglist = [“milk”. Both methods work. but most prefer the convenience. 32 | Coding Made Simple WorldMags. When someone begins coding. It’s for this reason that some of the earliest lists are stacks. This is where lists start to become interesting. provide in this book. But lists are . and a list is just another example. It might not be important what that order is. but they’re still useful for temporarily holding learning values. following one to the new item. Programmers like to call loosely. because We’d like to make this challenge slightly easier by looking the method for adding and removing values can help to at basic approaches that apply to the vast majority of define the list’s function.append(“soup”) a great helper. for example before retrieving them in reverse order Python. For example. Some languages like to make either by following an example project. In Python. with values either pushed on to the end or pulled off. related snippets of information a data structure. because each value is itself One of the best approaches is to just start writing code. beginning with the concept of lists. the like a stack of cards. for example. there’s an overwhelming number of different ideas to understand. to add a new item to the end of a list because all the You don’t get far with any moderately complex task application has to do is link the last element to the new one. which are more processor intensive. “bread”. it’s faster for the CPU circumstances and languages. such as the ones we that distinction. And our first target is lists. A list is a convenient place to store loosely-related the insertion point. and they’re the only real shoppinglist list. then links both the preceding item and the snippets of information. you could create a list of those values with the following line: into solutions. you can execute a function called append to programming the same effect: environment is >>> shoppinglist. without a list. the Stacks and queues relationship might be something as simple as food – ‘milk’. This is technically a list of lists. such as a chunk of memory. or by piecing together examples from Each of these items has been added to the freshly created documentation. And list logic in code is just like in first splits the links between the two items on either side of real life. WorldMags. it would make much I explaining the basic programming concepts. or a browser’s ‘Back’ button. Processing speed means that stacks aren’t a necessity If you’re any more. With a shopping list. and one of the first way to get to grips with the problems and complications of things you often want to do is add new values. but it’s the order that differentiates a list from a random array of values. t’s difficult to know where to start when it comes to remind you what’s on your shopping list. the values you put on the list first are the 1 2 3 4 5 first out (FIFO). rather than lists with values inserted and removed from the middle. in the Eric In Python. If you were writing an application to of data it contains is in a specific order. The list could be your terminal command tab completion history. The most important characteristic for a list is that the chain ‘bread’ and ‘baked beans’. absorb and eventually turn more sense to put these values together. POP PUSH A QUEUE With a queue. whether that’s a holiday to Diego Garcia or If you insert an item into the middle of a list. a list – a string of Get to grips with Python lists Let’s start by exploring some of the fundamental ideas behind programming logic.

There are many ways to use a queue. but the most in fact. and a great deal. interpreter – although they are. It’s perfectly possible. ‘bread’. But You can change the order in lots of ways. and should lines of Python Coding Made Simple | 33 . and explanation in a script or assigning to popping off a value from the end. ‘bread’. contrast to a stack. print tip PUSH The for loop here gives a value to x that steps from 0 to We’re using Python len(shoppinglist). WorldMags. But at their heart. because simply typing shoppinglist will output the list’s contents. This is in a script and something you can try together. the values you put you’re unlikely to grasp the logic. If you’ve got on these pages. ‘milk’. Q WorldMags. 0 is the real first element in a list and your own code. You can output a value from any point in the array. operations. it just uses an argument for the pop command. The symbols. known as FIFO. Typing shoppinglist[1]. ‘milk’. and because lists are shorthand for so many different data types. it can be removed easily with pop: >>> shoppinglist. a great language for beginners. ‘soup’. >>> shoppinglist [‘apples’.pop(0) how the language works. and you can now start typing following will remove the first item in the list. This is especially true of Python – because it has so many convenience functions. and they help to distinguish between another variable. but Python’s 4 sort method is tough to beat: >>> shoppinglist every concept we discuss works with other languages. in our case the word soup. regardless of your them. output ‘milk’ from the interpreter: This is a brilliant way of learning >>> shoppinglist.. And if you want to output the list by treating it as an array. the queues. ‘soup’] too – it’s just a matter of finding >>> shoppinglist. too. and can turn lists into super-flexible data types. which is a method to return the length of for our examples a list. such as popped off the stack. and now we hope you’re wondering what all the fuss is about. ‘soup’] If you can follow the logic of that simple piece of code. Python is an exception. These symbols represent the cursor immediately. interchangeable. and that’s the best place to start. for entire list. The main problem is that it can get complicated quickly.. shoppinglist[x] POP .net This will add soup to our shopping list. for example. These offer a big advantage over the original primitive programming in general. you might wonder why there comprehensive Python tutorials. When we’ve added it to our shop. you might have to construct something like: A STACK >>> for x in range(0. but for other languages. unless you know what they do. rather than needing any This would require the same amount of relinking as of Python’s interactive interpreter. the processing limitations in mind. ‘milk’.sort() for the functionality. value is output to your terminal isn’t an option to pop the first value off the stack.append(“apples”) the correct syntax >>> shoppinglist 3 [‘baked beans’. just a chain of values. but you will obviously lose the immediately by typing in to the current state of your code. You can quit the turns a list into something called a ‘queue’ – the values you something you might want to build into interpreter by pressing [Ctrl]+[D] put on the list first are first out. It’s doesn’t have any special commands for accessing the first at this point you’ll see the cursor value. which is LIFO. Errors in a Modern lists single line are far easier to spot than Lists are no longer limited by processor speed to stacks and those in a 20-line script that’s being run If you’re learning to program. and most modern languages and frameworks for the first time. Each location in the list is output as we loop through it in because it’s the order they were added (FIFO). As with nearly shuffles through these values from beginning to end.pop() Using Python’s interpreter If you’re running these commands from the interpreter. Python is particularly good at this. With a stack. As we Launching the interpreter is as simple explained. handles logic chosen language. There’s really nothing more to it. the only difference between a queue and a stack is as typing python from the command where the pop value comes from. 2 then it’s safe to assume you’ve grasped the logic of lists.. as well as in our more len(list) to return the length of a list. ‘baked beans’. making 1 the second. obvious is to preserve the order of incoming data. If you execute a function that you’ll see the contents of the last value in the list as it’s symbols preceding the snippets of code returns a value. and includes plenty of built-in functions for manipulating lists without having to write all things code-wise. you typically need to construct a simple loop that instance. they’re on the list last are the first out (LIFO). and you can also get Python interpreter can teach you provide a vast number of handy functions for dealing with a really good feel for how Python. ‘bread’. [‘baked beans’. it can be difficult 1 working out what might be happening in any one chunk of code..len(shoppinglist)): Quick . as well as experimenting with syntax and the concepts you’re working with. will return the second value in the list. ‘apples’] >>> shoppinglist. which is why Python line without any further arguments. You might wonder why we have three > and data.

because a function is a kind of list for code logic. This led to one of the most primitive hacks of the day. there’s a good chance it was written in BASIC – a language Functions also make program flow more logical and easier embedded within the ROMs of many of the home computers to read. But you’d have needed to be a wealthy Acorn Archimedes owner to get those facilities out of Understanding functions & objects After introducing the concept of lists. jump to the new code. but while you’re constructing your project. with many systems projects. it’s a basic example of a function if you can execute it from another part of your project. functions are independent blocks of code that are designed to be reused. Functions can also return a value. you need to remember where you are in the code. 34 | Coding Made Simple WorldMags. and written on a home computer. they simply store one value after another. and you can keep your favourite functions and use of the early eighties. such as the sum of a group of . functions become the best way of grouping even using line numbers. If your first programming project was from wearily turn it off and on again. and they allow you to write a single piece of code that can be reused within a project. and it’s this idea that led to the machines. it’s time for us to tackle the fundamental building blocks behind any application. They allow the programmer to break a complex task into smaller chunks of code. type the following: the best uses. you can try these ideas without getting too BASIC wasn’t retro. The cooler kids would change about 30 years ago. BASIC programming without functions can be a little like writing assembly language code. If you want to repeat a series of lines. Either way. And when it’s one piece of BBC BASIC was the first programming language many of code that’s being used in lots of places. It’s not built at runtime. You can then easily modify this code to make it more efficient. naturally breaking complex ideas into a group of far 10 PRINT “Hello world!” easier ones. From the interpreter. for example (just type python on always put to the command line and add our code). and accept arguments. them again and again. RUN and a carriage return. This bundle both the code logic and the data the logic needs to would create an infinite loop that printed ‘Hello World’ for ever work into completely encapsulated blocks. for instance. You they can work on functions and files without breaking the had to find a computer shop displaying a selection of operation of the application. and there’s a good chance that the functionality and splitting your project into different source following might have been your first program: files. But what must have come soon after lists in the mists of language creation is the idea of a function. then the text to say something rude and add colour to the output. But let’s start at – or for the 10 minutes it took for the store staff to notice and the beginning. Lists W have been around since people started to write one line of code after another because. fixing it once is far us came into contact with. If you then work with a team of programmers. Functions are fundamental for all kinds of reasons. BASIC provided some of this functionality with procedures. With Python. WorldMags. but functions give that chunk of code a label. and jump back after execution. These are a special kind of function that followed by 20 GOTO 10. That could be a list of numbers to be added. which can then be called from any other point in your project. You’d then sneak in and quickly type the above line creation of objects. and much like their mathematical counterparts. to add functionality or to fix an error. When you break out of single-file BASIC code was mostly sequential. easier than trawling through your entire project and fixing your same broken logic many times. in essence. for example. e’ve already covered a concept called a list.

and we pass the two values – each to indent the code and make sure Python understands quickly get complicated. You should see the output you’d expect from a example creates a class that contains projects for the better..27 same name as the original list but that might look confusing. 0. If you alter the function >>> instance = Shopping(“Bread”.99.. The best way is to first write your application. where it’s common sense to give each menu item its own function. 18]) That’s functional 53 programming in The biggest challenge comes from splitting larger a nutshell. The best example is a GUI. return The art of objects . partly because one for the item’s name and the other this. and why types are often To show how easy it is to create something functional. Other languages aren’t so picky. press language-specific features and how this class could be quickly [Return] to create a blank line. 12. You can process this string within the function by 0. return (sum (plist)) convoluted requirements – apart from its weird tab . 13. and how the world of classes problems differently. formatting.item ‘Bread’ expect to find a string passed to the function whenever it’s >>> instance. def __init__(self.. we’ll declared in header files because these are read before the now build on the idea of lists from the previous tutorial. main source code file. You should be able to see statement. self. but for a beginner. This can be solved by opening the function . function with a name like helloworld(). previous shopping list: >>> class Shopping: Passing arguments . When you’re using Python is very forgiving when it comes to passing types to The only slight problem with this solution is that you’ll get other packages. All we’ve done in our code is say there’s going to >>> pricelist = [1. You can’t . Instead of a shopping list... unless you can be certain where how they work. whereas the term object but it begins to make less sense. this task becomes second nature.. But it does mean you can send what input they’re expecting and what a list of values in exactly the same way you define a list: output they return. and go to the trouble of completely rewriting the code after proving the idea An IDE.. we’ll create a list of prices and then Working out what your language requires and where is write a function for adding them together and returning the more difficult than working out how to use functions.. Most other languages will want to know numbers to the function.99] be some data passed as an argument to this function. item. 2.. just it’s able to create the function. and you’ll need to press [Tab] at the beginning of side processes. You’ve now created a function.. price): There’s a problem with our new function: it’s static. After creating a new function called helloworld() that there’s less ambiguity on how class is the structure of Shopping while with the def keyword. For a programmer. but you should A class is a bit like the specification functions from within the interpreter. which is why we didn’t need to define exactly what an error if you try to pass anything other than a list of are exposed.50. Any lines of code you now add will be applied to the separation from the main flow and called __init__ is run when the object is function. for its price. This is something that should be don’t need to know exactly what kind of types an argument may contain before checked by the function. and Quick >>> addprices(pricelist) we’d like Python to call this plist. such as Eric. and you’ll find yourself splitting up ideas as the best way to tackle a specific issue within your project. and that’s why you often get those numbers come from. An object bundles functions and the refers to when specification is used As ever with Python. Python will >>> instance.. for instance. problems into a group of smaller ones. >>> def helloworld(): WorldMags. Dealing with objects can created. >>> addprices([10.. and better the object is instance.. and you’ve just both the item and the price from our jumped forward 30 years. only the functions functions. so within your code. Q and objects easier.. But don’t worry about that yet. it’s only when you’re attempting to write your first solution that better ones will occur to you. You plist contained. which can be launched from either the icons in the toolbar or by selecting the menu item. pass and process arguments. 6. In our example. which signals the end of the function.49. But >>> def addprices( plist ): Python is perfect for beginners because it doesn’t have any . can make working with functions works. 4. it’s an intimidating prospect. you need to be very careful about type of data they accept together. obviously be doing anything other than simply printing out for an object.item = item change anything...30. self.85 You can still create classes and changing print (“Hello World”) to print str...85) definition to def helloworld( str ). Coding Made Simple | 35 . print (“Hello World”) . and you can do that by enabling it to . This simple and objects can transform your coding interpreter. definitions before the program logic. what’s passed to the function.price = price up to external influence. implementations.. It could even have had the tip 16. And total value. Here’s the code: that’s why they can sometimes appear intimidating. It can now be executed by typing helloworld(“something to output”) and you’ll see the contents of the quotes output to the screen. The function with .. the interpreter precedes each new line a function should be used..price called. 0. After the return there are so many different concepts. Often. regardless of functions or programming finesse. Many developers consider their first working copy to be a draft of the final code. and partly because it expanded to include other functions (or and you can execute it by typing helloworld() into the requires the programmer to think about methods). the .

WorldMags. without any user interaction. we print a different message.python. a conditional statement is something like this. halt the transaction. Or if the Consequent Alternative variable PRICE is bigger than 500. too: there. if X contains 10 we print the message as else: before. thereby turning this into a long branch print “Program finished” in the code. you’ll be asking questions in your code: if the user has pressed the [Y] key. and we’ll come if x != 10 If X is NOT equal to 10 on to that in a moment. go to the pub. (We don’t use newfangled electricity around here. But most of the time. If you’re writing a program that IF condition. Here..” Ifs. but you can put more lines of code in inside the conditional . as in everyday life: if the At its core. org/dev/peps/ if truefunc(): pep-3103/ 36 | Coding Made Simple WorldMags. Get your head around coding’s ifs and buts. buts and maybes play a vital role in motor racing. Python style: if x + 7 == 10: if x == 10: print “Well. A condition is just a question.. we create a new variable (storage place for There are alternatives to the double-equals we’ve used: a number) called X.) Or if all the pages have gone to the printers. turn off the gas. providing they have the indents. We then use if x > 10 If X is greater than 10 an if statement – a conditional – to make a decision. you can call a function inside an if statement and perform an action depending on the number it sends back. the great Formula 1 commentator. Why? Read the explanation print “Execution begins here. simply processes and churns out a bunch of numbers. kettle has boiled. but then call the somefunction routine elsewhere in print “X is NOT ten” the code. and if not (the if x >= 10 If X is greater than or equal to 10 else statement). we print an affirmative message. If not. X must be 3” Comparing function results While many if statements contain mathematical tests such as above. and store the number 5 in it. Here’s an example in Python code: print “X is ten” x=5 somefunction() else: if x == 10: anotherfunction() print “X is ten” In this case.. Note the if x <= 10 If X is less than or equal to 10 double-equals in the if line: it’s very important. Look at the following Python code: def truefunc(): return 1 Python doesn’t def falsefunc(): have switch/ return 0 case.. If X if x < 10 If X is less than 10 contains 10. as they do in computer programming. then you might be able to get THEN ELSE away without any kind of conditional statements. then continue. M used to say “IF is F1 spelled backwards. And action action so forth.” at www. These comparison operators are standard across most Here. That could be a big function that calls other functions and so forth. urray Walker. stop. we’re just executing single print commands for the programming languages. You can often perform arithmetic if and else Adapt and evolve using conditionals Any non-trivial program needs to make decisions based on circumstances.

the principles are applicable to switch(x) { nigh-on every language. Another way that some programmers in C-like languages int main() shorten if statements is by using ternary statements. For instance. but print line. The lines beginning with if So. number 1. Q Big ifs and small ifs In C. replace 1 and 0 with True and False for code clarity. In Python and many other languages. because if here { assignment used as truth value. if (x == 1) else puts(“One”). If you puts(“X is 5”). run gcc foo. if (x > y) result = 1. If you recompile this code with gcc -Wall foo. you’ll see Yay but not Nay. it skips past it. and act on the then ./a. that’s conditionals covered. and case 3: puts(“Three”). result. you might be but if you’ve just written a few hundred surprised to see the X is five message lines of code and your program isn’t def falsefunc(): appear in your terminal window. Although we’ve focused on here can be replaced with: Python and C in this guide. type it into a file called We’re not saying “if X equals 5”. return False and the program will operate in the same way. number storage places (registers) with another number. This is neater and easier to read. with executing the indented code. else if (x == 3) Here. return True If you run this program. at the end of the day – the CPU can compare one of its case 2: puts(“Two”). It’s a small consideration. if (x == 5) { But only one instruction will be executed. They’re really simple functions: the first sends back the bit of C code – try to guess what it does. “put 5 in X.c. we call a function here. Program execution begins at the and if you like.h> Ouch. print “Yay” WorldMags. Instead of foo. the second if falsefunc(): Assignment vs comparison print “Nay” value of X to be 1! Well actually. is an indication that you might be doing function it calls. so you if (x = 5) The solution is to change the if line to could replace the functions at the start with: puts(“X is five!”).h> following the first matching case. shome mishtake? We clearly set the It’s caught us out many times. Otherwise. especially C. indentation – you have to explicitly show what you good enough for C – we need to use When you execute it. Now the program def truefunc(): } runs properly. if X is bigger than Y. Note that this doesn’t make the resulting code magically } smaller – as powerful optimising compilers do all sorts of C. If the if statement sees the number 1. put them in curly braces like if (a == 1) the following: puts(“Hello”). Note that the break Clearing up code instructions are essential here – they tell the compiler to end In more complicated programs. not a comparison. In some languages. this could be the root cause. do something like this: puts(“Have a nice day”). a long stream of ifs and elses the switch operation after the instruction(s) following case can get ugly. want with curly brackets. And it all boils down to machine code case 1: puts(“One”). C doesn’t care about Here we see how indentation isn’t puts(“Have a nice day”). and then we have our first if statement. if (x == 5) instead. where the if (x == 5) indentation automatically shows which code puts(“X is 5”). int x = 1. } Contrast this with Python. and some other languages. include a switch statement tricks – but it can make your code more compact. To attach both statement followed by a single instruction: instructions to the if. Shurley behaving. break. break.c (to show all warnings). you but it will print the second.out to execute it. and if that succeeds. That’s because only the don’t need to use curly brackets when using an if first is tied to the if statement. you The first four lines of code define functions (subroutines) have to be very careful with but in the if line we then performed an that aren’t executed immediately. which simplifies all these checks. For instance. result becomes 1. result = x > y ? 1 : 2. } Remember to thank your CPU for all the hard work it does.. result = 2. { Consider the following code: int x = 2.c to compile it and rather. it goes ahead #include <stdio. if not. else if (x == 2) This can be shortened to: puts(“Two”). you can something wrong. execute the code in the curly brackets”. This only does its work if it receives the number 1 back from the int x = 1. break.. otherwise it’s puts(“Three”). belongs to which statement. So int main() you’ll see that GCC mentions when you run this. it won’t print the first message. what the single equals sign does. That’s use. consider this C program: have been executed. WorldMags. look at this assignment. curly braces to bundle code. 2. it will execute everything #include <stdio. but are reserved for later comparisons. doing a comparison. and other languages that share its syntax. we did. jump to a different place in the code depending on the Coding Made Simple | 37 .

anything with variables and the contents of memory. Your program calls lots of different subroutines. the version of x we were using in myfunc() was a local variable – that is. you can without accidentally trampling over one another’s data. WorldMags. so let’s look at another implementation here. to Well. In most high-level languages. Why? Because variables are variable. and it stays that way back in the main code. For instance. or absolutely everywhere in all of It didn’t do anything with the x variable that was declared explanations the program’s files. myfunc() How do you know that those routines aren’t messing about print x with the RAM where X is stored? If you’re totally new to Python: the def bit and the The results could be disastrous. and in Python you can do this by inserting the following line into the start of the myfunc() routine: global x This makes all the difference. So. but the function had its own copy of the variable. You’d be totally terrified of choosing variable names that implementations. As control jumps back to the main chunk of our to the rest of the program. might be in use elsewhere. but then the myfunc() routine grabs that x as a global variable and sets it to 10. Still. How did that Most well. this 38 | Coding Made Simple WorldMags. and accidentally changing someone else’s data. and stores the state of the arm in a variable x=1 called X. we can choose happen? Didn’t we just set x to 10 in the function? documented whether it should be visible to the current chunk of code. How variable scope is handled varies from language to Variable scope of various variables Caution! That variable you’re accessing might not be what you think it is. it’s the same one as we used in the main body of the code. so once you’ve got the program design. and you were writing a article. we access x as a global variable – that is. we see that x is set to 1 at the start. there are legitimate reasons why you might want to make a variable accessible to other routines. can control the scope of a variable – that is. so that multiple programmers can work essential to keeping code maintainable – imagine if all basics from this together on a project. implementing their own routines variables were accessible everywhere. We print it out to This is where the concept of variable scope comes into confirm that. we create a originally envisaged. the idea that one part of the program could do print x anything with memory became less appealing. starts punching people instead of stroking puppies as Program execution begins with the x = 1 line. outside of it. explore specific good for modularisation and keeping data safe and secure. and play.000-line software project. This is scope. Try this: This was fine for simple. and these instructions could do your programming journey. Change of routine So most programming languages provide this level of protection. By adding the global command. It’s routine to be dropped inside a 50. languages have the current source code file. variable called x and assign it the number 1. So if we run this Python code now. it affects only the code located inside the function. and doesn’t of variable This level of control is absolutely fundamental to good want to interfere with data it doesn’t know about. Have we said ‘variable’ enough now? O nce upon a time. you might have a program that controls a robotic arm. The function lives happily on its own. we code. we print x again… and it’s back to 1. especially when the arm following two lines of code are a function which we call later. In programming. We then call a function which sets x to . low-level programs but as time went def myfunc(): on and people starting making bigger and more complicated x = 10 programs. Previously. print x some of which may have been programmed by other people. Let’s start with a bit of Python code. scope defines how a variable is visible prints it. yes. programs were just big lists of and therefore it’s a good thing to get right in the early days of instructions.

x). adds 1 to it and prints it out. that variable. For x is 3 } instance. in foo. So. #include <stdio. so there’s { no guarantee that the RAM is zeroed- int x. that’s a matter of own time. line at the top. they are only created in RAM x = x + 1. Note that while putting the x declaration outside of personal choice for your particular program. and you’ll see the intended result. Pointers are a tricky business! Q Remember to initialise! By default. references in C++).net time in C. So it’s somewhat clearer that myfunc() has its own version of void myfunc(). static variables is However. static int x = 0. then compile and run it. why don’t compilers just set variables. the number You can tell GCC to warn about the will probably be different each time use of uninitialised variables with the If you try to use automatic variables that haven’t been you do. does with automatic variables. given any value. but it’s extra work for the So if you have a program like this: CPU and adds a performance hit. and then and GCC tries to be pretty efficient. we call myfunc() three times. making room for other bits myfunc(). WorldMags. right? used previously by other data. so that’s something to look up in your global variables.h> int x = 0. a way to stop that. Once the } int main() routine containing the local variable has Here. Setting that chunk of RAM to zero } requires an extra CPU instruction. Inside the } a great way to get some of the benefits myfunc() routine. longer be useful. that’s not the only job you need to do. x). that variable will no which creates a variable x containing int x = 10. it rule is: use global variables only when necessary. but the general functions makes it global to the current source code file. WorldMags.c and you want to use that in bar. because we’re explicitly creating variables with int. Try to keep doesn’t make it global absolutely everywhere in all of the data isolated inside functions. because they might be the variable to zero? That would created somewhere in RAM that was make everything a lot safer.? Well. take it away so that the line just reads x = 20. But what happens if you } There is.. the output void myfunc() This is still a local variable that can be becomes this: { manipulated only by code inside the x is 1 int x = 20. Whereas Python is pretty flexible about using variables that you haven’t defined previously. printf(“x is %d\n”. void myfunc(). Most local variables are automatic – that is. Run the program. #include <stdio. yes. routines can’t access it. as it and now the variable has become global – that is. and bobs. change the declaration in myfunc() to and that’s by declaring a static variable. Well. compile and run it again. So. the compiler no doubt already guessed that running will typically reclaim memory used by this produces 1 with each call of myfunc(). but those features are specific to All of this leads to one final question: when should you use individual languages. using accessible by all functions in the file. but it retains its state x is 2 printf(“x is %d\n”. current function.h> compiler that it should preserve the state of the variable between calls. The compiler doesn’t from inside main() to after the void myfunc(). ditch it at the end of the function. Move int x = 10. most C compilers don’t don’t blindly use variables that set newly-created automatic haven’t been initialised with some variables to zero. every time the function is called. So if you have int x = There are usually ways to access the local variables from 10. it’s myfunc(). because x is being created printf(“x is %d\n”. But how do you go about making the variable but in future calls it doesn’t initialise the global in this particular instance? The trick is to put the int main() variable as new again. you’d need the one function in another (for example. that x is global and can be modified everywhere. on the very first call it sets up x as zero. The moral of the story is: -Wall flag. Consider this: Automatic variables #include <stdio. in the latter file.c. This is especially kind of value! true in the case of automatic Now. we still have a line that says int x = 20. of global variables (retaining its state The int here is still creating its own version of the variable. You’ve printf(“x is %d\n”. { finished. each time. because outside zero. when you have no other option. myfunc(). when program execution reaches the printf(“x is %d\n”. and when local? Ultimately. If you’ve got a big project with multiple C files. the variable. so void myfunc() throughout execution) without exposing { it to the rest of the program.. prepare for some Coding Made Simple | 39 . C is a little more strict. point of their initialisation. look at the following C code: The static keyword here tells the Here. x). out. x). and only use a global variable source code.h> The compiler allocates space for variables in RAM that may have been int main() used for other data before. myfunc(). however. { state from before. but retrieves its variable declaration outside of the functions. x). pointers in C and line extern int x. you’ll have to use the extern keyword.

Knowing that we need some www. for loops. Output data: monthly payments and total interest Input: mortgage value. The next thing we need to do is figure out how to combine all those arguments – all that input data – to get the output we’re after – monthlyPayments. there are two types of data (and much more) is vital if you want to learn to program. (Picture from: based on faulty assumptions). some set processes – recipes of “I want to make Space Invaders. but at 4% per annum. monthlyPayments = 0 Read through the above text carefully and pick out all the return monthlyPayments types of data that are described. so long as you’re confident that it’s reliable (your program won’t work properly if it’s Check often for bugs in your program. money. we’re going to look at the art of designing programs. It’s not really anything to do with programming. but that’s not really the important thing involved. smaller ones. we’re going to do something a little different. interest. by looking at the data might be unfamiliar. term): programming problem is to closely examine the specification. Functions: one task at a time To demonstrate. but that sounds like two problems instead of one – sneaky! you don’t have the faintest clue where to get started when You’ll find that many programming problems look like this faced with a new programming challenge.” but on closer inspection a kind – that you can follow that will help to direct your you’ll see that the problem’s actually made up of many thinking and make solving a problem much easier. separate the data into input and output. There’s not much to this function yet. and we’ve Once you’ve identified the smaller problems. Let’s say that Mike will be to focus in on one. Knowing about if clauses. – you’ll start with a grand description of what you want to do: There are. you can get to a point where you know all of the 40 | Coding Made Simple WorldMags. We’re going to start with the needs a mortgage of £150. We’ve given the function a name. but it’s some extra knowledge that we need to solve the problem. Let’s take a look and see what we have so far. but what was the point? Well. WorldMags. we’ve created a variable to hold this information. He wants us to help him. and we’ve specified all the input data as arguments to the Building proper programs Learn to break problems down into manageable chunks. annual interest rate. But there. but it’s often helpful to start with a sketch and fill it out later. lists and functions take a look at the output data. duration Great. we need an example problem. The first step when tackling a def monthlyPayments(mortgage. Some of the Python features we use to solve problems Identifying these smaller issues. This is what might be called ‘specific knowledge’. Since we know that we’re trying to work out the monthly payments. n this article. however. As you’re doing this. Innsbruck. is often the first step to finding a solution. Since that sounds exactly the same as what Mike wants to know what his monthly repayments will be in we’re doing now. paying it back over 30 years.000 to buy a nice house in monthly payments problem. and instructed the function to return it when it’s finished. it’s more of a sketch than something that might be . let’s try to create a function for our monthly each situation. and how much interest he’ll have paid in the payments problem. This is in this tutorial (you can always look those up on the internet called top-down development. with Mike paying it back over 25 years at a bookazine. You can use any source you like. easier ones. A bank has agreed to loan him the money at a rate If you look back at the tutorial on page 10 of this of 6% per annum. you’ll see us explaining that functions are great fixed monthly If we have to come up with two pieces of output data. your next task settled on a simple mortgage calculator. end. yourself) – the important thing is the thought process that we must go through. I Instead of looking at a specific feature that shows up in many programming languages. that was pretty easy. This is often a vital step in successfully completing a programming problem: identifying and finding the specific knowledge necessary to complete the problem. as we show you how to design a well-sculpted program. Another bank agrees to lend him the because they allow you to break a complex task into smaller.

that’s great. larger problem. Mike wants to live information about how to calculate mortgage repayments. By looking that we came up with: closely at this information. we managed to find monthlyPayments (200000. N): def monthlyPayments(P. but testing regularly will make spotting and fixing bugs much easier. but consistency can calls both the others and prints their output in a pretty help avoid mistakes. we looked up print statements specific knowledge to check that which allowed us to certain variables are what you’d “A good way of finding out solve the Coding Made Simple | 41 . r..0 . N. finished. with expect them to where the problem lies is by working solutions be at that point to all of the in the code. P) us anything about the amount of interest paid. c is the monthly payment. At this point. One important thing to be wary of is that all of the inputs that we have are in the same units as the formula expects. r. and work them out using a calculator. P the amount borrowed and N the number of monthly payments. a quick Google search turned up this handy and entirely relevant formula on Wikipedia: c = rP / (1 . we’re ready to move on to might have to further divide the subproblems. at the end of all this. making it easier and more Now that we’ve established a test case. it’s worth testing what we have put N) together so far. 30) = 1467. WorldMags. Finally. and instead look at solvable and then work your way back.math. but this is exactly what you would do would allow us to check that r was what we expected. what did our whole development check it with. adding more print statements” subproblems. r the monthly interest as a decimal. print ‘Total Interest:’. Also. Be sure to take note of the expected result. N): And that’s our function for calculating monthly payments print ‘Monthly Payments:’. If it doesn’t. Q WorldMags. P): (N * 12 * -1)) return monthlyPayments def mortgageComp(P. come up with a few values of P. but you would the second: calculating interest paid. totalInterest(monthlyPayment It’s obviously not the complete program. N = N * 12 monthlyPayments = (r * P) / (1 . we’ve added a couple of lines to (From Wikipedia’s Innsbruck page. This is what our final program looks like: import math import math def monthlyPayments(P. For some. to tackle almost any programming problem. def totalInterest(c. following the method laid out here. a good This was called incremental development. We called this top-down development.(1 + r)^N) Here. Designing programs Before you can test code. and he needs us to figure out whether he can afford it! Because they’re not here. This isn’t necessary.52 a way to split the problem in two. N). We’ll leave you to do just keep going until you reached a level that was easily that. print r The steps are simple. and working like this is known as incremental development. format. note that we have changed the argument names to The simplest way to do this is to create a third function that match the formula. you need some test cases to So. print the result.0 / 12.) convert them. 8. Notice how all the variables needed to calculate c in this formula are already provided to our function as arguments? Putting it all together Now we must convert this knowledge into our programming language of choice.pow (1 + r). Here’s one and identifying the input and output data involved.0 come up with a solution to the original. as it doesn’t tell s(P. beginning with sketches and testing each as we progressed. and developed solutions to each of these as separate functions. modify the code manageable. solving each level as how you can tie these two functions together. where we had to. r. monthlyPayments(P. r process look like? and N. you With the first problem solved. and when you reached it. In this case. we For example: combined them to r = r / 100. 25) This is a vital step in the development process. filling out our function sketch. We began by critically reading the problem specification.0 / 12. r. N. mortgageComp(150000. way of finding out where the problem lies is by adding more Also remember that. 6. N): r = r / 100. r. If everything matches. We then so that the function gets called with these arguments. WorldMags.myfavouritemagazines. M RE E O G NT3.C C T O A N M AT O R T T WorldMags. CYCLING AND MORE… LIFE’S BETTER WITH T3 E GET FIT FAST IN 2016 WITH THE VERY BEST TECH FOR .

net Not your average technology website EXPLORE NEW WORLDS OF TECHNOLOGY GADGETS. culture and geek culture explored Join the UK’s leading online tech community . WorldMags. DESIGN AND MORE Fascinating reports from the bleeding edge of tech WorldMags.

or why they do what they do. syntax isn’t from any one specific language. i >= 1. It’s the programming In the above snippet. and that it should be increased X factorial by one with every iteration of the loop. to the value 1. To make use of it. We’ve used a more bending your brain around what might be a more complex C-like syntax for the for loop. we can use a function that calls itself in return. this is easier to read than the range keyword we’d need to This is because recursion is simply a way of solving a more use if we wrote the same code in Python. it can save you from eccentricities of one implementation. we’re going to ask the function to control itself knowing that it has been called from within itself. factorial of a positive integer (we have to say this because the which is why this is an iterative approach. But if you do this. such as GNU (GNU’s for i =c. And that way uses recursion. equals . Don’t forget that as well as passing values to and returns the correct answer. recursion is a function to give a number’s factorial. examples of value of i steps down from c. You can then just copy and paste Pseudo code like this is used to explain a concept and to them into your code without necessarily understanding how create a template to show the logic of a program. If you’re working on complex problem by repeating a simple function. but be careful – you may well land on your own head. and easiest. Here’s the pseudo code for an updated factorial function that uses recursion instead: function factorial(c) 4 3 2 1 1 2 6 24 if c > 1 else return c * factorial(c-1) return 1 All that’s happening here is that we’ve replaced the old factorial function with one that calls itself and expects a value To calculate the factorial of a number. or connecting to the same virtual loop) to step through a range of values. That’s recursion! a function. many uses of recursion are well print total documented and explored. WorldMags. the input value. because recursion is cool. for example. and as a result. for instance. without being weighed down by the peculiarities or write a few lines of Recursion: round and round we go Jump down the ultimate rabbit hole of programming ideas. but the they work. Instead of controlling the If we wanted to approach this problem in the same way function from a for loop. i-- not Unix). because we think problem without recursion. It needs to be you’re missing out. the In programming. but it’s a concept much clearer in code. ecursion is one of those concepts that sounds far we’ve been doing with previous tutorials – a strategy known R more intimidating than it really is. of itself from within its own code. Rather than being a pseudo code sketch of any potential solution is a great way run manually from another function. or start thinking in four dimensions. or as iterative programming – we’d maybe write a function that multiplied two values within a for loop which was counting down through the factorial input value. it calls another instance of communicating your ideas or proving your concept works. the function itself can return a value. We’ve used the desktop from within a virtual desktop. In other words. you don’t need to grasp complicated mathematical ideas. Honestly. writing that this function repeats from within itself. The Each iteration of the multiplication is controlled by the code. The factorial of 4. we create a for loop that uses a variable equivalent of pointing two mirrors together to create a called i (that’s a common name for variables within a for seemingly infinite corridor. The trick is a problem and don’t know how to approach it. That’s confusing to read. usually using 44 | Coding Made Simple WorldMags. C-syntax to say this value needs to hold a number more than (>) or equal (=) to the value 1. which exact same result. function would change otherwise) is the product achieved by You might already see from the previous piece of code multiplying the whole numbers it contains against one that there’s a slightly more efficient way of achieving the another. It’s one of the detailed and clear enough for the reader to understand the best ways of letting the CPU do all the hard work while you logic. is 4x3x2x1. this invade one level after another of someone’s dreams to might look something like the following: implant an idea into their subconscious. In pseudo code. or even understand function factorial(c) the meaning of recursive acronyms. one of the classic. total = total *i For the most part.

This is 120 moves forward. you’ll have to could be an infinitely complex image. WorldMags. and multiplies this by the value that’s returned. which is what will launch other iterations. on for ever is because we first check whether the length of Before we start. so that the code that called the function can use the value. this means that all the installation.fd(length) mathematical solutions and filesystem searches. you will need to make sure you each line is going to be greater than 10. To turn this into a fractal. and this can be easily achieved by adding the most famous were documented by the French fractal(length*0. 2 and then 1. which itself returns (2x1) to the previous call. and on. returns (4x3x2x1).. you’ll see the Turtle the quickest ways to understand the Coding Made Simple | 45 . for example. following into the Python interpreter: because the cursor moves slowly along the path as our fractal Quick is being drawn..fd(length) Python interpreter prints this out without us needing to do trtl.fd(length) line. return 1 create a function to draw a star. we’re going to quitting. You can see that while it’s harder to understand the logic of how the final value is calculated..fd(length) something can be approached using recursion. but the reason why this doesn’t go we’re going to do using Python. which returns (3x2x1) which. but instead uses the relative position of the sleep (seconds) >>> factorial(5) a cursor and an angle to draw the path with the cursor as it command within your code. or doing . As long as the incoming value is greater than 1. by typing fractal(200). very useful if you >>> import turtle as trtl want to see the def fractal(length=100): final Turtle graphic The last two lines in that example are simply executing the if length < 10: rendering before the factorial() function with the value we want to the return keyword. Fractal algorithms use recursion to add infinite same function from within the function itself at the end of levels of detail to what’s a much simpler algorithm. another star at the correct point. the return values start to trickle back because factorial() is potentially infinite. The Turtle module itself needs you to install until the main star itself has finished and the fractal is tk-8. in turn. type the can also see exactly what our script is doing as it’s doing it. We use this to draw and display lines with as little other part-completed stars can draw their respective limbs code as possible.fd(length) Congratulations – you’ve solved the problem using recursion! trtl.5 for its drawing routines. we want to execute the are fractals. then expand this to draw anything else. there’s one cursor first move forward before turning left 144 degrees and particularly effective set of functions that can be used to drawing another line. When return window closes. if you have an idea that trtl.. should look like.left(144) Google search will reveal whether it can and what the code. The Fractal call the fractal function again. If you want your . too. the function finishes and returns the final calculation. and these the star. This is true of the majority of recursive solutions. you end up with what distribution doesn’t add this automatically. factorial() will be executed from within itself with the values 3. If you call factorial(4). then a simple trtl. making this solution more efficient and less prone to errors. which is why you see the results under this line.left(144) repetition. Some of each limb. Drawing with Turtle graphics sleep to the top of >>> factorial(4) is perfect for fractals because it doesn’t draw lines with your script and use 24 co-ordinates.3) after every trtl. other trtl. As with the factorial function. and so on. else: limbs.fd(length) all sorts of places that require an indeterminate amount of trtl. If you run the above piece of code. This will mathematician Benoît B Mandelbrot in his book.. But to start with. and a further one on each of those to pause before . trtl. no longer being called recursively. but it should be part of any default Python drawn.. But its complexity is 1. or by adding that But if you want to visualise recursion in action. only this time with a length Geometry of Nature. return c * factorial(c-1) end of each of its limbs. tip >>> def factorial(c): The fractal we’re going to create is called a star fractal. With just a few lines of code. with another star drawn on to the Python application .. Q WorldMags. the trtl. though. if c > 1: This is a five-pointed star.. or return pseudo code. Using the Turtle graphics module means we ending beauty of recursion.left(144) can’t think of a solution yourself. which is one of command to the last line in a script. And that’s the never install it yourself.. add from time import . such as many sorting algorithms. The first is Python’s Turtle return from the function. It does this four more times to complete illustrate both its advantages and its complexities. Even if you trtl. either from the Generating fractals interpreter. If you want to see this as Python code so you can try it out. If it isn’t. factorial calls itself with a new value that’s one less than the one it was called with. which means if your complete. This star. there’s a lot less code than with the iterative approach. When it hits We generate this fractal with just 16 lines of code. but there are many easier algorithms value around a third smaller than the original.left(144) anything else. 1 is returned and multiplied by 2.. and stars will stop being indefinitely graphics module.left(144) You should now be able to see how recursion can be used in trtl. then we have two dependencies installed. that can be created with just a few lines of code.

like each card to the correct location in the Super sorting algorithms Let’s take our coding further and introduce you to the unruly world of algorithms. away from the computer and the value of the two cards. that you have two statement. and if it is.2] amount of time to return the sorted list. but have you ever stopped to wonder card[0] = card[1] how on earth it works? It’s a fascinating question. you’ll also get a gentle introduction to algorithms and with the values 8 and 2. It works amazingly on the left was worth more than the card on the right. you’d leave them as they were. 8 5 2 9 Bubble sort 5 8 2 9 works by comparing adjacent elements in the list. What do you do? Easy. 46 | Coding Made Simple WorldMags. and you’ve got a huge list that you need to put in order. for example. if the card on the right was worth more. copy So. so what happened? won’t get anywhere very quickly. As it does so. You’re happily writing a little Well. and if the card P program. if card[0] > card[1]: This is really handy. it’s pretty simple: you’d look at them.8]. Because there’s no operator in Python that enables us to switch the position of two . That’s obviously not what we about how to sort a Python list with a million items in it. the way. ython is a great language. and it doesn’t even care how big the list is – it could What would that look like in Python? be millions of elements long and still take virtually the same cards = [8. where do we start? Sorting a list with a computer.2]. WorldMags. How would you put these two cards value. We then check to see whether the how to think about their performance. There’s a list of cards. You should find that difficult when you first begin. you want. and in the card[1] = card[0] next two articles we’re going to introduce you to some of the print cards techniques that are used to solve this kind of problem. Along That seems pretty straightforward. efficiency and sorted data. When we tried to do the second assignment. many programming problems. we ended up with both cards having the same hearts cards from a deck. we did what seems most Sorting two cards natural to us – we used the assignment operator to copy the But what if you step back. and you’re away. If you start off trying to think you don’t get [2. we just in numerical order? copied two identical cards. you’d switch them around. seems incredibly abstract and Run that code and see what happens. first card is more valuable than the second. just call the sort() method on the list. but [2. The problem is that after the first copy list of a million items? Imagine. the largest element ‘bubbles’ its way to the end of the list. quickly.

000 j=i+1 operations. the n2 term is always cards[j] = cur going to be far larger than the n term. while swapped: #sort until swapped is False That is to say the increase in the amount of work becomes swapped = False #assume nothing is swapped more and more rapid for every element added to the list. five loops: 20 operations. it will end operations this time. operations = n x (n . loops x num. WorldMags. and before we do any copying. these two operations. and bubble sort just two cards. and we It’s pretty clever. and it’s definitely not how Python does it. where it belongs. cards[i] = cards[j] In the general case given above. we’d There’s a definite pattern here. The element with the greatest value will always end up What about if we add a fourth? It will take three increasingly longer for every on the right-hand side of the comparison. performance The idea is that we loop over the entire list. 2. However. That on a fast computer. This code shows how a bubble sort might be implemented in Python: Big O cards = [8. but it’s pretty close. Q WorldMags. Eventually. in computer science it’s only ever the largest term that’s considered. and To understand why this is. – that means (and swapping. Speed matters The terminology used for this is ‘big O’ notation. In total. albeit harder to implement. In the end. so sorting a list two elements long isn’t particularly Bubble sort impressive. Because of this. comparisons loop. on each num. and it will simply get worse for every card from if cards[i] > cards[j]: there on. This for i in range(len(cards) . bubble sort had to do two comparisons – once makes the most sense here. 1] What this means is that the amount of work bubble sort does swapped = True increases in polynomial time for every item added to the list. it won’t move any further. 7. reverse order. said.1): #loop entire list is why it’s so slow for large lists – a 10-element list may take cur = cards[i] only 90 operations. Bubble sort OK. if we have n elements. Because we stored a copy of the first card’s value when we overwrote it with the first assignment statement. Five cards? That’s four comparisons and up at the very end of the list.000-element list will take 999. you should get the correct answer. we could use the copy to set the second card to the correct value. This means that. and three loops. to the number of elements in the list. work done by bubble sort is: We’ll know the list is sorted when we run a loop in which num. and four loops. and the number of until it reaches the largest element from the previous comparisons is always equal to one less than the number of iteration. Take a look at this code: cards = [8. bubble sort has to do the most work possible. it takes in turn. Bubble sort is any size list and it will get the job done. if we were to loop over the list only once. and hence will always swapped = True #reset swapped to True if anything have a much larger influence on how well the algorithm is swapped The way to get around this is to store a copy of the first card’s value outside of the list. operations = num. so will always be comparisons on each loop. if necessary) each set of adjacent elements In total – that’s six operations. compared in the next pair of elements. comparing it has do two comparisons on each loop. are much closer to how Python does it. 3. and then again to check If you fancy looking at sorting algorithms that are much that there’s nothing else to sort. There may be much work our bubble sort algorithm has to do. The work done by bubble get only the largest element in the correct position. if you try to actually considered to be one of the worst-performing sorting use it on a large list. you’ll find that it’s painfully slow – even algorithms. to get the cards in the correct place. assuming that they’re in with O(n2) bubble sort. it’s not quite how we would do things in real life.1) = n(n . Notice that. At this point. let’s think a little about how works all right for small lists on fast computers. 4.n nothing gets swapped.2] card0 = cards[0] if card[0] > card[1]: card[0] = card[2] card[1] = card0 print cards If you run that. it had to perform just faster.1) = n2 . because it’s loops. we’ll encounter another largest element that always And we can see that the number of loops is always equal ends up on the right-hand side of each comparison – that is. The way sort seems to conform to the formula: to get around this is to keep looping over the list. It’s easy to implement. When we had times when you just want to get the job done. That’s 12 element Coding Made Simple | 47 . right? You can now use this program to sort say that bubble sort is a O(n2) algorithm. but a 1. But we can extend the same technique to sort a is an algorithm list that has an infinite number of elements – this is known as When we add a third card. the amount of now in the correct position. don’t discard it entirely. when discussing the performance print cards of an algorithm. jump to page 102.

So. But rather than either. 16. and this is normally represented by a 1 for on is 170 (2+8+32+128). The first is octal. say. 64 and 128. And that value can be as 2’s compliment If you want large only as the number of bits the CPU supports. Using this logic with the above question. Computers use a numeral system called reference to 2’s compliment. If you write a PHP script for the web. is equivalent to 2. But you’d be wrong. and uncover the hidden meaning behind 1. which is -85 – the correct value. a scheme for handy display binary to store these on/off values within their registers and representing negative values in binary. the most significant bit – the one languages. topic in the 21st century. This is. If we move that script can have a huge impact on the performance of your bit to the left so that the 1 occupies the third slot along. yields 10101011. But what’s a bit? It’s represent in 2’s compliment? You might think. so that 1 becomes 0. Number systems are just as important for high-level assign them in that order. and it changes the mode for up to memory. Y ou wouldn’t think that numbers would be a relevant represents a number that’s double the bit to the right of it. its lowest level. The reason this method was chosen rather than swapping the most significant bit is because most binary arithmetic can still be performed on these negative values in exactly the same way they’re performed on positive values. If we enable every bit in an 8-bit binary number. 2. is 10 in octal. a process known as flipping. 4. and thousands of times a second. then with 1 added 11111110. we first subtract 1 from 10101010 to get 10101001 and flip the bits to 01010110. That’s a difficult couple of sentences to knowledge of how computers deal with numbers. These Consider the following question: what does 10101010 to see binary days. so that calculated or stored have an impact on performance. which gives a decimal value of 86. a base 8 system that uses the numerals 0-7 to hold 8 values. for example. Adding 1 to 10101010 (-86). so here are some examples: systems used to process them. WorldMags. which is the 2’s compliment representation of -2. that means either 32 or 64 bits. the negative of 00000010 is first 11111101. holding the largest value – is usually on the left. for example. right down to hardware and design. Typically. While we’re in the binary zone. 7+1. 8. that the binary value represented here in real time. or 00000010. information. single operation of the CPU can deal only with a value held within one of its internal registers. If we enable more than making any small binary value represents a number one bit at a time. Your code total value might be run doubles to 4. 2 and -1b1010101. it’s count them. and the digest. The position of each bit within a binary value meaning of the bits and what they represent. it’s worth mentioning a couple of other numeral systems sometimes used when programming. and adding 1 (there is a single exception to this). after the last registers update literally a switch that’s turned on or off – a single bit of couple of paragraphs. The clue is the KCalc has a and a 0 for off. having some minus 1 (or 28-1). And it’s not all for low-level stuff like assembler following values: 1. “The position of each bit within a so on. discrepancy in then all the values how those that’s double the bit to the right” are added numbers are together. so the answer to the question is -86. a we get a maximum value of 255. 00000011 represents 3 (1+2) and 10000011 represents 131 Numbers are important because they engage the CPU at (128+2+1). So. in fact. But for better or worse. reversing the configuration of bits. the binary small changes in the way you process numbers within the number 10. It does this by 64 bits of data. will help you to write better The positions within an 8-bit binary number have the programs. if there’s one thing giving a sequence of bits the ability to represent every value computers can do well. 48 | Coding Made Simple WorldMags. the . After Hidden secrets of numbers Allow us to channel the living spirit of Dan Brown. 32. Billions of between zero and double the value of the most significant bit times a second.

hexadecimal. and no more. for Ø1 1 1 Ø1 1 1 example. there’s short int. and how the underlying systems that take your code and make it run work. unless you want to. such as when rounding the value of pi to 3. it has numbers. such as 0. you need to prefix the something called an include file for C and C++. On most machines. there’s tip Data types long int and if you need smaller. and this limit is hidden within want to input a 2’s compliment binary. and it’s another create a utility that variable as you come to use them. and that’s the equivalent of four bits of data. As you can see with the last example. An 8-bit value has become known as a byte. they do when many of these are combined. which is most often ‘-0b1010101’ defined as int in programming languages such as C and C++. you’ll find replacing the 0b with 0c and with hexadecimal by using 0x. ‘0b1010110’ hardware and its internal representation of a value as bits. But understanding a little about what they mean and how they relate to one another OR XOR can help you when looking at other projects. like early Coding Made Simple | 49 . codes with any reasonable binary editor. it’s (the value held by an 8-bit value). Q WorldMags. because they wonder how they’re have decided to forgo the advantages of specifying the size of to read or write to supposed to know what they need to use before they write a variable for the simplicity it gives to programming. But unless you’re dealing with small fractions. Typing a binary number will output the decimal value: =1 1 1 1 = 1 ØØ 1 >>> 0b01010110 86 Binary and You can convert values to binary using the bin function: that reason. The compiler or interpreter needs to know about type One set of types we’ve neglected to cover is those that because it wants to assign only enough memory and include a floating point. which is why it’s often used when you play with binary values. and for storing raw binary data = 1 ØØ 1 within your program. that an unsigned int can hold a maximum value of and both of these numeral types have supporting functions 4294967295. you can do so using Python’s interpreter. This is an binary formats. because the designers hold together is essential if you want confusion in the beginner. If you architecture of your CPU. through the its dire consequences. you can enter a binary value using the 0b prefix – that’s a zero followed by the b. in reality. there’s no need for the usually enough just to create a variable of type float to deal compiler to ensure more than this amount of storage is with these numbers. If you know worry about the size of a float. this also works with The largest number an int can hold depends on the negative integers. This problem. where most machines rounding errors in employees’ payslips into his own account. which is base 16. there’s no standard storage size bitwise operators bring logic to >>> bin(86) for many data types. >>> bin(-85) The best example is an ordinary integer. and this is a great way of getting familiar with how the numbers work.14159. A byte’s worth of data is still used to store precise number. characters to this day. you need to specify the generally don’t need to worry about any of this in languages how bits and bytes type of a variable before you can use it. >>> oct(85) This is why an int is usually the most generic variable ‘0o125’ type. You Understanding In many programming languages. because this is typically used to store a single introduced by rounding a value up or down from a more character. communicates with external hardware. The biggest problems when dealing with floating point Although the number of bits in a byte used to vary. It always depends on your computer’s your programs. and But computer hardware has moved on. If you need just as 9+1=10 in decimal. Hex is a more Ø1 1 1 readable equivalent to binary. which is why it’s often used for memory and binary editors. you write the declaration for each example of something known as Duck typing. it’s the precision that’s your variable is never going to have a value greater than 255 important. Similarly. From version 2. uses the characters 0-9 and a-f to represent decimal NOT AND values 0-15. WorldMags. reason why Python is such a good beginner’s language. 1 1 1Ø 1 1 1Ø If you want to play with numeral systems. But. to the pure 32-bit Pryor’s character in Superman III when he siphoned off the PCs of the last decade and to today. and if you paste this value into a binary for converting integers: calculator. Ø1 1Ø which as an 8-bit value equates to 108. You can avoid using these numeral systems in your code =Ø 1 1 Ø and your projects won’t suffer. which you can view through ASCII While small rounding errors aren’t likely to cause problems.5 or 3. So. This can cause such as Python. For and amassed a large fortune. was brilliantly illustrated by Richard 16/32-bit era of the Atari ST and Amiga. or the code. and why programmers try to stick to integers. returning a 2’s compliment binary. available. Rather than processing to handle that number. are settled on 8. 1 1 1Ø the number 6c in hex is 0110 (6) and 1100 (12 = c) in binary. you’ll see this requires 32 bits of storage – >>> hex(85) probably the most common architecture in use. have a processor capable of handling 64-bit instructions. It takes exactly three binary bits to BITWISE OPERATORS represent a value in octal. it can store large numbers and can be addressed Quick efficiently by most recent x86 CPUs.6 onwards. Even 64-bit ‘0x55’ machines can properly interpret 32-bit values. and an data with -0b. You can do similar things with octal by equivalent for other languages.

but it gives you a better insight into what’s happening: for ( int i=0 . linked and run (this is the big difference 50 | Coding Made Simple WorldMags. a loop on its own is used mostly to programming sense. because it includes the implicit definition of a variable. as ways to step through data. Without loops. programmers are 1 forced to write everything in longhand. is a chunk of the same code that’s solve a simple calculation. This line needs to cpp -o helloworld’. Range is a special the command previous tutorials in this bookazine. leaving the loop when it gets to 5 (a total of five steps when you include zero). It’s the idea of a loop. you can’t really guess at the the results. we’ve already programming task would called i in examples. and it’s the same with other languages. It’s the 3 difference between sowing a field by hand or by using Jethro 4 Tull’s horse-drawn You can see in this snippet seed drill. the syntax looks slightly different. Which is why. because it requires a specific With a method or a function. we’re returning related to the idea of recursion. and for filling arrays and files./ any time discussing the various kinds of loops you can part of the for loop (as denoted by the :). condition. helloworld’ to see implement. or for waiting for a specific designed by the programmer to be run over and over again.. the variable i iterates between 0 and 4.. and how in recursion calls another instance of itself.. move to the next page. Otherwise. try reading this again. for when you need to wait for a On the following line. almost any requires a variable. and without loops almost . peculiar parts of any language. . a know only what input is needed and what output to expect. Ours is used several of no . in the more complex solution. } When compiled. The for loop is one of those they’re self-contained islands of Using loops and using loops If we have explained how to use loops adequately. A loop is a >>> for i in range (5): much more primitive construction. condition. perhaps. In many ways. This is because for is slightly different from most loops. A fter losing ourselves in the surprisingly complex problem by adding a loop in your code. because while combines a conditional statement within a loop’s structure – they’re both designed to be re-run over and over again too. we print the value of i. A loop. output from the syntax of the for loop. and that’s the for keyword. “Without loops. This is followed add the source code to a text file them in our become impossibly tedious” in Python by the phrase in and build it with examples in range (5). ‘g++ helloworld. typical for loop looks like the following: Everything else should be handled by the function. the programmer needs to syntax that doesn’t feel that logical. or how you might attempt to solve a linear But without prior experience. i++ ){ cout << i << endl. the most common loop It’s different from a function or a method. usually to build a programmers use them to solve problems. They’re used as counters. You just have to accept that whatever syntax they do use does the equivalent of defining a variable and creating an acceptable set of circumstances for the execution of your program to leave the loop. that the initial for statement If you want to Loops are so integral to code. In our previous example. We print the value of i within the loop so you can see what’s happening. which for some reason is nearly always build your own C++ application. But we’ve not spent be tabbed or spaced in because it’s going to be executed as Just run ‘. i < 5 . keyword in Python that we’ll revisit in a couple of paragraphs. But where a loop or function to a simpler concept. print (i) any programming task would become impossibly tedious. WorldMags. they’re domain of using numbers in our code. This is because they encapsulate what computers do well: 0 repetition and iteration. and write code that 2 can’t accommodate unknown values or sizes.. If you write the same thing in C or C++. In the case of Python.

check. within your block of code. However. This is exactly what the Python loop is doing. many languages also It’s simpler this way. as follows: it illustrates one example where do. the output is identical to our Python example from earlier. and building into your code the certain Coding Made Simple | 51 . This includes only the conditional if you use a do. This might sound like insanity if you ever want the Quick while. This can be helpful in arguing against infinite between compiled languages such as C/C++ and interpreted languages such as Python and JavaScript). The advantage of farming it out to a function is that do { you experiment you’re no longer restricted to using it in just the for loop. but it’s slightly more efficient and elegant alternative is a while loop. Using an because we’re used 3 infinite loop means you can be sure your application is to thinking of zero as nothing. but it’s 2 running. for example.. Of course. Range is a function in Python that takes a start point. you need to have first grabbed the input... such as the first position in an . break can be used to rather than adhering to those required by for. and you’re free to make that check positive in any way This is all the above loop is doing in C++. you could modify the for loop. Using break. but this can take take some input and then only test against that input at the more effort and might not be as efficient. so you could get the value of i to count down instead by changing the loop to: for ( int i=5 . by making the while loop wait for a variable consist only of the x character. and that’s using conditional checks for leaving a loop as complex as you need. Q WorldMags. as you don’t need to restrict yourself to numbers – range can use indices of Python is still a sequence. where the use of an infinite Nearly all languages >>> while i > 0: loop is the best way of building your application. You should be able to see from this that both the value of i and the value checked for by the condition can be changed. If you want to check the state of some print (i) input. the while statement at the end of the normally use this section of code to tidy up files. an infinite loop – simply a loop that never satisfies its exit In Python.. but not Python. because the do is used to start the user wants to quit the application.. WorldMags. is to place the conditional loops early if you need to. It’s also much more versatile. and isn’t useful in itself.while works well. but typed your code. like this: processor to skip over the remainder of your code. It grabs some input you choose. and the cout line is simply printing out the value of i during each iteration. the best you enter the loop. for example. If you wanted to count down in Python. This seems . and just something you 1 using while is probably the easiest way of creating one. and hasn’t exited under some other condition. this function would look like this: smaller applications.while loop to encapsulate the entire function. we need to take a closer look at the range keyword used in the first example. If you put on one value in the range. there’s a good case for while there are still some dirty plates’. 0. whether it’s from a file or from someone typing on the keyboard. One example count zero as a . and for i in range(5. However. much the same as the inputs for a C++ for loop. i -= 1 is if you want to build a tool to monitor the state of a server or value. i > 0 . and you’d Most importantly. a stop point and a step size. and cin >> c. } To do the same in Python. and by using while you can make the provide an escape from loops like this.. as well as leaving other kinds of other languages. the variable i is declared as an integer (int) and incremented (i++) one value at a time for as long as it remains less than 5 (<5). such as when you want the loop to ability to escape on a specific condition. because it lets effect. we could recreate the previous for loop using condition. and languages. for example if you have detected that the called a do. the execution section and the while is used to close the section. -1): that’s taking input. Another trick in escape from an infinite loop. array. something called the break command.. In C++. to reach a certain value. processes loop is checking the condition.. the function counts from zero up to to learn with the value -1. You could Infinite loop do this in a normal while loop by asking for the input before If you don’t need the iteration of a for loop. after which it quits the loop. 4 controlling the rendering within a game engine. anything else will create a different char c.. i--){ cout << i << endl.while loop... This is normally for loop quickly. but there tip >>> i = 5 are certain times. of your code continues after the loop section. This example is oversimplified. You also find infinite loops watching hardware inputs or illogical at first.. print (i) some other service. such as ‘do the washing up and memory before an exit. You could easily emulate the behaviour of a for from the keyboard using cin. Another common use for while is to create what’s known as make sure your calculations attain that value at some point. 0 (true) {} is all that’s needed. Then. especially for end of the test. as we a great language did in the original loop. and see results you’ll find many programmers use range for convenience } while (c != ‘x’). while have to get used to. and waits for that input to loop. In the C++ code. You might want to escape from a checking at the end of the block of code. as soon as you’ve throughout their code.

resulting file isn’t intended for human consumption. wouldn’t it? Finding mistakes puts(“Hello. from the GNU project. but Compilers exist for many different programming they don’t understand human languages. and that is what we are going to directly tell the CPU in English that we want to print a use here.c and then run the following commands: gcc foo. C omputers aren’t actually very smart.. Then main you’ll just see code is processed. we have to somehow tell the machine this information Dissecting a program in binary. human.c from the source code into a binary executable file called a. such as the zeros – because that’s all that a CPU understands. and it’s one of the most important components of a million things in the space of a second. and readable source (stdio). The execution should begin). like this.out: ELF 32-bit LSB executable.out. for GNU/ Linux 2. First of all. this makes things a bit complicated.. not stripped If you try to examine the file yourself. but there’s a difference between compiled and interpreted languages. If you’ve never seen C before. This is because we mere mortals can’t read binary. enter this command: 52 | Coding Made Simple WorldMags. would be nigh-on impossible. Sure. as in the screenshot shown on the left. pulled apart.out The first command uses GCC to compile foo. to transmit videos of cats around the internet. and the second line runs it. languages. This final. then you’ll just see gobbledygook./a. Ultimately. In a code is processed. pulled apart the #include line says that we want to Try to read a binary compiled and converted into binary code” use standard input executable file in language. { That would be a nightmare. imagine if your programs looked like this: First up. but here we’re going to focus on C. to fix this problem. converted into binary code that the CPU can understand.out – you’ll see output similar to the following: a. So. and output routines a text editor.c . and so less is trying to convert it into plain text characters.out for instance. But then. consider this simple C program: 10010010 11100011 #include < . and the puts command means “put up characters program that does this is called – naturally enough – a string”. For us Linux kernel. using less a. Intel 80386. dynamically linked (uses shared libs).6. where a load of messed. source brief explanation: on the latter later). they can do a compiler. jumbled up and eventually says that this is the main part of our program (that is. version 1 (SYSV). WorldMags. Enter this text into a file called foo. the entire concept of This simply prints the message “Hello world!” to the free/open source software falls apart.h> 01011011 10001101 int main() . wait for a key to be pressed and so forth. By far the most common compiler on Linux is programmers. because it’s everything in a computer boils down to binary – ones and the language used for many important projects. but we can peek into some of the stages in the compilation process. you might be a bit we use compiled puzzled by some of and interpreted the text. We can’t GCC. and help us an operating The magic of compilers A compiler turns human-readable code into machine code. You can get more information about the resulting file by running file a. so here’s a languages (more “In a compiled language. message on the screen.15. and if you gave your code to } someone else for modification… Well. screen. world!”).

Q the puts (put string) function from the C library. and (a. into CPU-understandable instructions. an interpreter reads It doesn’t know what’s coming up. call 80482f0 <puts@plt> the loop is going to be executed five Interpreted languages can. using the objdump 10 LET A = 1 interpreters allow you to pause them command. and it’s called assembly language. such as important. Assembly is a human-readable way of representing the instructions that the CPU executes. Most of them are unrelated to our program. this places the location of our “Hello world!” fundamentals. parsing complicated it’s a list of CPU instructions written in a slightly more instructions. and benefits. is a entire source code file and converts it much simpler program that simply those human-readable instructions into their binary into CPU binary instructions in one fell steps through the program line-by-line. Assembly But wait! There’s an intermediate step between the C code and binary. instead.h file have been included in it. knowing in advance that each line step by step during execution.LC0. the compiler can be useful where speed isn’t crucially a moment ago. and on the right a disassembled binary. (%esp) been written about the science of compilers – it’s not a call puts subject for the faint-hearted! But now you know the Essentially. in that you don’t have to Jump back! at run time.c > foo. GCC now runs an assembler to convert a program called a compiler takes an An interpreter. In larger.p WorldMags. As we’ve seen in the former. So. This file is then complete. In assembly. Those are the exact same instructions as the ones we saw times. the compiler can spot bare like this. So. In other words. where you can simply say “print a We’ve highlighted the areas showing identical instructions.(%esp) bigger picture. With the -E switch. the output from gcc -S.p in a text editor and you’ll see that it’s much longer than the original program. -E or -S switches). most programmers prefer Have a look at the list file now – it’s a disassembly of the 50 END compiled languages over interpreted binary file. without the interpreted. with all the information that GCC needs to start converting it into machine code. These two lines are exact CPU instructions – as programmers. expressed in a slightly different way.c language such as C++ is an even harder job than writing an This produces a file called foo. Having your whole work prints a message five times on the are used to tell the Linux program loader some useful things screen. programmer about them. But tucked away in there. the compiler does much more work in this ‘pre-processor’ stage. and we have a individual lines from a source code file just dutifully executes things as and program that’s ready to run. In contrast. Precision and the process of how human-readable source code is converted PRINT lines if that makes execution individual execution rule here. programming language: compiled and errors that might come up and warn the In the normal process of compilation (that is. for example the Bash replacing the whole bunch with five scripting language. that’s make various optimisations.out > list 30 LET A = A + 1 of execution. This offers some essentially interpreting each instruction advantages. Similarly. it can be quite humbling to see single instructions laid There are two main types of quicker. Given that modern CPUs execute billions of instructions per What are interpreted languages? Coding Made Simple | 53 .s that contains the operating system. and you will certainly look at your code in a text string into a register (a little like a variable). and acts on them one at a time. It then adds extra information to the resulting file swoop. readable form. when it sees them. because the contents of the stdio. For instance. Consequently. take this wait for a compilation process to finish We can take the a. now enter this: that writing a fully-featured compiler for a complicated gcc -S foo. telling the CPU exactly a compiler are deep and complex. and then calls different way from this point on. like so: 20 PRINT “Hello world” and make changes in the middle objdump -d a. more complicated programs. in terms of managing variables. but these are the Don’t think for a second that we’ve completely covered two most important lines: the compiler here. It’s much lower-level than typical languages On the left. how would a compiler look condensed down into CPU-readable and set up the environment. Open foo. you’ll at it? Because a compiler processes the binary makes for better performance find these lines: source code file as a whole. passing control around to different functions. such as C and Python. we tell GCC that we don’t want a binary executable file just yet. you have never touched assembly before. and many process. equivalents. The inner workings of WorldMags. Most of it will look like complete gibberish if and so on. handles #define statements and places additional information into the file for debugging purposes. string for me”. It’s only right at the bottom that you can see the main function and our puts instruction. on the other hand. and therefore full of assembly language It’s pretty clear what this does – it ones because of the performance instructions. it sees the than a background program parsing movl $0x8048490.out file and go one step backwards in the BASIC program: before testing your work. we want only to see what happens after the first stage of processing. and many would argue which instructions it should execute. It expands macros. to the assembly language stage. gcc -E foo. 40 IF A < 6 THEN GOTO 20 Ultimately. you have to move memory around into the video buffer – for instance. Shelves full of whopping great books have movl $. Think of all the work a compiler has to do assembly language version of our program. however.out) to make it a valid Linux executable. there is no way that we can break them down into smaller pieces.

or it could be as complex as describe what it does and how it does it. forcing you to sell your home and declare what your own code does. and because self-contained code functionality is easier to test and forget about. When you going to write or how you’re going to solve a specific problem. you’re not expected to understand you should always go back and clean up whatever code you how a specific function works. This might sound strange. they are there purely to help could also mean a subtle rounding error in your tax returns other developers and users understand what a piece of code that prompts the Inland Revenue to send you a tax bill for does. you need to change over time. Even if you’ve had four cups of coffee and triple- check every line you write. This might mean it interpreted by the language or the compiler – they don’t crashes and dumps the user back to the command line. the comment will also be coloured differently to make it more obvious. way. Finding the problems weeks or months. But we don’t mean you need to write a book. You need only to study the The IDLE end up with. one of the most frustrating things you have to the delicate art of troubleshooting. for example. while you can’t always plan what you’re This is exactly how external libraries and APIs work. memory problems or just inefficient code. Either simple text descriptions about what your code is doing. your usually including any inputs and expected output. It might be as simple as a typo – a missing revisit these old bits of code. Comments are broken logic. Keep your words as brief as they need to be – sometimes that might mean a single line. You should model your own comments on the same idea. but no matter how clear your insight might have been when you wrote it. hunting down problems than you do coding. But. you don’t your variables making your project as easy to understand as possible have to know how it manages to be so efficient. When your applications grow more complex than calculates and how it works. both because it makes documentation easier. In Python. t doesn’t matter how much care you put into writing your becomes important as it starts to grow. documentation of the interface and how to use it within the Python IDE has a redundant variables and bolted on functionality into illogical context of your own code. but you don’t really want to cause too many. even though do is solve a difficult problem twice – once when you create our examples of code from previous tutorials stretch to no the code. If you want to can show how code easier to maintain and easier to understand. Everything a programmer needs to debug mode that places. they are there to remind you of millions of pounds. WorldMags. and your skills in programmer. you can spend more time you to understand anything about what a piece of code does. How you add comments to code is dependent on the language you’re using. They’re not program won’t do what you wanted it to. The importance of documentation The first is that. give it a few days. install Avoiding common coding mistakes Bug reports are useful. the second thing you should do is add a few comments to bracket or the wrong number. and again when you want to modify it but don’t more than 10 lines. the results will always be the same – at some point. before you worry about debugging. and it may as well have been written by How quickly your mistakes are detected and rectified is someone else for all the sense it now makes. But it affect how your code works. Everything that comes after this symbol will be ignored by the interpreter. know only what to send to the function and how to get the results back. Going back and cleaning up these areas makes the know should be included in the documentation. you should follow a few simple rules while writing your code. sooner or later you are going to make a mistake. Here’s what to avoid and how to avoid it. And as a dependent on how complex the problem is. you’ve probably needed to debug them as understand how it works. for example. comments are usually demarcated by the # symbol in the first column of a line. The more detail 54 | Coding Made Simple WorldMags. or may even obviate the need for just a few lines or functions. for instance. yourself bankrupt. And use Qt’s excellent sorting algorithms. For instance. and if you’re using an editor with syntax highlighting. Which is why as you need to know only the inputs and outputs. more importantly. A line or two of simple description you’ve transferred them from these pages to the Python can save you days of trying to work out what a function interpreter. and you seldom I code. Whenever you write a decent chunk of . This is because it’s likely you’ll have used now.

for example – although Python is pretty better wear your flameproof jacket for that release. When you start to code. for case sensitivity. This happens in C or C++. Most languages offer both inline and block comments. This is why it’s often a good idea to create your own variable names out of composite parts. give it to other people to test. you need to test it variable only after you’ve assigned it a value. something ready to release. Python users can denote blocks of comments using a source code literal called a docstring.Though not a programming language. But this does be. Initially. Q Comment syntax Different languages mark comments differently. if sense of code hierarchy. If you’re using an IDE. and usually have for example. However. but expect. which is Python a convoluted way of saying ‘enclose your text in blocks of triple quotes’. if. or that it needs a runtime errors. you use a variable without first saying what type it’s going to is all that’s needed to create unpredictable results. And when you’ve got you’ve assigned it a value. we’ve included this because you’re likely to have already seen the syntax. and they’re initiated by using a couple of little consensus on what a comment should look like. difference between compiled languages and interpreted ones. C/C+ can be – not just with the kind of values your application might even more random. and there seems to be of code on the same line. Python enforces this by breaking are in the correct A related problem that doesn’t affect Python is using execution if you get it wrong. you can go back and flesh out your thoughts when you don’t feel like writing code (usually the day before a public release). you’ll introduce many errors without realising it. or a comment after a piece different start and end characters. Watch out for using a single equals sign code be ready for the wild frontier of the internet. else. colon at the end of compound statement headers. such as int x to declare x an integer. When # is followed by a ! it becomes a shebang # and is used to Bash tell the system which interpreter to use. you can’t assume a default value created don’t make sense. for example: #!/usr/bin/bash BASIC REM For many of us. and sometimes a misplaced bracket script won’t run. this is the first comment syntax we learn C /* This kind of comment in C can be used to make a block of text span many lines */ C++ // Whereas this kind of comment is used after the // code or for just a single line <!-. WorldMags. there’s a good chance that its syntax highlighting will stop you from using a good at catching these problems. but with an extra * at the beginning */ = heading Overview As well as the hash. It’s only after doing this can make Python trickier to learn. not necessarily generating an error. Typing print (x) in Python. # A hash is used for comments in many scripting languages. If necessary. lambda. of text (or code you don’t want interpreted/compiled). but with anything that can be input. Your code should the value held in an uninitialised variable is unpredictable until fail gracefully. in Perl you can also use something called Plain Old Documentation. class and Coding Made Simple | 55 . especially with keywords and your own instance. if you don’t stop a lot of this you can use the variable in your own code. like this ‘’’ WorldMags. Typos are also common. and you’d to check for equality. This is the big know about its strict tabbed requirements. there are characters before the comment. Block comments are used to wrap pieces a couple of rules. will result in an error. but other languages try to make place. you won’t know what is and isn’t a keyword – a word used by your chosen language to do something important. Only then will your syntactically correct. To begin with. with x = 1. in action --> Java /** Similar to C. This is because the interpreter knows the type of a When you’ve got something that works. the errors However. This is careful in Python that the colons where conditions and functions use code hierarchy to split and indentation Undeclared values the code into parts. Inline are usually for a single line. Python is good at avoiding is inaccurate indenting. in both languages. rather than go with real words. because it can span lines. rather than randomly. Each language is different. where they can go undetected because they are your code in ways you couldn’t imagine. but don’t write a book. or your undeclared values. so make them as brief as you can without stopping your flow. but not if you precede the line variable names. for instance. as well as less obvious words such as yield. import. but it does Perl force you to explain your code more thoroughly =cut ‘’’ As well as the hash. and HTML therefore comments. Adding comments to code can be tedious when you just want to get on with you put into a comment the better. You also need to be careful about for an uninitialised variable. However. raise and assert. but Python’s list of keywords is quite manageable. for example. especially in conditional They’ll have a different approach. It has a specific format. and will be happier to break statements. Another type of problem You have to be protected keyword. and includes common language words such as and.

net .net WorldMags.WorldMags.

..............WorldMags............................................................ 76 Databases ...................................................... 70 Modules 74 ...................................... 78 Coding Made Simple | 57 ....................................................... 64 UNIX programs part 1 ........................................ it’s time to advance your skills Data types ....................................................................... 66 UNIX programs part 2 ............................................................................................................................................................ 58 More data types .................................................................... Persistence .... 60 Abstraction ................................................. 62 Using files .................................................................................. 68 UNIX programs part 3 Further coding Now you’ve got the basics down..............

‘a’]. including slices. or integers. The computer has a few basic If you combine different types of numbers. ‘Fish’]. 65 The computer’s world is a lot more limited. It returns looking only at particular. type retains the most detail – that is to say. these are like a You can also use the same operations on strings and lists. we’ll look at a few more advanced topics that build on what we do here: data abstraction. In later articles. for example. there are all the different types of food multiply two numbers and Python will return the result: and the list that stores them – each of which has its own kind >>> 23 + 42 of data. What makes them I Python and the concepts that accompany them. In You can test this by using the type() function. Python knows about the type of whatever argument you pass to it. the elements are all strings. [‘Bananas’. ‘cake’. but it’s data that they operate on. such as ‘Hello World’. For instance. WorldMags. such as <type ‘float’> you’ll see a TypeError. there are lists. while the * operator repeats the contents of the string or list. basic data types. in a data in Python. 10. other types of numbers. >>> word = “Hello” >>> word[0] ‘H’ >>> word[3] ‘l’ >>> list = [‘banana’. too. but that doesn’t 2 stop it from working with them. 3 and 2580 are all examples of these. Lists are identified by the square brackets that enclose them. 10. but they have different effects. subtract. divide and shopping list program. Let’s go through the basics of data in Python. the value returned by Python will be of whatever represent all the variety in the world. and more. You can use >>> type(8 + 23. in that they are a sequence. the interest There are lots of things you can do with the different types of rate and the term of the loan are all types of data. In some ways. we’ll be covering the basic data types in string. which begins from 0. such as an int ones it can work with. There are also strings. Finally. The + operator concatenates. It doesn’t know >>> 22 / 11 the difference between all these data types. In a mortgage Working with data calculator. >>> type(8) in real programs floats (such as 10. there’s an amazing variety of different types of data. n this article. but you could create another list that mixes different types. too. such as such as trees.01) wrong type can ‘Banana’ and ‘Pizza’. These are identified as a sequence of <type ‘float’> cause problems. >>> “Hello “ + “World” “Hello World” >>> [“Apples”] * 2 [“Apples”. characters enclosed within quotation marks.35 or 0. In this example.8413) and complex (complex <type ‘int’> getting the numbers). we have and a float. and in the programs that we’ll write. the value of the .net Different types of Python data Functions tell programs how to work. In the world. and that you have to use creatively to and a float. “Apples”] Strings and lists also have their own special set of operations. if you add an int We’ll begin by highlighting three data types: first. two strings or two lists. ‘Oranges’. If you want to reference the last 58 | Coding Made Simple WorldMags. [‘Bananas’. While we’re numbers. and each item or element within them is What is data? separated by a comma. you can add. >>> type(23. These enable you to select a particular part of the sequence by its numerical index. these are ints. the returned value will be a float. ‘tiffin’] >>> list[2] ‘tiffin’ Indexes work in reverse. including longs (long integers). that is combines together.01) in which case either double or single quotes. fancy structures different is that the elements that make up a list can be of any type.

‘tiffin’. together. The second word in that construct function to a variable name: doesn’t have to be item.lower() English language dictionary. You can also see this in action if you apply the type() on each item in the list. ‘tiffin’. You’ll find you create a tuple you cannot change it – and that tuples are lots of useful tools. among the list type’s methods are append and insert. To see the order of the arguments and the so long as it’s unique within that dictionary. These are known as methods. Then you pass any arguments identified by round brackets. For example. It’s quite like an see how different >>> word. What makes them different is that they’re associated with a particular piece of data. It works the same with strings and any other data a tuple in that they contain a collection of related items. once provides for the data types we’ve looked at before. such as sort and reverse! Q WorldMags. too: differ in that the elements aren’t indexed by numbers. and hence have a different syntax for execution. ‘cereal’). we created the list as we would normally. Tuples are very similar to lists – they’re a sequence data In the meantime. They make it >>> english[‘free’] easy to manage all the bits of data you’re working with. and to tuples and dictionaries (which we’re immutable data type as the key (strings are immutable. WorldMags. the indexes don’t start at 0. If you try to use full range of methods available. -3 the third. then a single equals sign. we used the idea of variables to ‘as in beer’ make it easier to work with our data. The big become familiar with some of the other methods that it difference is that tuples are immutable – that is to say. -2 will reference the second-to-last character. >>> list. we’ll be ready to look at how you There are two other common types of data that are used by can put this knowledge to use when modelling real-world Python: tuples and dictionaries. and so on. Consider this data that you want to assign to that variable. but by Python code and >>> word = “HELLO” ‘keys’ and are created with curly brackets: {}. that’s just a variable name that >>> type(word) gets assigned temporarily to each element contained within <type ‘str’> the sequence specified at the end. about to look at). The key is the word that you’re data types work ‘hello’ looking up. too). ‘cake’. ‘burrito’] to the variable. read the Python documentation to type. its previous association is forgotten Python documentation. ‘chicken’] >>> list. and the value is the definition of the word. ‘chicken’] As you can see. you can use any lists and strings. problems in later articles. They’re similar to functions such as type() in that they perform a procedure. you’ll need to consult the an already existing key. and ‘as in liberty’ greatly reduce the complexity of development (when you use sensible names). ‘tiffin’. ‘pasta’. ‘cake’. First comes the name of the of the sequence types is looping over their contents to apply variable. Variables are a way to >>> english[‘free’] = ‘as in liberty’ name different values – different pieces of data. then we element in a list by appending index notation to the variable used the for… in… construct to perform the print function name. you can use the same notation with a -1 as the index. >>> english = {‘free’: ‘as in beer’.append(‘chicken’) >>> list [‘banana’. In the examples. each unique to that particular Coding Made Simple | 59 . however. ‘tiffin’. small Python program: From that point on. ‘pasta’) >>> list [‘banana’. They experiment with object. completely and that data lost for ever. you are referring to the data that you assigned for item in list: to it. followed by the piece of an operation to every element contained within. a method is invoked by placing a period between the piece of data that you’re applying the method to and the name of the method. as opposed to square brackets: The Python interpreter is a between round brackets. ‘linux’: ‘operating system’} Variables >>> english[‘free’] In the previous examples. but with the Other data types basic data types covered. and they can contain elements of mixed element of a list or the last character in a string. just as you would with a normal (‘bananas’. Looping sequences As we saw above. Methods Lists and strings also have a range of other special operations. Note that when working backwards. whenever you use the name assigned list = [‘banana’. in Python you create a new variable with One common operation that you may want to perform on any an assignment statement.insert(1. There are lots of different methods that can be applied to With Python dictionaries. That’s all we have time to cover in this article. Dictionaries are similar to a list or great place to function. we saw this in action when we print item referenced the second character in a string or the third First. We could just as well >>> type(list) have written for letter in word and it would have worked <type ‘list’> just as well.

We demonstrated how they work with different operators. 60 | Coding Made Simple WorldMags. . The first is the name of the file to open. we’ll be using The Time Machine. WorldMags. and that we’re counting individual words. should be opened in: r stands for read.-. not lines.python. we introduced Python’s most tm = open(‘timemachine. lower() and split(). by HG The result should be every line of the file printed to the Wells. the first being None and the second being common word the list of characters to be deleted./:.txt’. For example.<=>?@[\\]^_`{|}~’) Machine. the and The). which removes specified characters from the beginning and end of a string. strings. By putting this code in to a . tm. the program will print the today we’ll be using a for… in… loop. lists.. consider the same word but in different cases as one word. As an example. program.. the entire path would have to be most useful methods. give much insight given. Looking at the Python string documentation (http:// docs. ‘r’) I common data types: numbers (ints and floats).net .txt. such as all punctuation marks. To see how this works. screen. We didn’t. whitespace characters. w for write or rw for read-write. removing a set of characters. by lower() speaks for itself.. results to the screen. We’re going to write a program that counts the number of Notice we’ve also assigned the file to a variable. which you can download from Project Gutenberg.strip() Hardly When passed with no arguments. tuples and dictionaries. with punctuation. There are several ways to do this.. we also need a way to different cases (for example. we can see that there are four methods that can help us convert line strings into a format closer to that specified by the description: strip(). and explained a few of their In this example. however. It should look like this: try opening timemachine. really – it converts every character in HG Wells. it needs to be passed be the most two arguments. n the previous tutorial. but to represent a single word.translate(None. Each of these are methods. ‘!”#$%&\’()*+. we have been able to read only entire lines as strings. in The Time >>> line. which is one of the jobs we needed to our counting get done. In this article. open() is passed two variables. is used like this: >>> line. so we times each unique word occurs in a text file. The second argument specifies which mode the file into how they might be used in real situations. however. it removes all surprisingly. and if the same word occurs but in With a reference to the file created. As it stands. strange whitespace characters (such as \r\n) and different cases intact. To use it in this capacity. but you can also use we’re going to fix that. strip(). the first thing we’ll Cleaning up need to do is make the text accessible from inside our Python The program description also specified that we should program. This is done with the open() function: exclude punctuation marks. Finally. after The function translate() is a method that can be used for being sorted. say More Python data types Learn how different types of data come together to solve a real problem as we write some code that counts file. they will be taken access its contents. marks will be in the interactive interpreter the: 123 and then typing: you: 10 >>> for line in tm: a: 600 print line . we’ve saving it in the same folder as your Python file under the got the start of our Python program. Punctuation can refer to it later in the program. finds ‘the’ to from a string. As the program description suggests. translate(). and as such they’re functions that are applied to particular strings using the dot notation. if it were in a different directory from the Python name timemachine.

abstract program. there is still some work to be for word. but in every line contained within This for loop looks different to what you’ve seen before. This dict[word] = 1 made sense until we wanted to consider unique instances. adding each entry to type for representing different abstract concepts. and in the process got to the exact. we started off with a single string occurred once in the file). incrementing it as the . one entry on a line. we’ve been able to remove all the bits of Another data type wrestled with. split() splits distinct elements inside a string in to separate strings. the key-value What’s more. At this point. is an Because all of the string methods return a new. concatenate an integer and a a string to lower-case. rather than operating on the existing string.split(‘ ‘) In this example. Uniqueness Phew. too. By passing an argument to split(). very end of the file. With all punctuation removed. Try running it. That’s all we planned to achieve in this particular tutorial and Next. if the key already exists. we can use the value to store the number of filled with lines like: times each word has occurred. how to use them. the entire file. returning them as a list.translate(None. representing an entire line. and you should see your terminal screen What’s more. which is ready to receive Data everywhere! our words. It should now look like this: tm = open(‘timemachine. Put all of this in the Python file we started working on earlier. program comes across new instances of each key. representing a line. [\\]^_`{|}~’) dict[word] = 1 http://docs. representing another occurrence. we As a further programming exercise. Notice. overwritten and the count will be reset. >>> line.<=>?@ else: Coding Made Simple | 61 .. and ensuring that it sick: 2 persists for the entire file – not just a single line – by placing ventilating: 2 this line before the start of the for loop: . thinking about uniqueness is of a dictionary. we are available and increment the count by 1. into smaller chunks by converting print the dictionary and put it all together and run the it to a list. ‘r’) for line in tm: line = line. As we saw last time.strip() dict[word] = count Python’s Standard Library line = line. We now need a way to identify which words are unique print word + “: “ + str(count) – and not just in this line. we’ve and seventh lines.-. count and 1 are assigned to that key’s for discovering re-assigned the line variable in each line to store the work of value. we’re guaranteed there won’t be any duplicates. line = line. we hope to the dictionary. ordinarily a simple chance to see how several different types of data and their assignment statement would be enough to add a new word methods can be applied to solve a real problem. other: 20 Start by creating the dictionary./:. WorldMags. outside of the line-looping code. at But remember. dict = {} This creates an empty list = line.. the dictionary with a value of 1 (to represent that it has For example.Q WorldMags. and we’ve made considerable progress. what methods the previous step. so by entering each word as a key within a dictionary. Our stunning progress aside.count in dict. another step closer to our data that we weren’t interested in. and we eventually split this into for word in list: a list of individual strings representing single words. To get around this. we can The first thing that should pop into your head when access both the key (word) and value (count) in a single loop. It doesn’t allow duplicate count. inside the for loop. As well as having had a the dictionary. as the + operator can’t keys. all that’s left to do is insert some code to string. we’ve passed a single space as the character to split the string around. with each word in the string stored as a separate element.iteritems(): done. modified value and assigns it to the variable count. this will create a list. into a string. it returns the library. an integer..lower() This is a little bit confusing because dict[word] is being python. it’s possible to specify which character identifies the end of one element and the start of another. while in the fourth invaluable source string. the old value is which point we put everything in to a dictionary. look at all that work we’ve just done with data! By using Putting it together the string methods. ‘!”#$%&\’()*+. to save the fruits count += 1 of your labour.split(‘ ‘) used in two different ways.txt’. why not look into can place an if-else clause inside the loop: sorting the resulting dictionary in order to see which words if word in dict: occur most frequently? You might also want to consider count = dict[word] writing the result to a file. By using the iteritems method of the dictionary. respectively. that if a word is already in the dictionary. we’ve had to use the str() function to convert store we saw in the previous article.. We’ve also split one large goal. The print section should look like this and be at the concept we’re most interested in: words. We could then iterate over the list we you’ve noticed how important it is to select the appropriate created above (using another for loop). we need to think about a way to get each word into it’s actually turn out to be quite a lot. In the second line.

problems involving Pythagoras’ theorem. before returning to it in a later article.5 obscure code you have to copy and paste. only that want to consider is abstraction. We can treat the we’re first going to look at abstraction in general and as it square root button on our calculator as a black box – we applies to procedures. This second approach First. Solving building robust software). the more 1 2/1 = 2 (2 + 1)/2 = 1. I n the previous few tutorials. We haven’t listed the contents of each new function we’ve 62 | Coding Made Simple WorldMags. because it helps us to manage by thinking about square roots and different techniques for complexity. you can read about what is involved. As we repeat this procedure.5)/2 = 1. we have been looking at data. Square roots This a very powerful technique.0 guess (y). The next data-related topic we don’t care about how to calculate the square root. this time coming up with 1. 1. and even for finding the square root of a number. with a piece of code this short.5 2/1. You could type it all out again. we can do it and get the correct result. but the more typing you have to do. b): root. Creating abstractions can make code much easier to maintain. Calculators come with a button return the expected results – how would you start testing all marked with the square root symbol. and all you have to do is the parts to find where the error was? Finally. Sure. In most attempts. we’ll only make our guess more and more return guess accurate. to check that it works? What if this function didn’t method to find square roots. there’s useful code in here that could be reused in other functions. you’d have a terrible time figuring out what It’s a lot of work just to on earth it was doing. but before we get on to that. vital for steps manually.4167)/2 = 1.33 + 1. One of these was discovered by Newton. When working on and then we demonstrated how they can be put to use problems. finding them. we get closer and while ( Reliability by abstraction Think your code is solid? Perhaps it’s a bit too lumpy. we when solving a real problem.fabs((guess * guess) . or the code for improving a when you were at school. is what’s known as an abstraction. whether or not a guess is close enough to the actual result Luckily. written like this. would For instance. let’s start programming a lot easier. we introduced some of Python’s core data types.4167 = 1. but none of it is reusable because of the way it’s written.5 = 1.33 (1. we’ll never reach guess = (((a2b2 / guess) + guess) / 2) a definite result. we’ll reach a level of accuracy that is The first thing to note is that it’s not in the least bit good enough for our needs and then give up. What’s find the square root of a number.4167 2/1. assuming you were allowed to use calculators (and can you even identify it?). it would be very difficult to test the different you were in school. or copy and Guess (y) Division (x/y) Average (((x/y) + y)/2) paste it. and is consider the Python code below for finding the longest side of thus known as Newton’s method. take a look at the table below for how through it reasonably quickly and figure out what’s going on. we can then improve upon that result by averaging our a2b2 = (a * a) + (b * b) guess (y) with the result of dividing the number (x) by our guess = 1. such as those involving Pythagoras’ theorem. for Find a square root taking an average of two numbers. and the more likely mistakes are to make it in to your programming.4118 (1. So. this time we’ll take a brief hiatus never look inside it. To demonstrate how abstraction can help us. much easier .01): closer to the square root. every time you had to find a square technique that makes parts of this code as you go along (aka incremental root you had to do all these programming easier” development. we should start with a guess (y) of its square def pythag(a.4167 Let’s try writing that code again. how would you break out the code for testing be much more unwieldy. a right-angled triangle: It says that when trying to find the square root of a import math number (x). we don’t know how it does what it does.a2b2) > 0. you would apply this method to find the square root of 2 (for but at a glance it’s not obvious. WorldMags. for instance. which can make To get our heads around the concept of abstraction. from data.4142 some abstractions to fix the problems listed above. and if it were longer and example. all that matters is that we know how to use it and that it gives the correct result. such as that for squaring a number. Imagine if when “This is a very powerful more. there’s another. x). press this button once – much easier. Just to be clear readable.4118 + 1. Eventually.

we could change the implementation completely. def improveGuess(x. we can easily test it. Assembler You treat it as a black created. def closeEnough(x. WorldMags. To help keep a triangle is And. guess): . you’re not stuck with working Layers of abstraction through thousands of lines of code. . the purpose of which is also obvious. You just accept the fact that typing 2 + 3 in to the Python interpreter returns the correct result. For instance. we’ve split the code in to several smaller functions. function – six characters instead of four lines means there’s def sqrt(x.. guess): generally better. this example has demonstrated how powerful a section that finds a square root. These functions are now visible only to code within the improved by taking sqrt() definition – we say they’re in the scope of sqrt(). What’s more. Anything outside of it has no idea that they even exist. One final point: because our sqrt code is now abstracted. This code can be improved still further by taking layers of abstraction present in everything you do on a computer that you never think of. you could just call the sqrt() inside the definition of sqrt(): start. WorldMags. This advantage of scope” way. all code colliding names or the headache of figuring out what that relies on it would continue to work properly. each of which fulfils a particular role. to work with binary numbers. and far less opportunity to make mistakes. and you never have to worry about how it does this. guess): . manually changing every Hopefully. “This code can be .. and it’s done technique abstraction is... def sqrt(x. functions are unlikely to rely on their services.. we could quickly test all these auxiliary functions to particular to the sqrt() function – that is to say. This means that if you come across a much more efficient way of calculating square roots. leaving them for you to fill in. and translate alphabetic characters in to their numeric representations – There are layers of abstraction underneath everything thank goodness for abstraction!Q you do on a PC – you just don’t often think of them.. we can easily reuse any of these new our code clean.. of Coding Made Simple | 63 . other longest side of narrow down where the bug was. if we later need to define similar functions for improving a guess in a different context.. For example.. but so long def improveGuess(x. you can see clearly that a2b2 is the result of squaring two numbers. guess): . import math: def square(x): . we can place their definitions what we had to a different function.. Our final code If pythag() itself was found not to return the correct advantage of scope. and make the relationship between these longer than functions. for instance. guess): more robust. def closeEnough(x. do the improvement by hand.. Think how much longer it would take you to program if you Object code had to manually take care of what data went in which memory location. For starters. guess): . If you were finding the square root of a number in functions and sqrt() clear. This has many benefits. but it’s more readable. closeEnough() and improveGuess() are for finding the result.. because each part of the code has been split into a different function.. improveGuess1() and improveGuess2() do. def pythag(a. we won’t face the issue of as we kept the function call and arguments the same.. and then compare your results with those returned by the function. and everything below that has been consolidated in to a single function call. how much easier is the pythag() function to read? In the first line. you do it once. Bear in mind that there are many everywhere. b): a2b2 = square(a) + square(b) return sqrt(a2b2) Here. when you’re programming do you know how Java Python represents integers in the computer’s memory? Or how the CPU performs arithmetic operations such as Abstraction addition and subtraction? C The answer is probably no. testing whether improveGuess() was doing the right thing would be very easy – come up with a few values for x and guess.

or Google’s bots skimming websites for data to easy depending on how many assumptions the language is feed its search engine. This is read a file. because nothing is end in chunks the output from the command to a file called list. Python will generate a “No such file or directory” error. Every language will include functions to load punched cards to get patterns into a 19th century Jacquard and save data. as with most other languages. the current directory. before explicitly closing the directory. creating one if it doesn’t familiar with on the command line. reversed alphabetical list of a folder’s contents. but you able to change it. dealing with external input is as willing to make on your behalf. but it becomes difficult when you need to know where to store a configuration file or load a default icon. When you type ls to list exist. it won’t usually allow access. Most languages require you to specify a read mode outputting the contents to another. ls | sort -r will pipe (that’s the vertical bar same table. many data from the use that output as the input to another. logical sequence of events that need to . WorldMags. However. and if the filesystem knows the file is being step through its helps when you want to save the output of a command. and it’s one of the more tedious issues you’ll face with your own projects. exactly like a file. the inputs and outputs aren’t files in the sense filesystem whether to expect file modifications or not. And it’s a problem and a concept that you may be more You will first need to open a file. but that’s the way the Linux important because many different processes may also want languages will filesystem has been designed – nearly everything is a file. or changed. This is within the folder from where we launched the Python Files and modules done quickly It’s time to expand your library of functions and grab external data with just two simple lines of Python. we’re reading a character) the output of ls into the input of sort to create a In Python. If you know about databases. for instance. “r”) If the file doesn’t exist. or write data to the contents of the current it. folders and file locations can quickly become complicated. processes can access a read-only file without worrying beginning to the You may already know that typing ls >list. because this tells the When you Of course. most most people would recognise.txt. opening a file to line at a time. there’s always a fundamental as programming itself. we’ve used the output from our command line example to create a text file called list. contents of a file. with some creating keywords for common locations and others leaving it to the programmer. These locations may be different depending on your Linux distribution or desktop. you don’t get complexity of how data input and output can be far before facing the age-old problem of how to get accomplished is entirely down to your programming data into and out of your application. you might want to consider using environment variables. This to access the file. and then either read data from this file. In can take this much further because the output can be treated kind of problem you face with multiple users accessing the this example. but this can either be difficult or textile loom. they’ll also be different for each operating system. the file again so that other command is reading in the “If the filesystem knows processes can use it. To avoid this. These are similar to variables with a 64 | Coding Made Simple WorldMags.txt. For that reason. it won’t allow access” when you open a file. for example. and then the file is being changed. You’ll find that different environments have different solutions for finding files. Environment variables Dealing with paths. F or the majority of programming projects.txt”. the terminal.txt will redirect about the integrity of the data it holds. The write or as read-only can be done with a single line: >>> f = open(“list. Whether it’s using environment. This isn’t so bad when you only deal with files created by your projects. However. it’s the same you specify. but with a cross-platform language such as Python.

When you then try to read the input. If you type env on the command line. where file – or no file type at all if it’s raw data. Repeating the code you’ve just added to your project.environ[“HOME”]+”/list. Modules extend the simple constructs of a language to add portable shortcuts and solutions. But all we’ve done is open the Coding Made Simple | 65 . but not in the same way we opened list. most importantly. associated file Setting the standard Python knows which home folder is yours. as well as file input/output and support yet read any of its contents. for instance. turning code to your project: Binary files have no context the way they do things into a standard. and the one we have asked it to Which is why you default. and what it requires as an input and an output. binary file are organised according to the file type used by the If you were programming in C or C++. output when you for specific file types. use f. and more can usually be installed with just a couple of clicks Alternatively. and these embed standard os. You will find the documentation for what intuitive. which is why this is also the way nearly all does. at least for the initial input.txt”. is common to the vast majority of languages. Internally. You languages work. /lib/python2. They will become dependencies read it into a string. and you’ll see a few that apply to default locations and. you’ll see the file. This file is known as a module in Python terms. if you wanted to read the entire file. This might seem counter. Only it’s better than that. you’ll see a list of the environmental variables currently set for your terminal session. Look closely. the else. copying the But this is where the ugly contents to a Python string spectre of dependencies can is an easy conversion. you’ll see the and output this to the interpreter as a string. The start to have an effect on your “If you load os. This will list each function. which is what package managers do when to add a b flag when you first open the file. for example. you’ll need to do some extra provide a portable way of accessing operating system. The value assigned to this environmental variable will be the location of your home folder on your Linux system. because modules such as os are used by everyone. ways of doing many things a language doesn’t provide by an environmental variable.x will include all the The above instruction will read a single line of the text file modules. because Python is functions are now accessible to you. To see what we mean. you need to make sure that person has also got the code you’ve just added” organisation of the bits and bytes that make up a same modules installed. including statements and definitions.close might be. data types return is HOME. As you might guess. many different modules for Python – it’s this is being done using something called a pointer and this. If you load os. Getting back to our project. which is why other languages might call them libraries.”r”) without an This line will open the file list. for example. what it used to be stored. any other programming language) would be unable to extract those binary libraries will also need to be present on any other any context from a binary file. The line to do this is: import os This command is also opening a file. Libraries and modules are a little like copying and pasting someone’s own research and insight into your own project. This includes knowing where your home directory f. f = open( into a text editor. we first need to add a line to import the operating system-specific module. you’ll see the hexadecimal values of the file output The os module to the display. so that a programmer doesn’t have to keep re-inventing the wheel. as this should ensure the integrity of your applications without worrying about where files should be filesystem. WorldMags. one called HOME. It’s only after a file has been opened that you should also be able to find the source files used by the import can start to read its contents: (and by #include in other languages). but they apply to any one user’s Linux session rather than within your own code. which we’ll look at next. add the following piece of And it’s as easy as that! Q WorldMags. As a global scope in many programming languages.readline() systems. too. and modules like this ‘import’ functionality. into a same isn’t true of a binary project. because the type and a way of There are even libraries called std. as well as which command will read the next line. make sure you close dependent functionality so that you can write multi-platform the open file. one of the best reasons to choose it over any other language. such as common mathematical functions. remembering how far through the file it has read. we’ve not get the raw data and string services.txt. The solution. you could from your package manager. the os module is designed to To make this data useful. but first. the command looks like this: placed. warns Python to expect raw binary. and if we want to use this within our Python script. because if you want to give your code to someone text editor. because this you install a complex package. There are many. causing an error if you try to system that runs your code. Because our file contains only text. is for your Python (or your code is compiled and linked against binary libraries. a library does within an API.txt in your home folder. Rather than being treated as text. but it’s an historical throwback to the way that files read one.environ function from the os module returns a string from handling them. On most Linux f.

or otherwise manipulate. it’s writing real programs” arguments: -E. so if you want to follow along. while using sends the output to standard out. because in Python files are iterable objects. line by line. not write to it. as follows: for line in file: print(line) The print function then causes whatever argument you The final program we’ll be implementing. and -n. send each line of the files to This means it won’t take too standard output. cat. we’re going to create a cat clone that can work with any number of files passed to it as arguments on the command line. Python files Let’s start with the easiest part of the problem: displaying the contents of a file. This time. at which point it because it’s small and focused on a single task.txt”. you access a file with the open function. because we passed a second argument to the open function. WorldMags. This is very easy to achieve. that when called with no we’re going to create a Python implementation of the arguments accepts user input on the standard input pipe popular Unix tool cat. the next task is to display its contents. but will also “You now know more whole of the first file. Create a Python program. We’re going to be using Python 3. “r”) This creates a variable. r.txt. this means you can access each line contained within simply by putting it in a for loop. which returns a file- object that you can later read from. like so: file = open(“hello. which will make it put $ signs at the end of learning the ins-and-outs of your chosen language’s libraries each line. With a file. file. which specified that the file should be opened in read-only mode. that’s what we’re aiming to do: get Our goal for the project overall is to: you writing real programs. It should accept two Standard Library. Iterable objects. It’s not long. different operating system features. displaying the long to should pipes and so on. Write your own UNIX program Try re-implementing classic Unix tools to bolster your Python knowledge and learn how to build real . such as make sure you’re using the same version. It will only allow us to read from this file. To capture this file-object for use later in your program. With access to the file now provided through the newly- created file object. number at the beginning of each line. In Python.x. then the expose you to a selection of Python’s core features in the than enough to start whole of the second file. on standard output. of core language features you’ll be able to re-use time and again. I n the next few pages. but it makes use of a lot pass to it to be displayed on standard output. When called with file names as arguments. 66 | Coding Made Simple WorldMags. Like all Unix tools. line by line. including accessing files. cat is a great target until an end of line character is reached. Over the next few tutorials. allow you to access their individual member elements one at a time through a for loop. because some features are not backwards- compatible with Python 2. to standard out. that will later allow us to read the contents of the file hello. tuples and dictionaries. strings. you need to assign the result of running the open function to a variable. and once you’ve mastered the basics. which will make it put the current line that will let you get on with real work.

Python this. so to access it. you need to loop over all the how much work is available for you to recycle).net If you put all this in a file. This simple shortcut function takes care of opening each file in turn and making all their lines accessible through a Many files single iterator. and how a files in the argv list. this is a fairly straightforward task. be able to use it to recreate the rest of our cat program so far. The part of the sys module that we’re interested in is the argv object. which is part of the Standard Library.argv[1:]: about this. there’s a glaring omission here: we would have to edit the program code itself to change which file is being displayed to standard out. when implementing new programs. add: import sys The output of the real Unix command. our program can only accept example. but compared to the real cat command. otherwise everything would be on one line!). you’ll see that it works rather well. you need to type In order to use this shortcut. WorldMags. provides a shortcut for doing To access the list.argv. Since Python has ‘all batteries included’. cat. but as things stand. operations. The Python interpreter automatically captures all arguments passed on the command line. and output all their contents to standard output. This tells print to put an empty from the command line.txt with sys. for line in fileinput. There is one oddity. our program is meant to accept more than one file That’s about all that we have space for in this tutorial. you must first import it by sys. you first have to import it to your program and then access its contents with dot notation – don’t worry. Knowing this. end=””). you’ll realise this is easily done with a slice. end=””) pass the name of any text file. Passing arguments This is all right. Instead. even if you can’t see it. much is available in Python’s Standard Library (and therefore To fix this particular problem. Because there’s already a newline character at the end of each line in hello. Even though sys is part of the Standard Library. First. to import it to your program. to the top of your cat. which means you can because this is the name of the program itself. we’ll explain this in a moment.input(): When you call cat.argv[1] to get the first argument to putting import fileinput at the top of your code. the second newline character leads to an empty line. one after Although there has not been much code in this particular another. or sys. called fileinput. make it executable and create a hello.argv[1]. named argument such as: print(line. so that we could call our new program by typing cat. Q WorldMags. This object stores all of the arguments passed on the command line in a Python list. You will then your program. are exactly the same in this simple example. makes this available to your code. say. You can fix this by calling print with a second. and it will work just the same. as well.txt (there hello. we hope you have started to get a sense for how one file as an argument. The only thing that you need to be careful good knowledge of its contents can save you a lot of work of when you do this is that you exclude the very first element. What we need is some way to pass arguments on the command line.txt on the command line. The reason this happens is that print automatically adds a newline character to the end of each line. and a module called sys. Of course. you should now be able to adjust the code as follows: we created previously by replacing hello. and our Python file. at the end of each line instead of a newline character. it’s not available to your code by default. however – there’s an empty line between each line of output. or no character. you need to use dot notation – that is to this in the Standard Library.txt file in the same directory. argv is stored within sys. They are: “The part of the sys Because operating on all The first element of the list is the name of the program module we’re interested the files passed as arguments to a program is such a itself – all arguments follow in is the argv object” common operation. you can then print(line. This is There are only two things just one line: you really need to know for file in sys. If you think access and manipulate it using various techniques we’ve back to our previous article on data types and common list seen in previous tutorials and will show in future Coding Made Simple | 67 .

. however. tuple or list) or a map (like a dictionary). saving you a lot of hard work. if it’s called without any arguments. we want it to Fortunately. which displays line numbers at the beginning of lines. the same is true. let’s dive in. alternative to sys. including the standard output. which will do most of the hard work for [OPTION]. seeing as we’re on a journey to are almost identical to those that we had last time. In Linux. otherwise do this with the standard input pipe is access to the sys library. Every time a actually provides us with a much more powerful alternative to sys. provided as part of the optparse module. you Parsing arguments and options will see what happens. which version: if you followed along last time. This function is built in to than specifying the name of a file. You may not have realised it. If it’s In Python. end=””) Pretty straightforward.] print(line. and -n. method for a similar purpose.. This is a special Enhance your UNIX program Our tour of the Python programming language continues. we are going to add two options to our program that will modify the output generated by our program. we’re going to add [Return]). It doesn’t matter which you do. To demonstrate this. We could a pipe as an just like the real Right.] import sys else: for line in sys. In this guide...python. but cat does in fact have a range of options. and the ability to pass options to your cat --help a string in order to remove all white space – in the tutorial. by concatenating the files’ interact with the standard input pipe. we treated like files – you can want our program to work by pass a file as an argument to repeating each line entered a command.. which shows dollar symbols at the end of lines. ability to read from the standard input pipe. find at http://docs.argv” check to see what the length of the sys. is an iterable object.. but we need to put them together into a single without further delay. you already know everything you need to work like last time – that is. [FILE]. If we call our program with arguments. All you need to get to work greater than 1. WorldMags. now we have two modes that our program can cat. it will simply wait. As well as automatically detecting options and arguments.stdin: [this month./cat. or you can pass “Python provides us with into standard input. it will then print everything that came before it to some more features to our program. The lines that follow the use of the len() function. which you can each line.argv. stdin. Rather discover different Python functions. which is found inside the sys string. we specified the Python. we used the rstrip Usage: cat. because standard input starts off empty. Let’s write a if len(sys..argv) > 1: little sample program first to demonstrate: [last month. We’re going to implement the -E.html. To do this.argv array is. 68 | Coding Made Simple WorldMags. T he previous tutorial showed you how to build a simple new line character is passed to standard input (by pressing cat clone in Python. OptionParser will automatically generate help text for your users in the event that they use your The Python language comes with all the bells and whistles you need to write program incorrectly or pass --help to it. however. all pipes are contents together. You might be wondering how this works. and can be applied to any type of sequence object (a name of the file-object. Just like a real file. we’ll start by setting up an OptionParser. In this example.. operate in. and Python that’s present straightaway. like this: useful programs. The only point of interest here is The first line imports the sys module. as we continue our clone of the Unix cat command. then do last lesson’s version. you already have. If you run the program. and it always module. you can see the replace method applied to [jon@LT04394 ~]$ . in Python the standard input pipe tells you how many elements are in that object. Rather than printing out everything This is quite a simplistic approach. program. though. so we use a for loop to walk through There are more useful functions like . a much more powerful easily do this with what we have learned so far – simply because they’re basically the same thing. So.

dest=”shownum”. org/3/ should be your first port of call.” a string. Let’s think about the the necessary components: -E. with everything set. as implied by pressing saw before. a new instance of the Coding Made Simple | 69 . the action store_true says to set the dest a little more complicated than it ordinarily would be because variable to True if the argument is present. removing the existing new line. WorldMags. add some new options for it to The first part. Next. help=”Show $ at line endings”) Completing the job parser.. it will strip parser = OptionParser(usage=usage) those characters from the right-hand edge instead of white parser. This removes all string to display: white space characters by default. can be detect with the add_option method. The still need to write some more dest argument specifies what logic to further control the name you’ll be able to use to “Don’t confuse yourself flow of the program based on access the value of an argument once the parsing has by putting the variables what options were set. You can call by investigating the string. We say “almost complete” because we the name of your program. you can keep yourself busy arguments left over after parsing out the options. -n. and False if it is we need to maintain a cumulative count of lines that have not.parser_args() functionality in a class. In this case. In our case. action=”store_ space. which means you’ll need to know a little bit about To get started with OptionParser. but the two will always be you can figure out how you can append a number to the set in the same order.Q WorldMags.. this logic needs to be be. in the arguments that were passed to your program and assign the next tutorial we’re going to introduce you to a bit of object- results to two array variables: oriented programming in Python and implement this (options. you’ll next want to start implementing the code -E Show $ at line endings that will run when a particular option is set. option first. If you ever wonder how to do something in Python. while the action specifies what that value should the other way around!” arguments are passed.format() method and see whether these variables whatever you like. [file].. action=”store_ The second part of the job is as simple as setting the end true”.python. or shownum. args) = important Python convention – the main() function and the such as -E or -n. option. and pass it a usage achieved by the string. -n Show line numbers we’ll be modifying the string of text that’s output by the Just like a real program! program. we’re only [Return]). You can read about other actions at been printed as the program runs to implement the second http://docs. We’ll also introduce you to a very The options variable will contain all user-defined options.add_option(“-E”. In the meantime. In both cases.add_option(“-n”. at the right-hand edge of usage = “usage: %prog [option]. http:// docs.rstrip() method. The thing is. --help show this help message and exit code written. true”.net The Python 3 website provides excellent documentation for a wealth of built-in functions and methods. you just need to parse the While there are several ways you could achieve this. All we want this to do is remove from optparse import OptionParser the invisible line break that’s at the end of every file (or every You may notice that this looks a bit different from what we line of the standard input pipe. or showend. dest=”showend”. just white space will do. Instead of importing the entire module. and replace it with a dollar symbol followed by a importing the OptionParser object. you first need to import Python’s built-in string editing functions. so don’t confuse yourself by putting the beginning of each line.. If you pass a string to it as an argument. help=”Show line numbers”) variable in the print statement to the string $\n and the job The %prog part of the usage string will be replaced with is almost complete. as well as whether or not any been done. you need to create line break. while args will contain all positional name variable.html.python. Finally. Options: variables the other way around! With the argument-parsing -h.

A class is a template. We’re going to turn our cat program into an object. such as moving one finger to press a key. because it mirrors the real world so closely. One of these is the init method. of thinking because it various paradigms that provide techniques for working program. broken down into objects which contain state – variables. the contents of multiple files to the screen. number option and to gather “It’s a very natural way To make this easier. and methods. with a those variables or with that object. we specify the methods (functions) and state that we want to associate with every instance of the object. and we can describe certain methods or things you can do with your hand. here’s our cat implementation. figuring out how to ability to echo standard input to the screen and the ability to organise them so they remain easy to read. WorldMags. or holding a cup. easy to track detect and act upon options passed by the user of our which variables are being used by which functions. You probably noticed the self variable. and its methods perform the action of the cat program – redisplaying file contents to the screen. and an object is a particular instance of that class. modelled on the template. or add new for us to implement the line features. Python objects Python implements objects through a class system. can be challenging. . such as having five fingers that are in certain locations. implement the same function with some It’s a very natural way of thinking. W e’ve come quite a long way over the last two nested for loops. One of these paradigms is Objects the concept of object-oriented programming. little careful thought. Your hand is an object. We can describe a set of properties about your hand. however. however. that are frequently used. much like we define a new function: class catCommand: Inside the class. we ended by saying that there are many ways we oriented programming. and allows you to set specific variables that you want to belong to that object. there are together everything else we’ve written into a single. and wondered what on options being put to use. and easy program. and we’ll be using this to record how many lines have been displayed. def __init__(self): self. complete with state and methods that let you work with it. in We’re going to show you how to do it in an object-oriented other words – that describe the current condition of the style. In object- Last time. mirrors the real world” managing complexity. 70 | Coding Made Simple WorldMags. that allow us to perform actions on aspect of Python programming. passed as Just to prove that it works. because it gives us an excuse to introduce you to this object.count = 1 In this case. There are some special methods. with all of the the first argument to the method. having implemented the ability to echo object-oriented code. we’re going to finish our clone of cat. where its state records how many lines have been displayed. This is run when the class is first instantiated into a particular object. the When building complicated Finish up your UNIX program Our guide to the Python programming language continues. This tutorial. All that remains is to update. although they’re not nearly as readable as tutorials. We define a new class with a keyword. the elements of the program are could implement the line counting option in our program. You could. we’ve assigned 1 to the count variable.

This isn’t actually – when the program is run on the command line. It might seem more natural If there weren’t any – given the description of methods as individual actions “The last thing to do is arguments. for a in args: The logic after that is clear – for each line in the current f = open(a. It lets us refer instance of a class – how we create a new earth that was What is new is then increment the count and print the line. reference to whichever file is being displayed at this moment.count += 1 print(line. “r”) file. is going to be a introduce you to many different aspects of the Python too. The completed program isn’t very long. because that hasn’t changed. use the run method attached to the same object each time We then check to see whether any arguments have been we cat a new file in the argument list. options): #set default options e = “” for line in i: #modify printed line according to options if options. The c object to variables stored within the current instance of the object. or otherwise required in Python.. [option parsing code . i. is that we if __name__ == “__ main__”: found it meant we could re-use more code. but not when we’re importing it as if len(args) > 1: a module. WorldMags. def main(): it’s not. passing in any options extracted by OptParse along the way. but many programs follow this idiom.format(self.count is a count variable that is exclusive to individual instances of the catCommand object. defined in the init method. The name variable is special going to do this by writing a main function. This is how we create an The most important part is the use of self. it is set to main. then we call the run method of the remember how many lines were displayed in the last file. This is what will enable us the current execution of the run method ends. count.] In this way. We are useful in a lot of circumstances. which will always point to the particular instance of the object that you’re working with. when it we will too: is imported as an external module to other Python programs. different method. i. the count will Coding Made Simple | 71 . and this is a when the program runs” The final thing we need fine way to approach the to do here is actually call problem. though. Well. it is the main distinguishing feature between methods and ordinary functions. now has a variable.. but quite Now all that’s left to do is to tie everything together. so as a standalone application.showend: [.stdin. which is accessible by all its Because it’s stored as part of the object. options) we suggested you research last time. must have the self variable. Q WorldMags. we simply call the run method that can be taken by our objects – to split each argument into a call the main function with sys. continue to count correctly. we can automatically execute main when run c = catCommand() as a standalone program. though.count.. however.. c. It is an automatically populated variable. using the . We previous tutorial. end=e) Notice that we’ve passed the self variable to this method. options) Either we do as last time. it will persist after methods as the self. but it has given us a chance to just like with a normal function.count variable. the main function when the program is run: The reason we’ve done it this way. line) self. So self. making it more main() readable and less error-prone.stdin instead of a file object. These last two lines are the strangest of all. If they have.last time] if options.format method that c. and modify the end character to be else: “$\n” or we modify the line. Methods.shownum: line = “{0} {1}”. The two other arguments passed to this function are arguments that we’ll pass when we call the method later on. modify the line depending on what options have been set. As long as we to track the line numbers. and object c for each file that was passed as an argument. We’ve called this the run method: def run(self. the c = catCommand() line. even those which have no other arguments. to append the count We haven’t filled in the object parsing code from the variable. The first. while the options variable is a reference to the options decoded by the OptParse module. to the rest of the line. The run method We next need to write a method that will execute the appropriate logic depending on whether certain options are set. . tablet & computer Be more efficient and increase your productivity Helping you live better & work smarter LIFEHACKER UK IS THE EXPERT GUIDE FOR ANYONE LOOKING TO GET THINGS DONE Thousands of tips to improve your home & workplace Get more from your smartphone. twitter.lifehacker.

com WorldMags. anytime.T3. WorldMags. now optimised for any .COM NOW LIVE Showcasing the very best gadget THE GADGET WEBSITE INTRODUCING THE ALL-NEW T3. anywhere. www. reviews and features.

import fact print fact. as two different result *= n parts of your program require functions called add (for n -= 1 example. Inside this. but – in Python at least – they’re really just plain which parts rely on each other to get work done – and it’s old files. this is a tool you’re no doubt desperate for. and we’ve them by typing the module’s name. in part because you don’t start to come across it clone. and the only tool you have to do that is boring factorial function. In our cat yet to cover. followed by the name of introduced you to quite a few of the tools and techniques the function we wanted to execute: that help programmers do this. the code that dealt with the logic of echoing file contents to Yet. or you may have written a useful Create a second Python file called doMath. as you’ve relied on Python built-in or third-party modules to provide lots of extra functionality. We could access programming is all about managing complexity. there are other your program. the location of which are defined when 74 | Coding Made Simple WorldMags. The big question that’s left is. and reusing this code was as easy as typing of the latest error. we specified in your import statements. becomes more difficult to read.OptionParser() definitions or object-orientation. didn’t have to worry about using names in our own program In a long file of code. You should notice that the name of enabling you to put structure back into your code. It first looks inside all of magically got access to a whole load of other functions that the built-in modules. file. if you’ve written a program of any length. followed by the function name. printing the result to the screen: and error-prone copy and pasting. You can try it out for yourself. remember The Python path the optparse module we used before. when you run the doMath. adding integers or adding fractions in a return n mathematics program). and when you’re trying to hunt down the cause namespace. instead we could focus on and name spaces. where you defined that all-important variable. define a function to visualise the flow return the factorial of a given number: “As your programs grow of data through def factorial(n): in length. With all How modules work your code in a single file. we didn’t have to wade through lots of code about until you’re writing larger programs. we few hundred lines. it’s more difficult to determine the Modules sound fancy. you should see Modules are a great way to solve all of these problems. 120 printed on the screen. we have mentioned how automatically parsed command line options. and you might think they’re dependencies between elements of your program – that is.factorial(5) Untangling the mess Now. in the same directory. From variables to function optparse. even just a the screen and to the standard output pipe. Functions seem to blur into because they were all hidden inside the optparse one another. avoid naming conflicts. and making it easier for you to share with the extension removed. complicated. As an file. you’ll have noticed how quickly it that might collide with those in the optparse module. how does Python know where We included it in our program along with the import to look to find your modules? statement. Create a new directory more difficult to and inside it create a fact. I n previous tutorials. Neater code with modules Untangle the horrible mess of code that you’ve made and add coherent structure to your programs. defined in that module by typing the module’s name. These problems are caused by a lack of structure. function that you want to share with other programs that first import the module you just created and then execute the you’re writing. What’s more. As your result = 1 while n > 0: problems that occur” programs grow in followed You’ve no doubt been using them all the time in your code by a dot. letting you the module is just the name of the file. if n == 1: result *= 1 there are other problems that begin to occur: for instance. One tool we’ve This was great from a readability perspective. else: you may find yourself with naming conflicts. Inside it. We can then call any function useful chunks of code between programs. they all help. you find it difficult to remember exactly import optparse – no messy copy and pasting here. is the idea of modules parsing command line . like so: The answer is that Python has a pre-defined set of import optparse locations that it looks in to find files that match the name After putting this line at the top of our Python program.

because each module has its own We have touched upon scope as a concept before. This demonstrates two The PYTHONPATH. Variable scope in modules In simple. which is a set of directories pre. use it often have learned a lot about the If you’re interested in finding out more pep-0008 best ways to do things in the language – about these best practices in Coding Made Simple | 75 . its a quick refresher.python. in how show_choc() the contents of the Python path are generated. you install Python. it then searches through a list of print food directories known as the path. Python starts with the attribute (typing sys. a accessed via dot notation. in which food refers to a list of chocolate. when we import a module. starting with the Once a program has started. def show_choc(): This path is much like the Bash shell’s $PATH food = [“snickers”. Using modules can about: variable scope. and then finally it will look at all the built-in names. Read these and you’re sure to gain in terms of the easiest way to solve there are two very useful resources from some deeper insight into the language. it is a bad idea to put Before you head off and start merrily writing your own variables in the global scope. and then the module’s global scope. which particular variables can be accessed. it refers to a list of chocolate bars. there is one more thing that you need to know subtle errors elsewhere in your program. importing the sys module. This makes global variables single Python module might contain the following code: somewhat less around since the early 1990s. it’s actually been format your code to make sure it’s http://python. however. It can cause confusion and modules. it can even modify the path immediately enclosing function. As with any readable for co-workers and anyone else projects/pycon/2007/idiomatic/ programming language that’s been working on the code with you (including handout. “kitkat”. As we saw above. and the best ways to which you can start learning: a modern language. and then inspecting the path When looking up a variable. and serves print food exactly the same function. different scopes: the global scope of the current module. in defined in your default installation. and the local scope of the You can inspect the path in your Python environment by function.path will do the trick). single-file programs. It varies. and then any functions itself and add other locations to it. “dairy milk”] environment variable – it uses the same syntax. although you should still be food = [“apples”. Q Python style While many people think of Python as common problems. “pears”] careful when using them. “oranges”. you can bring order to your projects and make future maintenance easier. For instance.html around for any length of time. but as global scope. people who your future self).net By splitting your code up in to smaller chunks. while inside the function. WorldMags. print food the locations stored in the path consist of the following If you run that. you’ll see that outside the function the two locations: variable food refers to a list of fruit. scope refers to the part of a program from contents are all stored as attributes of the module’s name. Initially. each placed in its own file and directory. help with this problem. which food refers to a list of fruit. innermost variable and works its way out. The directory containing the script doing the importing. enclosing that. www.

You still perhaps using a web form and CGI). file) the write method: … for feed in feeds: with open(“ . Support for it is The second is that you have to close the file after you have included in the standard library. matter) into a string first of all – for dictionaries in . or wherever you of file objects.xml”..dump(feeds. Just use pickle. Fortunately. though. or convert them to a character string and back again..load(file) 76 | Coding Made Simple WorldMags.”] with open(“lxf-test. and to bring a modicum of functional style into and append (a). automatically closes it for us. Python provides two tools Writing to files to make this easier for us. It’s no surprise. otherwise we would smartphones come with at least 8GB of storage. to use the function: with keyword: file = open(“lxf. but you no longer store that list of feeds on disk so you can re-use it later when have to worry about figuring out an appropriate string you’re checking for new updates. you thought had been committed to disk. application stores data in one way or another. there are two things With this in mind. while even add a new line to the end of each string. str(42) => “42”. the feeds representation for your data: are just stored in a Python list: import pickle feeds = [“http://newsrss. use the open() file. When using files in your Python code.close() to our program. as well. of choice – Python. saved figure this one out. we’ve shown you that this file object is in fact an iterator. edition/front_page/rss. and you don’t even have to finished using it – if you don’t do this. Working with files would be much easier if you didn’t have to one line at a time. case. this could get messy. WorldMags. It’s better. “a”) as file: To get the feeds into the file is a simple process. cached data to speed up future use. then. In our example. however. load each line in turn into a list. because you can just use the built-in The most obvious form of persistent storage that you can str() function – for example. You’ve already got some way to ask accepts many different kinds of Python objects. If you are unsure what the second line does. S torage is cheap: you can buy a 500GB external hard Easy! Notice how we used the format string function to drive for less than £40 these days.rstrip(“\n”) for line in f] application stores data The first argument to open This simple piece of Python code handles opening the file object and. You can do this manually with the close method wherever you ran the Python script from. This is easy. Suppose you’re writing your own RSS application to deal with The first of these tools is the pickle module.txt”. to-do lists or photos. and can then users to enter in a list of feeds (perhaps using raw_input(). that almost every modern Using the file as an iterator. Before reviewing that information. but now you want to have to do the file opening and closing. been flushed. worry about converting your list (or dictionary. Pickle your favourite feeds. The first is that you need to demonstrate how to deal with persistent data in our language convert whatever you want to write to the file to a string first. At the moment. your work. whether that’s stripping off the trailing new line character. We’ll leave you to configuration data. but that had not yet To open a file in the current working directory (that is.format(feed)) feeds = pickle. take advantage of in Python is file storage.txt”. try looking up Python list specifies which mode the file should be opened in – in this comprehensions – they’re a great way to write efficient. pair of jeans. and end up with everything on one line – which would have made many are easily expandable up to 64GB for only the price of a it harder to use later. this programming tutorial is going to that you need to keep in mind. “w”) feeds = [line. for that let’s look at how to write data to a file. “r”) as file: Embrace storage and persistence Deal with persistent data and store your files in Python to make your programs more permanent and less transient. with open(“ Re-using the contents of this file would be just as simple. you risk losing data that import any modules to take advantage of it. The list goes on and on.txt”.write(“{0}\n”. In previous tutorials. games. “ this would translate to adding were when you launched the interactive shell). it’s write. but other valid options include read-only (r) concise code. “a”) as file: “Almost every modern test. while the second finished. which means you can use the in keyword Serialising to loop through each line in the file and deal with its contents.txt”. when the block inside the with statement is in one way or another” is the filename.

If you like the concept of pickling (more generically. you use it in exactly the same way as pickle – in The shelve module has its own operations for opening and the above example. a shelf is a persistent dictionary – that is to stored in the shelf. you assign a underneath. a persistent way to store key-value”: { “last-read”: “bar”. object that pickle can You might do this with a transfer your feed list across the network.0 applications. so you can’t use the standard open function. The problem with this is that it will only work in Python – “tuxradar. a good next stopping point is the ZODB object database. however. too: JSON. of about the shelve module: In Python. details for each in a single file by using the shelve module. serialised code! To save some data to the shelf. too. Let’s take a look at how you That’s about all we have space for this tutorial. Rather than another Python standard module. you wanted data: relational databases (for example. but makes access to the stored objects more value to that stored in the dictionary at a particular key: feeds intuitive and convenient: the shelve module. and it has other applications outside to keep track of how many unread items each feed had. then re-assign that temporary value back to about shelves. and of persisting data in files. }} the pickle data format. It’s great. that uses pickle assigning a key in the shelf dictionary to a value.zodb. do with pickle. shelf. If you want to modify the data that was Essentially. but keep can use If you’re interested in persistent data in Python. some code bases have many different objects that As with“lxf-test”) identical to objects found in the JavaScript programming shelf[“feeds”] = feeds language. Of Q WorldMags. because we’ll discuss one final option for persistent imagine that as well as the list of feeds to check. you must first use a standard Python assignment operation to set the value of a Shelves particular key to the object you want to save. = shelf[“feeds”].net Coding Made Simple | 77 . There’s Accessing data inside the shelf is just as easy. there’s another option that You could then store the list of feeds and the tracking does have support in other languages. that is to say. “num-unread”: 10. is that the value can be any Python the shelf before closing it again. and keeping with. if you wanted to which item was the last to be read. Thinking back to our RSS reader application. modify it in the temporary value you say. for example: have to make it into a character string. }. track of many different pickled files can get tricky. reading. and is a way of converting objects into import shelve human-readable string representations. This is much easier. MySQL). other programming languages don’t support “num-unread”: 5.close() largely because it has become so popular with fancy web There are a few important things that you should be aware 2. which you could tracker = { “bbc. you’ll be writing interoperable. It’s much easier and more natural in Python than a relational database engine (www. you must close the shelf object once finished you want to store persistently between runs. replace pickle with json throughout. and closing files. because it’s human readable. The great thing assigned it to. and also shelf[“tracker”] = tracker because it’s widely supported in many different languages. serialising). you would first”: { “last-read”: “foo”. You may have heard of JSON – it stands for JavaScript like so: Object Notation. otherwise your changes may not be stored. which look almost shelf = shelve. WorldMags. For example. however. too.

the album title and year published). Artist_id 1 As relational databases are by far the most common tool for asking complex questions about data today. a unique name for an artist. but very wasteful. With the basics all the information about the artist. other information. useful form. Here. we’ve simply Album time 65:58 65:58 specified the unique ID for a row in another table. even. probably Year 1972 1972 called Artist. you’ll be able to start integrating relational and the year they split. or as you try to express more complicated ideas and Running time 65:58 relationships. its running time. or a unique title for an album).net Data organisation and queries Let’s use SQL and a relational database to add some structure to our extensive 70s rock collection. and each album can be described by lots of ‘relational’ part of a relational database comes in. Relational databases solve these problems by letting us are used to ask complex along. The techniques we looked at were flat-file based. We can then add an extra column to each table that Artist Free Free references the primary key in another table. When we want to present this album to a user. harder to “Relational databases your code. For every track on the same tutorial we’re going to introduce you to the basics of relational album. of its drop-in In our example. Relationships All that duplication is gone. As well as being wasteful with storage databases into space. To follow interpret and more dangerous to modify later. as performance becomes more important. Each CD is produced it and the album it appeared on? That’s where the a single album. or Structured Query Language). A logical place to start might be information about a single track. These unique columns form what is known as a primary key. too. We would then to the MySQL console: only need to have a single entry for the artist Free (storing the mysql -uroot name and the year the band split). what happens when you want to report all the in our music . or homogeneous table – like the one below – which is all well a combination of columns (for example. right? I n the last tutorial. we might split information about the replacements installed. and as useful as they are. or attributes. such as the databases and the language used to work with them (which is album name. in this coding and good. Where a natural primary key (a natural set Duplicated data of unique columns) doesn’t exist within a table. Year 1972 such as an object database or. but now all the data has been Let’s start by thinking about the information we want to store separated. including the artist who Every row within a database table must in some way be created the album and the tracks that are on it. unique. Track Little Bit of Love Travellin’ Man consider the table above. track in the database (storing everything else) in each of their respective tables. either based on a single unique column (for example. use the -p switch to give that as album Free At Last (storing its name. Throughout. the year it was well as the username. make sure you have got split the data and store it in a more efficient. As your applications grow Album name Free At Last more ambitious. and a single entry for each database to track our music collection. For example. You do have one. They let us identify separate entities within the database that questions about data” MySQL or one would benefit from being stored in independent tables. a relational database. in Band split 1973 1973 conjunction with information about the artist who published 78 | Coding Made Simple WorldMags. Relational database they’re not exactly industrial scale. including the artist who thinking about it in terms of the CDs that we own. WorldMags. such as their name mastered. we’ll be working on a small published and the running time). you can easily add an artificial one in the form of an automatically Album Free At Last Free At Last incrementing integer ID. a single entry for the If you’ve set a password. you’ll need to look towards other technologies. artist and track into separate tables. and called SQL. this also makes the data slower to search. rather than giving all the Track time 2:34 3:23 information about the artist in the same table. the year it was published. and can also find a way to get access album. we looked at how to make data persistent in your Python programs. we have to duplicate all the information. We could represent all this data in one large.

To create these tables within the database. then retrieve the information about the artist. and that it would have taken just that column. You’ll also want to investigate the different types of whether it is part of the primary key. the type of object that we’re operating on and then you must always specify a data type for your columns. Now you’ve seen the basics. you use create database: create database lxfmusic. otherwise we won’t be able to link the tables together Track_id int auto_increment primary key. you’ll want we give the column a name. so many separated by commas. Pretty self-explanatory really! If we’d only wanted to get the ID The most obvious things to note here are that we have field. separated by semi-colons. we can show you how to use SQL to create and use your own. The database is the top-level storage container for bits of related information. eventualities are covered. look out for an appropriate incremented for every row in the database. Splitting information into manageable. such as one-to-one. First. select * from Album where name = “Free At Last”. That said. Q WorldMags. notice how similar it is to the The big thing to note is that we specified the running time create database statement. we then specify the columns which we’re name varchar(100) inserting into. education stop there. You can find out more about the create table Much as you work within a current working directory on the statement in the MySQL documentation at http://dev. many-to-one The auto_increment keyword means you don’t have to and many-to-many. This command says we want to select all columns from Album_id int the Album table whose name field is equal to Free At Last. Album_id) values the correct places. then we describe the type of data to investigate foreign keys and joins.html. the first thing we need to do is create a database. such as the python-mysql module for Python. as long as you put the right punctuation in insert into Track (title. We specify the action we want in seconds and stored it as an integer. SQL That. primary key.5/en/create-table. 1). and the properties of that object. thus forming a module. ). we’re acting. we specify the action and the object on which Album_id int auto_increment primary key. as MySQL will ensure that this is an integer that gets programming language of choice. running_time. With most databases. in a nutshell. and describing the relationships between those chunks. and you can issue your commands in whatever case you like. As for the command itself. WorldMags. To do this. and now that you know what a table and a relationship is. OpenSUSE and even Slackware. To do this. many commands you issue are mysql. most relational databases make use of SQL. but don’t let your MySQL separated entry describes one column in the database. Inserting data into the newly created tables isn’t any trickier: Now to create some tables: insert into Album (name) values (“Free at Last”). SQL doesn’t Since that returned a 1 for us (it being the first entry in the care about white Coding Made Simple | 79 . and you will with the create table statement. That’s all we have space for here. With the database created. we must discover what the ID of the album Free At create table Track ( Last is. to insert and query data. (‘Little Bit of Love’. if you want to integrate MySQL with your data. of extra properties that come inside the parentheses and are MySQL does have a wide range of data types. however. Linux console. then we techniques that will enable you to be far more expressive with specify any additional properties of that column. in a different manner than in your application. 154. relationship. combining it for presentation. You can switch databases with the use command: Inserts and queries use lxfmusic. one-to-many. is what relational databases are all about. Before we can insert an entry into the Track table. two more advanced stored in it (this is necessary in most databases). we can get the information first from this Album table. reusable chunks of data. we use the select statement: title varchar(100). we’ve used lower-case letters: SQL is not case-sensitive. worry about specifying the value of Track_id when inserting Finally. from the Artist table. to manage the relationships. to we have split each command over multiple it. relative to the currently selected database. we’ve also got a whole load need to write some code to convert it for display. With the create database sometimes this means that you need to represent your data statement. whose ID is 1. such as your SQL. so we need to create it before we can start storing or querying anything else. so you can split your code up database). the only property was the name of the database. we can insert into the Track table as follows: however you like. ). you now need to switch to it. and is quickly finding favour among distros including Mageia. and finally the values of the data to be put in. create table Album ( Once again. and each comma. very easily. running_time int. in MySQL. These are known as column definitions. After logging into the MySQL console. we could have replaced the asterisk with Album_id and issued two commands. Notice the semi-colon at the end of the command – all SQL statements must end with a semi-colon. Also notice that MariaDB is a drop-in replacement for the MySQL database. .

........................................................ Starting Scratch 84 ............................................................................ 114 WorldMags.............................................................................. Python Coding Made Simple | 81 Raspberry Pi Discover how you can develop on the low-cost......................... 108 Image walls in Minecraft ......................................................................................... Advanced sorting .................. 110 2048 in Minecraft ........................ micro-PC system Getting started 82 .................. Coding with IDLE 92 ....................0 on the Pi 98 .............................................................. Further Scratch 88 ................. Python on the Pi 94 .............. 102 Hacking Minecraft ...........................

Bear in mind that the Pi (particularly non. The Software bottleneck is mostly application. there’s a special edition of Minecraft. T he Pi-tailored Raspbian desktop environment free to peruse that to learn about commands such as ls . 82 | Coding Made Simple WorldMags. Raspbian may appear Terminal velocity somewhat spartan. Windows 10. It’s possible to do this from – you may want to make a cup of tea. Compared to. which applies equally well here. tutorial (see page 16). That updates Raspbian’s local list of all available packages. handles all of the consultations with Raspbian mirrors and but there’s also Wolfram Mathematica (for doing hard sums). which install. so lightweight is the order of the day. Open LXTerminal from and image viewers. and thanks to graphical hardware are available. you’ll get important security anything from the command line. it can even play HTML5 YouTube videos. updates and the latest features or fixes for all your software. so feel The syntax is clean and concise. it’s possible to do pretty much packages pretty regularly. It system is checked against this. You should update your the command line too. the list of current packages installed on the desktop computer. Most importantly. these are offered for upgrade: acceleration. such as this one featuring a tiny arcade cabinet. as well as PDF dependencies with a minimum of fuss. say. which you can trust. there are no awkward The new Epiphany browser works well. It’s a good idea to keep the software on your Pi an even friendlier place to learn. Sonic command: Pi (the live coding synth). too – there’s Scratch (the visual coding language). making it and mkdir . This downloads packages from Raspbian’s due to the speed at which data can be written to the SD card repositories. In Pi 2 models) is considerably less powerful than your average the next . not to mention the Python $ sudo apt-get update programming language. Software is your average desktop computer. either the menu or the launch bar. WorldMags. cd received a thorough overhaul in late 2015. There’s a very brief introduction to the terminal in the Mint Python is a particularly good first programming Welcome to Pi Reveal the Raspbian desktop and partake of the pleasures of Python programming on the Raspberry Pi. play or work. The up to date. the managed from but remains no less functional. of packages to upgrade. In fact. so let’s see how that works from the terminal. it $ sudo apt-get can play high- definition video “The Pi is far less powerful than upgrade If there’s lots without batting an eyelid. and where newer packages remains no less functional. and enter the following wise. We’re amply catered for programming.” process may take the Add/Remove some time. Raspbian team has squeezed a great deal into the 3.5GB We’re going to use the apt-get package manager. does a remarkable job of (un)installing packages and their LibreOffice and the Epiphany web browser.

you’ll run into something that print(‘Hello World’) requires Python 2. Python 3 (see page 94 and 120) has our Python programs. than others. to date. Fortune has it that by turning to the scenarios but you can also play with the Finally. Open up a terminal. there’s a for which the Raspberry Pi is well suited. and then navigate to the version of Python provided by Raspbian – tutorial (see page 16). if you haven’t already done so. cameras or LEDs. so finally the shift to 3 is Now type the following into your chosen editor gaining traction. but people have been slow to adopt. but it’s a fully working do here. Some wireless adapters work better with the Pi practice. Sooner or later. and turn your cat as its mascot. but for this tutorial we’re going to stick with the new editor. Scratch (see page 84) is a great way very next Coding Made Simple | 83 . The Raspbian desktop WorldMags. You’ll also find links to help resources and. To start you’ll appreciate how efficient it is. you have a choice: you can proceed as in the Mint A tale of two Pythons tutorial and use the nano text editor. or even been shared on its website at https://scratch. Keeping on top of your filing is A Good been around since 2008. by hitting Ctrl+D. Launch bar Frequently used applications can be added here – just right- click it and select Application Launch Bar Settings. Assuming you’re using the graphical things.5 million projects have University of Kent and Oracle). Many of the larger projects that used to only work on the old $ mkdir ~/python version have been ported to the new. use Ctrl+X to save and exit. Q Other programming tools We’ve only covered Python in this tutorial Then there’s also Node-RED. So we’ll now leave the interpreter about anything. For example. you will find an entire tutorial underlying Java source (if you’re feeling brave). Plus it has an orange full-blown Java IDE called Greenfoot (which to add sensors. in the Preferences menu. start the Python 3 interpreter by entering: Now we can run this and see what we have created: $ python3 $ cd ~/python Once again.4. It’s easy represent events and logic. we’ll create a directory for storing last few years.7. you could do the following: programming adventures. so it’s worth doing some research before you buy. too. Before you reflects a duality that has formed in Pythonic circles over the make that choice. and then you might have to unlearn some and then save the file. and save it as helloworld. with connections. Thing. semicolons to terminate statements. It can watch and. to get kids (or grown-up kids) into coding. some 12. It opens at your home folder and is also capable of Terminal Network browsing Windows and other The command line gives direct access to the From here you can configure your wired and wireless network network shares. recently created Python folder. it makes more sense to save huge number of modules that enable you to achieve just your programs in text files. The black screen icon in the centre opens the terminal. At this point. operating system. the basics of open-source design using visual water your plants. monitor the weather. some tools for adjusting system settings. if you wanted to find out how many program and something you can build around in further seconds there are in a year. File manager The PCManFM file manager is lightweight but thoroughly capable. created by dragging and connecting blocks that available in Raspbian. File > Save As. Scratch was developed at MIT has been developed in partnership with the Pi into a bona fide smart device. Menu Here you’ll find all the great programs mentioned earlier – and more. for designing visual language. This teaches your letterbox. It’s a devoted to the language. which means that programs are but there are other programming languages applications based around the Internet of Things. mit. if you have a look at the introductory Mint $ python3 helloworld. lots of shortcuts for >>> 60 * 60 * 24 * 365 things that are cumbersome in other languages and there’s a As mentioned elsewhere. This graphical one located in the Accessories menu. you’ll learn about a few things you can It’s not going to win any awards. and make our first Pi Python program. and If you’re using nano. It can be daunting but. though. WorldMags. or you can use the Raspbian comes with two versions of Python installed.

It’s a great beginner’s language. although Scratch can be downloaded from https://scratch. Without further ado. or images. Each program is made up of a number of sprites (pictures) that contain a number of scripts. The main window is split up into sections. Costumes tab to create new ones or manage existing ones. and the little learning computer is our focus in this series of articles. or if you’re new to graphical programming. WorldMags. It’s best to use Raspbian rather than one of the other distros for the Pi for this. Broadly speaking. It’s these scripts that control what happens when the program is running. because not many of the others support Scratch. Each sprite can have a number of costumes. Click on the Click on ‘New Sprite From File’. let’s get started. so there’s no need to install anything – just click on the icon to get started. You’ll find Scratch on the desktop in core Raspberry Pi operating system Raspbian. If you’ve never programmed whether you’re using Windows. In the top-left corner. you’ll see eight words: . Operations and Variables. or ‘Costumes > Import’ to see them. These tutorials will be equally applicable whatever your platform. while you make your programs in the middle. Pen. Good luck! Scratch comes with a range of images that you can use for sprites. Looks. Sensing. we’ll ease you gently Starting Scratch Discover how to build a cat and mouse game using this straightforward beginner’s programming language. 84 | Coding Made Simple WorldMags. the bits you can use to make your programs are on the left. It’s especially good for creating graphical programs such as games. because it introduces many of the concepts of programming while at the same time being easy to use. Control. ou can use a wide range of programming languages Y with the Raspberry Pi. Sound. Each of these is a category that contains pieces that you can drag and drop into the scripts area to build programs. mit. Mac or Linux. and the programs run on the right. and hopefully have a little fun along the way.

you’re going to want to get your different types of data. could also put text in them. and for a script programming languages. Then reduce the sprite size by clicking on When r Key Pressed. It might be worry about that in Scratch. the ‘Shrink sprite’ icon (circled) and then the mouse. Go To X:100. Y:100 (from ‘Motion’. Note that in some so they have to be created first. These can be used to trigger this using variables. If you drop it the size of our thumbnail. or anything. don’t forget to change 0s as score. You can do Once you have created a Variables and messages Sooner or later. or you can output them. but you don’t need to to communicate between them. you can then use messages. then you can use them to one script broadcasts a message. Set Score To 0 and Set Over to 0 (both from ‘Variables’). although we 11). Click on ‘Make A Variable’ and enter the variable name ‘Looks’). We set it to about Then drag Move 10 Steps off the bottom of the script. it will be deleted. Receive … Like variables. Repeat the process to create a variable called over. We’ll use this to start a new game (r is for reset). WorldMags. Step by step 1 Create the mouse 2 Set keys Change the image from a cat to a mouse by going to ‘Costumes > Click on ‘Scripts’. you have to create Messages to trigger it has to be linked to the same message different types of variables if you want to store If you create a number of scripts. back in the left side. you have to set them scripts in the same way as keypresses can. messages have names. to 100s). In step 3. Firstly. add the lines show (from what they are). Sometimes you program to remember something. you may need as the broadcast. When computer’s memory that your program can to be a particular value. a piece of text. and change When Right Arrow Key Pressed to Import > Animals > Mouse 1’. WorldMags. it will then place pieces of data in. can do this with Coding Made Simple | 85 . we create a pair evaluate conditions (which we’ll do in steps 6 and trigger all the scripts that start with When I of these to store some numbers in. but it is often better to a number. 3 Create and name variable 4 Reset the score Click on ‘Variables’ in the top-left (see boxout above for more details on Under the script When r Key Presses. These are little pieces of the use it in a few ways.

5 Add broadcast 6 Create a loop
Add the block Broadcast … to the bottom of the When r Key Pressed We can create loops that cycle through the same code many times.
script. Once it’s there, click on the drop-down menu and select ‘New..’. Continue the script with Repeat Until … (from ‘Control’), and then
and give the message the name start. We’ll use this to let the other drag and drop … = … (from ‘Operators’), then drag Over (from
sprite know that the game has started. ‘Variables’) into the left-hand side of the = and enter 1 on the right.

7 Add to your loop 8 Hide the mouse
Inside the Repeat Until Over = 1 block, add Change score By 1 (from Once the game has finished (and the cat has got the mouse), the
‘Variables’), Move 7 Steps (from ‘Motion’) and If On Edge, Bounce Repeat Until loop will end and the program will continue underneath
(also from ‘Motion’). These three pieces of code will be constantly it. Drag Hide (from ‘Looks’) under the loop, so the mouse disappears
repeated until the variable over gets set to 1. when this happens.

9 Resize your cat 10 Move the cat
Select ‘Choose New Sprite From File > Cat 4’, and shrink the sprite In the scripts for the new sprite, start a new script with When I Receive
down to an appropriate size, as we did with the mouse. Each sprite has start (from ‘Control’), and Go To X:-100 Y:-100. This will move the cat
its own set of scripts. You can swap between them by clicking on the over to the opposite corner of the screen from the mouse. (0,0) is the
appropriate icon in the bottom-right. middle.

86 | Coding Made Simple

11 Give the cat a loop 12 Set the difficulty
As with the mouse, the cat also needs a loop to keep things going. Add Inside the Repeat Until block, add Point Towards Sprite 1 (from
Repeat Until (from ‘Control’), and then in the blank space add ‘Motion’) and Move 4 Steps (also from ‘Motion’). The amount the cat
Touching Sprite 1 (from ‘Sensing’). This will keep running until the cat and mouse move in each loop affects the difficulty of the game. We
(sprite 2) catches the mouse (sprite 1). found 4 and 7, respectively, to work well.

13 Finish the loop 14 Tell the player the game is over
The loop will finish when the cat has caught the mouse – the game is We now want to let the player know that the game is over. We will
over, so we need to stop the script on Sprite 1. We do this by adding do this in two ways: with audio, and on screen. Add Play Drum 1
Set over To 1 (from ‘Variables’) underneath the Repeat Until block. for 1 Beats (from ‘Sound’), then Say Mmmm Tasty For 1 Secs
This will cause Sprite 1’s main loop to finish. (from ‘Looks’).

15 Display a score 16 Play your game!
Finally, we can let the player know their score. We increased the Press [r] and play! You can use the up and down arrows to move the
variable score by one every loop, so this will have continued to go up. mouse around. You can make it easier or more difficult by changing
Add Say You Scored … For 1 Secs, then drag another Say … for 1 the size of the sprites and the amount they move each loop. Good luck
Secs block and then drag score (from ‘Variables’) into the blank field. and happy gaming!Q Coding Made Simple | 87
Further Scratch
We’ve dived in, but let’s now look at the fundamentals of Scratch to
understand how our programs work and set up a straightforward quiz.

ow did you learn to program? Typically, we think of a
person sitting in front of a glowing screen, fingers Fig 1.0 The logic for
slowly typing in magic words that, initially, mean our logo sprite.
nothing to the typist. And in the early days of coding, that was
the typical scene, with enthusiasts learning by rote, typing in
reams of code printed in magazines.
In this modern era, when children are now encouraged to
learn coding concepts as part of their primary school
education, we see new tools being used to introduce coding
to a younger generation, and the most popular tool is the
subject of this very tutorial.
Scratch, created by MIT, is a visual programming Fig 1.2 This is the code
environment that promotes the use of coloured blocks over that clears effects.
chunks of code. Each set of blocks provides different
functionality and introduces the concepts of coding in a to version 2.
gentle and fun way. Children as young as six are able to use As mentioned, Scratch uses a block-based system to
Scratch, and it’s now being heavily used in the UK as part of teach users how different functions work in a program. This
the curriculum for Key Stages 1 to 3 (6 to 14 years old), and can be broken down into the following groups and colours:
as part of the Code Club scheme of work. Motion (dark blue) This enables you to move and control
Scratch uses a For the purpose of this tutorial, we are using the current sprites in your game.
three-column UI. stable version of Scratch, which at the time of writing is 1.4. Control (orange) These blocks contain the logic to control
From left to right: Version 2 of Scratch is available as a beta and reports suggest your program (loops and statements) and the events needed
Block Palette,
that it’s very stable to use, but there’s a number of differences to trigger actions, such as pressing a key. In Scratch 2.0, the
Script Area and
between the locations of blocks when comparing version 1.4 events stored in Control have their own group, which is called,
The Stage.
naturally enough, Events.
Looks (purple) These blocks can alter the colour, size or
costume of a sprite, and introduce interactive elements, such
as speech bubbles.
Sensing (light blue) For sensing handles, the general
input needed for your program, for example, keystrokes,
sprite collision detection and the position of a sprite on
the screen.
Sound (light purple) Adds both music and sound effects to
your program.
Operators (green) This enables you to use mathematical
logic in your program, such as Booleans, conditionals and
random numbers.
Pen (dark green) This is for drawing on the screen in much
the same way that logo or turtle enable you to do so.
Variables (dark orange) Creates and manipulates
containers that can store data in your program.
By breaking the language down into colour-coded blocks
Scratch enables anyone to quickly identify the block they

Scratch online
Scratch is available across many platforms. It with the same interface and blocks of code, but version of Scratch from the website. This very
comes pre-loaded on every Raspberry Pi running with a few subtle differences. This is the latest latest version is still in beta but reports show that
Raspbian and is available for download from version of Scratch and you can save all of your it is very stable and ready for use. Scratch 2.0 But did you know that work in the cloud ready to be used on any PC you uses Adobe Air and is available across all
there is an online version that provides all of the come across. If you wish to use the code built platforms including Linux. Adobe dropped its
functionality present in the desktop version, but online on a PC that does not have an internet support for Air on Linux a few years ago but you
requires no installation or download? Head over connection, you can download your project and can still download the packages necessary for
to the MIT website (above) and you’ll be greeted run it offline. You can also download the latest Scratch 2.0 to work.

88 | Coding Made Simple

An event is typically clicking on the green script associated to the stage sends a broadcast called is a quick way to flag to start the game but it can be as complex as listening for player_name. What this does is triggers belong to your particular program. which is handled via the code For this tutorial. using the Answer variable. The purpose of the We’ve broken Matt’s main loop into three parts. so let’s look at what they each do. two quiz masters. the start of the game. Once the user enters their name. Fig 1. there’s a section of code associated with Quick answer the question correctly to progress to the next round. So we have a number of actions to perform once we receive these broadcasts from Neil and the stage. can drag our blocks of code Let’s move on to Neil. the code associated with else. Double in size. it’s game over. Children typically work answered a question correctly. world. we move on is Sprite8. Neil will say your code. Neil’s code is waiting to receive this broadcast duplicate or delete a trigger from another sprite. which is basically a way to chain trigger events between sprites in the program (you can find ‘broadcast’ under ‘Control’). Matt has five sections of code that react to something called a ‘broadcast’.net need. which is repeat until answer = ubuntu. Fig 1. This large loop is triggered once we background that we want to use in our program. (see left) shows the code that Fig 1. We wanted this logo to appear right at given. Neil’s code inside support Neil sends a broadcast to Matt once the player has the main loop.1 The code used Script area In the second clears any special effects used for Matt to receive column is an area where you on his sprite. We’ve given our four game sprites names: Neil is Sprite6. broadcasts. statement which uses a condition to perform a certain Hide.5. It then stores that tip you receive three wrong answers in the game.0. or if it is false it will run Wait for 2 seconds. receive the name of the player. game_over Neil sends Matt Fig 1. This is because he’s the your programming and can be used to interact with the game main part of our game. sequence of code if a condition is true. In the case of the answer being Show. Once the code is triggered. Clicking on a sprite will Neil’s sprite to reset any special change the focus to that sprite. via the colour-coding system at insult Neil sends a broadcast to first. which is for each of these broadcasts divided into three columns.5 The second loop of has entered their name. WorldMags. Now let’s look at the logic for Matt’s sprite. we need to move blocks of ‘code’ The second part is the loop from the block palette to the script area for each sprite or that controls our game. This shows the sprites and assets that event. sprite has a lot more code than The stage The third and final column shows the results of Matt. and you must start of the game. Loop 10 times and each time reduce size by 15% You can see this as Scratch presents it visually in Fig 1. The environment the game. WorldMags. Matt is triggered to run a certain The first column is: sequence of code. there’s the Green Flag handy Sprites pane. we are going to make a quiz game. hello to the player by their Coding Made Simple | 89 . question in a loop that will repeat until the correct answer is starting with the logo. Matt also has Block palette This is where a script that’s run in the event of our blocks of code are stored clicking on the green flag. the a block of code an event triggers it. below). but not be visible straight away. natural process of playing they Score Neil sends a broadcast to understand the link between Matt triggering Matt to tell the each of the blocks and how player their score.3. At the bottom of this column you will also find the very First. At the game is to score more than three points. This second loop is an if When Green Flag clicked.4 Part 1 of the main game code. enabling you to write code for effects that may be in use and that sprite only. which is stored in the Sensing Right-clicking on Each of our sprites has their own scripts assigned to run once category of blocks. and then through the Matt to taunt the player.2 and sorted by function. then stores 0 in the variable called guesses (see Fig 1. so our We then ask the question and run another loop inside of logic was as follows: the main loop (see Fig 1. player_name The stage sends a broadcast once the player Fig 1. To write code with Scratch. We wrap the associated with them.1. as a variable called Answer.3 This resets Neil’s sprite and the a broadcast to trigger the end of guesses variable. our logo is Sprite5 and the Game Over image Once we have the formalities out of the way. using associated with the stage. which we will come to later. Matt is Sprite7. called Matt and Neil. If the stage that asks for the player’s name. left). Building our game above-right). as a trigger event. they work together. Scratch uses a clear and As we can see (Fig 1. structured layout. This from the block palette to add code to our program. Each of these sprites has their own scripts to the main loop that controls the first question.

Once created. in parallel to each other. who will say something nice. play a gong sound effect. If they Loops A way to repeat a sequence. we can easily Programming concepts Using Scratch is great fun but did you realise that Parallelism This is the principle of running rules that we all learn in school. first block is a broadcast score to Matt – this will trigger Matt to tell us the score. times to change the size and rotation of the sprite. The first section of the third part is exactly the same as the main loop from the previous two parts.3)). just like you’d see in the classic 8-bit games of the 1980s. associated with that broadcast.6 The last The Green Flag event is the code that controls the over broadcast is sent. We completed in a certain order. the player would have to try in our game. For our game we have two sections of code on the stage. then Neil will say ‘Incorrect’. And once because each sprite has its own code that runs data if required. . To create a variable. The first part resets two variables called guesses and score. doubled your code in just one click. The second section of code is an infinite loop that will play the loop DrumMachine continuously and set its volume to 50%. above). So let’s move Fig 1. below). who will then run thorough the end of game code The Game Over sprite has two scripts associated with it. In there you will find the ‘Make a variable button’. Click on it and you will see Fig 1. we need to use the ‘Variables’ button from the block palette. the player would be awarded a for statement (for x in range(0. then alter the variable score by 1 point and. We then pause for three seconds to allow we broadcast game_over to Matt. Hey presto – you have be connected. The stage As well as being the home of our sprites. learnt they can be applied to any coding project. which enables us language you use. To have a white ‘halo’ duplicate code in correct. Our have its own scripts.7 The Stage contains the sprites but it can also down to the last four blocks of code (see Fig 1. triggers the Matt to finish speaking. which is then broadcast to Matt and Neil. the game here is clicking on the green flag to start have used conditionals in our game to compare steps needed to solve a maze. the answer given to the expected answer.6. 90 | Coding Made Simple WorldMags. we use stop all to stop The first is simply that when the green flag is clicked. We’ve used that a lot in our Scratch game to perform calculations in our code and iterate coding provide a firm foundation. and the most visible event in our Scratch against the input that is given by the player. play a sound to reward the player. tip Part two of the code is exactly the same as the main loop Blocks that can be of part one and the reason why is because we duplicated the linked together will code and changed the question and expected answer. we need to create it. giving us a rotating zooming effect. In our game we used two variables – score and guesses – and we want them both to be available for all sprites. Both sections of code are triggered by the click on Green Flag event. We have the score to show the player’s progress through point. It triggers the sprite to reveal itself and part of the main code associated number of guesses that the player has. broadcast support to Matt. in turn. They can Data We use a variable to store the value of our both matched. As we mentioned earlier on. logic to say that when the number of guesses is equal to 3. you can simply right-click on the indicating they can blocks of code and select ‘Duplicate’. We can apply you are also learning to code? No matter what more than one sequence of code at the same operators to text and numbers. Neil will say that the answer is correct. the game. which in Boolean logic would be be run for ever (while true) or controlled using a score and we can later retrieve and manipulate classed as True. so that Matt and Neil can use them both. Then we send another broadcast to end of game script. The second script is triggered when the game_ Fig 1. Conditionals These form the basis of our logic The main concepts are: Events This is a trigger that starts a sequence and provide a method for us to compare data Sequences A series of tasks required to be of code. the underlying concepts of time. the stage can also contain its own scripts (see Fig 1. to hide any scripts in the game.7. Operators These are the basic mathematical once again. variables are a great way to store data. Lastly. We use conditional set its size to 100%. the sprite. But before we can use one. Matt. and then increment the guesses variable by 1 and send a Quick broadcast to Matt who will taunt the player. We then use a loop that will repeat 10 with Neil. and starts the main code loop assigned to Neil. defined as False. which. which would be used many loops to control the player’s progress the game. WorldMags. We then ask the player to provide their name. For example.9 (see right). If the player provides an incorrect answer. If they did not match.

This is when you write down the logic of how your program will drop these variables into our code. Matt will also say something nice. A box will appear for you to type your answer. we iterate a by 1. In both Scratch and Python. and that we reach a = 9 and then it will stop as the next value.8 below for the example that we made for our game. Matt says hello and Neil says hello and your name. If you guess correctly. So now let’s play our game. Every time we go round the loop. Else if your answer is wrong. you will be taunted by Matt and the number of guesses will increase by 1. We then create a a=a+1 conditional loop that only loops while a is less than 10. see Fig 1. there are two variables in our you’ve enjoyed learning Scratch.Q WorldMags. is Scratch can be used to help understand the logic that powers not less than 10. If the number of guesses made reaches 3 at any point in the game.9 Hit the forever if a < 10 a=0 ‘Make a Variable’ say a for 2 secs while a < 10: button to create a variable. though this is just scratching the surface of what you can do with it. You will then have another chance to answer the question. we ask Scratch to print the value of a for 2 seconds. If answer correct. from there we create a loop that will continue to iterate round until it reaches 9 (which is less than 10). then Neil will say so. Testing our game We’ve done it! We’ve made a game. and this will happen twice as there are three questions. our code will look like this: [When Green Flag is clicked] Set variable a to 0 Fig 1. Pseudo code When trying to understand the logic of our game. we like to write pseudo code. We hope Fig 1. but how do we express this in a programming language? First. you will move on to the next question. let’s do this with Scratch followed by Python. If you answer all the questions correctly. we create a variable called a and set its value to be 0. They both welcome you to the quiz. In Scratch. You will be asked for your name. ‘Pseudo what?’ we hear you say. Neil asks a question. allowing us to count the number of times that we have been around the loop. leaving you with only 2 guesses left. it’s a great tool to game: guesses and score. We’re going to move back to using the more advanced Python on the Raspberry Pi over the next twenty or so pages. Matt prompts Neil to ask the first question. Your score will increase by one.8 As you can see. Inside So why did we include that piece of Python code in a the loop. In Python our code looks like this many applications. then the game will automatically skip to the Game Over screen. The flow of the game should be as follows: Click on green flag. Let’s look at a simple example: a has the value of 0 while a is less than 10: print on the screen the value of a increment a by 1 So we have our pseudo code. enabling us to reuse their value many times in the game. understand coding but it’s also great fun to learn. change a by 1 print a This gives the variable a the value of 0. WorldMags. Matt will tell you your final score and then say ‘Game Over’. Scratch tutorial? It simply illustrates that there isn’t a lot of then increment the value of a by 1. The Game Over sprite will appear on screen and all of the scripts in the game will be turned off. We’re going leave Scratch for now. This loop will continue until difference in the logic between the two languages. Coding Made Simple | 91 .

so start it up now unhelpfully appears behind the Minecraft window. however. game called Minecraft. then navigate to the python/ Minecraft aficionado. no previous tutorial. whose IDLE can talk to it. We need it open so that Space makes you (actually the Minecraft protagonist. if you were already flying). To choose a type of block to place. So either minimise the Minecraft window with the W. in Create New to generate a new file probably noticed we made in the that the Pi edition is slightly restricted. S and D keys. WorldMags. complete with helpful syntax highlighting. select Run Module or press F5. A. If you edit the code Steve feels catastrophically compelled to introduce his sword to the TNT. name is Steve) jump. so use that . and look around with the mouse. improbable Open. Click on Start Game and then because of the selfish way the game accesses the GPU. wherein we met the Geany IDE. which you might have heard of. Ultimately. and click on the Raspbian menu. guide to the interface opposite – note that only the press E to bring Interpreter window up a menu. There’s no crafting. T he rationale for favouring an integrated development interface) for hooking it up to Python. There’s a quick used for placing blocks. and double-tapping Space makes you You’ll find Python 2 and 3 versions of IDLE in the fly (or fall. So in no time you can environment (IDE) is discussed in the Mint section be coding all kinds of colourful. After a few seconds. From the Run and it is free. but it does support networked play. You’ll notice that it rather You’ll find Minecraft in the Games menu. The Interpreter window with a comprehensive API (application programming now springs to life with its greeting. opens initially. obsidian and TNT blocks. effect ignoring anything else on the screen and summarily you’ll find yourself in the Minecraft world. Raspbian comes with IDLE – an IDE IDLE hands specifically designed for the Python language – and we’re We’ll put Minecraft aside for the moment as we introduce going to use it to further our programming adventures using a IDLE. It’s actually harmless because it’s not live. code. The Editor window opens to display our enemies and no Nether. This can be changed. It also has another trick up its sleeve – it comes menu. improbable things involving (see page 28). 92 | Coding Made Simple WorldMags. efficient way to work.. In the event “In no time you can be coding all Select File > that you’re already a kinds of colourful.” folder and open the helloworld. You can navigate drawing on top of it.. Press Tab to release the mouse cursor from the Coding in IDLE Make Python coding more convenient and start hacking in Minecraft. you’ve things involving TNT blocks. or put it somewhere out of the way. The Minecraft Python API has been landscape with the left mouse button – the right button is updated to support version 3. You can bash away at the Programming menu. This is as a pre-coding warm-up. it comes down to being a more centralised.

com. Add the save it first – you can’t run unsaved code.getPos() offending bit of code is highlighted in red.setPos() to change it. These functions are beyond the scope of this the y direction determines your height. Fortunately. Similar to Geany (see page checks the syntax of your code. and again make sure the Minecraft choosing File > New from the Interpreter window.postToChat(‘Hello Minecraft World’) through your code. primer. we can also tell IDLE to execute visible. Now return to your program and run it does something: once again. The mc step by step. mc (short for minecraft). then executes it. and run your program.Player. it the debugger window. classes or methods of any code we have open appear. worry about going on in the debugger.player.] wander around the variables x . and mc. Python keywords are highlighted. a everything up to this line. It also shows any variables. Now enough) ridding your code of bugs. A few seconds later. the Run Module helpfully asks if you want to current position. so that our program actually Debug > Debugger. The second Catching the bug line sets up a new object. IDLE auto-indents with the output appearing in the shell. Steve doesn’t get from mcpi. presumably a little The first line imports the Minecraft module into our code discombobulated. Next. choose game. using four spaces. The debugger enables you to run step by step mc. We’ll start window is visible before running the file and start a new one by Save this update. There’s a lot of stuff you needn’t program. Notice that in the game will vanish. you get an error message and the but then we suddenly find ourselves Python talking to our Minecraft game: high in the sky and falling fast. The IDLE interface WorldMags. though… – don’t worry too much about the awkward syntax here. and on our go ahead continue. Now let’s add a third line. Press Go again to initiate left change.player. rather than a tab. And we can do an awful lot more. Output from programs run from the Editor appear here. y. the our new program with the boilerplate code required to get message is displayed. without saving it. Right-click the final setPos() line and choose object acts as a conduit between our code and the Minecraft Set Breakpoint. but from our own far as being sent skyward. y + 50. z) Close the helloworld. arrange windows so that both your code and Minecraft are By defining a breakpoint. unfortunately. If all goes according to plan. y and z from the getPos() line have been Minecraft world. 28). This This is where we edit our code. choose Go. but you’ll be able to find some great The API contains functions for working with the player’s Minecraft tutorials at Martin O’Hanlon’s handy website: position: we can use mc. using the We can use IDLE’s built-in debugger to see this happening create() function that we imported in the first line. in the Interpreter window. z = mc. all you need to know is that setBlock() functions for probing and manipulating the the x and z directions are parallel to the world’s Coding Made Simple | 93 . You’ll find the Run Module option (F5) here. If your code following lines to your code: contains mistakes. You can access it from the Run menu Editor Window menu. but do worry about getting the capitalisation correct. but not as display messages not from other users. Q WorldMags. Don’t worry if the idea of doing geometry The Minecraft API also contains getBlock() and is terrifying or offensive – for now. and he’ll land somewhere around where mc = Minecraft. and navigates any breakpoints you’ve set up in the Editor.setPos(x. you’ll notice that some numbers in the top. which is incredibly useful for (funnily Save this file in the python/ folder as Debug The built-in debugger helps you to track down any errors in your code. co-ordinate system. From message should appear in the game. mc.minecraft import Minecraft hurt in the game. but notice that the As you [you mean Steve – Ed.getPos() to get the player’s http://stuffaboutcode.player. Interpreter We can use this shell exactly as we did earlier when we ran Python from the command line. Class browser This is where the functions. We’ve manipulated the game’s chat feature to window we get as far as displaying the message.create() he was before the program was run. calculated in the Globals panel. These give your position in terms of a 3D Steve’s catapulting skyward. and environment. As before.

From the interpreter. we can get down to some proper coding. for itself. You can override the behaviour by specifying a sep parameter to the function – for example. print() also issues a most suitable for beginners can be debated until the bovine newline character.‘) Having pressed Enter and greeted our Python 3: Go! Learning to program with Python needn’t involve wall-climbing or hair-tearing – just follow our three guides to Python prowess. If the >>> import math previous command indicated that this was the case. then you’ll need to find the python3 the recently defined x is a floating point number (or float for packages from your package manager. but for this calculator. the syntax favours simplicity specifying the end parameter. Either way. by Python code is easy to follow. Learning a new following code uses a dot: programming language can be as daunting as >>> print(‘Greetings’. Your distribution probably Besides welcoming people. but Python is certainly a worthy candidate. while If that doesn’t work. * tutorial we’re targeting the newer version 3. final argument. Exactly which language is separation at all. WorldMags. where we would have to straightforward to locate and install. . on the other hand. as well your Python version by opening up a terminal and typing: as many more advanced maths functions if you use the $ python -V maths module. throughout and its enforcement of indentation encourages depending on the circumstances. which is accomplished as follows: >>> name = input(‘State your name ’) Note the space before the closing quote. command succeeded. Unlike typed languages. It understands + (addition). Note that we don’t need to put spaces around our variable. it is separated from our curt demand. . name. Also. Besides separators. we can use the interpreter as a already has some version of Python installed. which is sometimes desirable. saving us the trouble. the explicitly specify the type of a variable where it is defined. If. We could also have used a print() line to display this prompt. good coding styles and practices. / (division) and ** (exponentiation). see what >>> x = math. ‘enjoy your stay. represented by the string ‘\n’ after the herd returns. we can also use the print function: >>> print(‘Greetings’.’. and here is have fixed types. print separates arguments with a space. This means that when the user starts typing their name (or whatever else they want). They should be short). Python variables do not Here you can execute code snippets on the fly. find yourself at the Python 3 interpreter. as we did with the input function.(subtraction). though. to find the square root of 999 Many distributions ship with both versions installed. but times 2015 and store the result in a variable x: some (including Debian 8) still default to the 2. so we could actually recast x above to an where we will begin this tutorial. all the more so for those embarking On the other hand. by default. then you will. and then instead used a blank input call as follows: >>> name = input() This means that input is accepted on a new line. For example.sep=‘. This can be easily changed. >>> quit() However. ‘enjoy your stay.sqrt(999 * 2015) happens if you do: One of many things that Python helpfully takes care of for $ python3 us is data types. which will appear alongside.’) it is rewarding. using sep=‘’ instead gives no on their maiden coding voyage. It’s useful to accept and work with user input. You can check (multiplication). Our first variable name was a string. we can see the values of any variable just by typing its name – however.’) The print() function can work with as many arguments as you throw at it.7 series. The command prints the given prompt and waits for something to be typed. besides being availed of Python is smart enough to figure out that sort of information version information. each one separated by a comma. so let’s instead do a cheery: >>> print('Hello world. You can exit the interpreter at integer with: any time by pressing Ctrl+D or by typing: >>> x = int(x) 94 | Coding Made Simple WorldMags. your first lines of code really ought to be more positive than that. the A fter the basics let’s delve into Python. the user’s input is stored as a string in a variable called name.

2)) arbitrary example: Negative step sizes are also supported. but Python is not one of them.append(19) We can also get the last character using name[ -1] rather We could also insert the value 3 at the beginning of the list than having to go through the rigmarole of finding the string’s with twostep. such as: Thus we can get the first character of name with name[0]. and omitting x defaults to the end of the list. Similar to slicing. So we could Strings are similar to lists (in that they are a sequence of add 19 to the end of our previous list by using the append() characters) and many list methods can be applied to them. >>> twostep. For example. the range() function returns an iterator (it doesn’t contain any list items but knows how to generate them when given an index). method. Methods in Python are firstList[2].2. There are many other list Coding Made Simple | 95 . you’ll probably find that any additional steps to get Python working. Omitting x defaults to the beginning of the list. which defines the so-called step of the slice. separate IDLE shortcuts for starting each $ sudo apt-get install python3 Now x has been rounded down to the nearest whole number. It’s included in the Raspbian distribution. or wherever the previous step lands. there are a number of constructs available for defining lists that have some sort of pattern to them. You might pressing F5 or selecting Run Module from the running python3 returns command not found. you get the pleasure of a ready-to-roll out a few lines of code and then run them by don’t have Python 3 installed (in other words development environment called IDLE. Thus slicing our list above like so returns the reverse of that list: >>> firstList[::-1] Besides defining lists by explicitly specifying their members. so we could count >>> firstList = [‘aleph’. Some languages are one-indexed. and omitting y defaults to the end.3). and again it’s something we simply have to get used The IDLE environment is ideal [ha. These are short forms of the more general slicing syntax [x:y]. ha – Ed] for developing larger Python to. 3. Items in our list are zero-indexed. In Python 3. select New Window. the slice [x:y:2] gives you every second item starting at position x and ending at position y. and such things certainly become versions 2 and 3 of Python. because 6 is not in that Raspberry Pi-thon If you’re following this tutorial on a Raspberry Pi IDLE enables you to write and edit multiple lines version. of code as well as providing a REPL (Read only the former. arguments specifying the start value and step size of the We could convert it to a string as well. and this can be a they’ve been defined. and are called by suffixing said people find more intuitive.3. WorldMags. Again. One can even specify a third parameter. fine because they can be redefined. too. witness some rather strange behaviour. length first. so we access the first Items can be inserted into lists – or removed from them – item. Here’s an >>> twostep = list(range(5. which returns the substring starting at position x and ending at position y. copied or reconstructed When you start working with multiple lists. WorldMags. with firstList[0] and the third one with by using various methods. We can get the first two elements of our list by using firstList[:2].4. A list is between 5 and 19 (including the former but excluding the defined by using square brackets and may contain any and all latter) by using: manner of data – even including other lists. but if you’ve done an apt-get there’s good news: you don’t need to perform Evaluate Print Loop) for immediate feedback. range.14159265] down from 10 to 1 with range(10.insert(0. together with two $ sudo apt-get update advantageous when working with larger projects. Again. Help is available for function. this can be abbreviated – if you just want every second item from the whole list – to [::2]. In see this in action.0. we can make the list [0. in which case our starting point x is greater than y. or all but the first item with firstList[1:]. so there is an additional function call to turn it into a list proper.1. object with a dot. Previous Raspbian versions came with (1 or 2) and using the Raspbian distribution. This means that we can get all the odd numbers Another important construct in Python is the list.19. followed by the method name.-1). such as the diagram A particularly useful construct is list (or string) slicing. for which you would have to use the len() which you can peruse using help(list). the range() function can take optional projects. they cannot be changed – but this is very useful resource when you get stuck. ‘beth’. hammer the new version has been pulled in. for example. To dist-upgrade recently. using the str type. which some properties of an object. Negative step sizes are also permitted. find this more fun to work with than the Run menu.5] by using list(range(6)). then you can get it by opening LXTerminal and command-line interpreter we use throughout Newer versions of Raspbian come with both issuing the following commands: this tutorial. you might depending on our purposes. For example. But if you fact. Strings are immutable – which means that once any Python keyword and many other topics. there is potential for 0-based grievances.

you must accept the consistency is key. or >>> for count in range(5): the first line of The Wasteland. equal to (>=) operators conjoined with an or statement to wherein a codeblock is iterated over until some condition is test the input. even though it’s awfully handy for checking code snippets. So long as year has an unsuitable value. You may indentation. we The code still runs if you don’t indent this last even wish to use a development environment such as IDLE line. enter the following listing: There are all judicious use of white space. so many variables can point to just keeps asking you the same thing until an appropriate the same thing. our wily while loop keeps It’s time for us to level up and move on from the interpreter – going over its code block until some condition ceases to . KDE’s kate or The print statement belongs to the loop. things inside a for 1900. for example. want to iterate over different values for count. import datetime def daysOld(birthday): today = datetime. ‘Saturday’. so (which comes with Raspbian and is designed especially for only gets executed at the end. which we can >>> count = 0 either import into the interpreter or run from the command >>> while count < 5: line. as shown here: save our code to a text file with a . but in Python it’s all colons and Having found such a thing. Fortunately. we’re using the for construct to do keep asking. Other languages delineate code blocks for this opposite illustrates. It is initialised to 0. enter their granny’s name. so we are guaranteed to enter the loop. so let’s look at a more involved example: # My first Python 3 code. You need to find a text editor on your system – you can … print(count) always use nano from the command line. it We can easily implement for loop functionality with this is not suitable for working on bigger projects. such as Gnome’s gedit. you were born on a’. birthmonth. the canny coder makes extensive use of loops. by which time the value of the language) but we don’t require any of its many features This Pythonic creed is worth count has reached 5. programming >>> year = 0 # The # symbol denotes comments so anything you put here habits. ‘Wednesday’. form. but in that case the print call is not part of the loop. They could. the prompt changes from >>> to …. That while loop was rather #! /usr/bin/env python3 kinds of bad trivial. count) interpreted as a year. Instead we’ll construct. WorldMags. which is certainly less than some counting. ‘Sunday’] birthyear = int(input(‘Enter your year of birth: ’)) birthmonth = int(input(‘Enter your month of birth: ’)) birthdate = int(input(‘Enter your date of birth: ’)) bday = datetime. then you can ‘1979’ – needs some treatment. If you always returns a string. change 2015 if you want to keep out interpreter. studying. ‘Thursday’. which guarantees that we range iterator. Python (honest) youngsters. so even good input – for example.weekday()] print(‘Hello. string consisting of anything other than digits to an int. Note that the input function issue five print statements in only two lines of code. value is selected. trying to compare a string use a different range or even a list – you can loop over any and an int results in an error. We (alongside many others) like to use possibility that they will enter something not of the required four spaces. objects you like. We use the less than (<) and greater than or Very often. When you start such a block in the program.birthday). using brackets or braces. dayBorn) 96 | Coding Made Simple WorldMags. Another type of loop is the while loop. Rather than Grown-up coding iterating over a range (or a list). thanks to the the lightweight Leafpad. but Whenever you deal with user input. birthdate) dayBorn = weekdays[bday.days return(ageDays) if __name__ == ‘__main__': weekdays = [‘Monday’. The result is that we continue looping the loop. Likewise. so just a simple text editor will extension. which comes with Raspbian. so this code variables are really just labels. permits any number of spaces to be used for indentation. ‘Friday’. the last line of our example Enter a blank line after the print statement to see the does a good job of sanitising the input – if we try to coerce a stunning results of each iteration in real time. You could loop (or indeed any other block definition) must be indented. ‘Tuesday’. neither of which can be … print(‘iteration #’. change 1900 if you feel anyone older than 115 might use your otherwise you get an error. not just integers. which we met earlier. Note the indentation here. For our first loop. but you may prefer … count += 1 to use a graphical which >>> while year < 1900 or year >= 2015: doesn’t matter are best to avoid … year = input(“Enter your year of birth: ” ) from day ageDays = (today . This seemingly inconsistent behaviour is … year = int(year) all to do with how variables reference objects internally – We met the input statement on the first page. then The variable count takes on the values 0 to 4 from the we end up with the value 0.

so using this as an index into our list weekdays in the instructions. ‘Sun’] >>> [j ** 3 for j in range(11)] It’s worth noting at this point that to test for >>> days = [j + ‘day’ for j in daysShort] This returns a list comprising the cubes of equality. Therefore we can apparently command line. anyway – first we must make it executable by running the following command from the terminal. ‘Tues’. you can find some great Python tutorials on the web. we haven’t bothered with list language constructs. which returns a datetime.’) Save the file as ~/birthday. No tutorial can teach this.timedelta spooky action at program or the j and k. returning the number of days the user has been alive. Python also has a huge number of modules (code libraries). ‘Satur’. example. Be careful. We have written a bona fide object. but hopefully we’ve next line gives the required and www. is datetime. before. – and our next line (using the input that we quite extensive. as opposed to being import-ed into another subtract two dates. It’s not the if block is ignored. This example uses the datetime module. The final line calls our sufficiently piqued your curiosity that you will continue your function from inside the print() function. You are free to remedy either of these and more exciting project. We’ve actually covered a good deal of the core demons. provide sensible dates. The special variable __name__ takes on the such as weekday() and year(). demonstration of Python’s laconic concision. Our iterator variable j runs we could select only those beginning with ‘Z’ or introduced can join forces to form one of over the beginnings of the names of each day of those which have ‘e’ as their second letter by Python’s most powerful features: list the week. species. To keep things (Python programs all have the . working with lists. but now we’re making our own. and we trust the user to difficult to develop the ideas we’ve introduced into a larger Python rolls. The first line just tells Bash (or whatever shell you use) to execute our script with Python 3. the numbers from 0 to 10. Due to leap years. which also strive for simplicity. However. And so concludes the first of our Python coding tutorials work of Chthonic The next four lines are similar to what we’ve come across on the Pi. you could try: [‘Herman’. Our function takes one parameter. you can dive straight in and see it in action. ‘Zanthor’] ‘Thurs’. including We also have plemnty more excellent tutorials in this very weekday(). The The datetime module provides a special data type – official tutorial (https://docs. which provides all manner of functions for working with dates and times. ‘Wednes’. we use the == operator. date objects also allow for run into this special value __main__ when the code is run from the general date arithmetic to be done on them. These are a great suffixes the string day – the addition operator >>> names = [“Dave”. this would be some pretty fiddly calendrics if we had to work it out manually (though John Conway’s Doomsday algorithm provides a neat trick). which we use next. if we have a list of names. coders use short variable names. then we can call it into action: $ chmod +x ~/birthday. and then our list comprehension using: $ ~/birthday. but when we import it. Comprehensions can because a single equals sign is only used for commonly i. then the program works out how many days old you are and on which weekday you were born. use all kinds of other constructs as well as for assignment. (+) concatenates (in other words. though. and with a little imagination it’s not it’s just how comprehension for the weekdays. 5: would result in an error. daysOld(bday). Before we analyse the program. for ephemeral variables. because there are a couple of things that we haven’t seen before. joins) strings “Zanthor”] Consider the following example: together. As well as having a simple core language structure.codecademy. This returns an integer publication. learning to code is much more between 0 and extension). If you want a more arithmetical >>> [j for j in names if j[0] == ‘Z’ or j[1] == ‘e’] >>> daysShort = [‘Mon’. so doing something such as if a = such as those which are used in loops or loops. everything in the or seconds(). Besides methods coding adventures. and uses the datetime module to do all the hard work. and using your newfound skills. which we can then convert to an integer using days() a distance when Python module here. Very often. Date objects have various methods. Help is never far print(‘and are’. Q List comprehensions Lists and the various constructs we’ve just If you entered everything correctly. Next. with 0 corresponding to Monday and 6 to about experimentation and dabbling than following Sunday. oddly enough. after the comments. Almost. ‘Fri’. “Herman”. The def keyword is used to define a function – we’ve used plenty of functions in this tutorial.‘days old. we import the datetime module and then begin a new codeblock. birthday. and you can find others at http:// have just harvested) sets our variable bday to one of this tutorialspoint. WorldMags. For Coding Made Simple | 97 .python. The strange if statement is one of Python’s uglier You might constructions. We’ll do a quick rundown of the code. “Xavier”.

The API. a multicoloured LED matrix and much more.raspberrypi. where they will be run in zero-G. Owing to power requirements aboard the space install. Also worthy of attention. They’re not critical for understanding this tutorial. because many young learners find programming much more intuitive when the results can be visualised three-dimensionally from the point of view of WorldMags. whence comes the code used in this tutorial. e have published a fair few guides to the Python W API for Minecraft:Pi edition for the Raspberry Pi. you can still have a lot of fun playing with the Minecraft Python API. the Pi cannot be connected to a proper display – its only means of visual feedback is the 64-LED Astro Pi and Minecraft We conclude our Python exposition on a recreational note. combining Minecraft and space exploration. so can still provide a fair amount of --no-check-certificate | bash It takes a while to run on the original. attired with an Astro Pi. and also featuring excellent Minecraft tutorials. will join ESA astronaut Tim Peake for a six- month stay on board the ISS. The lucky winners will have their programs join Tim on his voyage to the ISS. and will very soon be available to the general public. Minecraft. It is available for free for school pupils and educators from the website . This is a Hardware Attached on Top (HAT) expansion board. but you can also download an installer for these. accelerometer. install it from the repositories: $ sudo apt-get update $ sudo apt-get install minecraft-pi If you don’t have an Astro Pi board.If you don’t have it. various environmental Open a terminal and type: $ wget -O . The Astro Pi ships with a Raspbian SD card preloaded with all the required drivers and configs. single-core Pi. which features all manner of cool instrumentation: gyroscope. magnetometer. One of the most exciting Raspberry Pi projects right now is the Astro Pi. While we’re setting things up. further edifies the Pi’s status as an educational tool. see page 108. a Raspberry Pi. and you’ll need to reboot for everything to work properly. enter a new world. but are certainly worth checking out if the idea of programming a voxel-based world appeals. These are installed by default on recent Raspbian versions (there should be an icon on your desktop). The most exciting thing about the project is that in November 2015. A competition is currently underway across UK schools in which entrants must devise Python code utilising the Astro Pi. then Alt+Tab back to the 98 | Coding Made Simple WorldMags. if you can come up with a good coding idea.http://www. the game’s intrepid hero. This is multicoloured. make sure you’ve got Minecraft and the Python 3 API set up too. though. is Martin O’Hanlon’s excellent website http://stuffaboutcode. besides being a lot of fun. connecting via the GPIO pins. Just start Astro Pi sits snugly atop Terrestrial Pi.

35. >>> mc.T. 0.setBlocks(-5. O. 1. -2.setBlocks(0. O. X. 3. 13) O.set_pixels(question_mark) The setBlocks() function fills the cuboid given by the first It is probably more desirable to type this code into a text six numbers (the first three are co-ordinates of one corner editor and then import it into Python. O. 42) ] >>> mc.setBlocks(2. -7. -2. O.setBlocks(-6.. O. rather than work in the and the next three are co-ordinates of the other corner). 0. We’ve used the setBlock() function above – this just sets up a single block.setBlocks(-6.“) hand. 42) O. >>> mc. air warmed by the Pi’s CPU won’t join astronaut Major Tim Peake aboard a Soyuz Measurements. too. instead it will just hover around in (glorious nation of) Kazakhstan. As well as text. we’ll turn our attention to coding on the Astro Pi. 11.Minecraft. we don’t need to specify a colour. 35. 0.show_message(“E. >>> mc. X. -2. O. -2. For now. O. desktop and open a terminal window.. 15) >>> mcsetBlocks(0. we can also load images general is referred to as block data. so that our ap 35 stands for wool). Space Radiation here on Earth). 11. 2. -3. -2. >>> mc. O. >>> mc. WorldMags. 11. O. This connects to the Pi via the General Purpose Input/Output (GPIO) pins. O. 0] # Red Python 2.setBlocks(-5. 15) O. O >>> mc. Wool is a special block that comes in 16 object is correctly set up. as well as to provide pupils. O. O. >>> mc. -2. O. O. with the winners having Tim run their anything that is going to be connected to the ISS much needed airflow. -2. but you information there. O. 42) O. 11. we don’t need to worry about coding at the level of individual pins. -2. 42 ) O. though. O. O. O. O. two Raspberry came together to make this exciting outreach electromagnetic interference. O. next number decides the block type (42 stands for iron. -2.setBlocks(-6. You can find a thorough guide to the API at www. O. X. X. we can through an optional eighth parameter. You can use this trick as a slight shortcut if you’re only throughout this change the player and camera position.stuffaboutcode. -9. Space. X. 2. O. O. -2. -4. So you need to put the first two lines from our E. 35. because each LED requires its own colour you use Python 3 The API is capable of much more than this – we can triple. get the ground level going to be working with a few api-reference. 8. -3. 0. O. 35. -6. 35. For example. so only requires one set of co-ordinates. The following draws a rough and ready O = [255. This carefully machined and very strong case (it’s made of 6063 . being hazardous. -2. O. WorldMags. O. O. we can display a suitably space-themed message in an extraterrestrial shade of green using the show_message function: from astro_pi import AstroPi ap = AstroPi() ap. O. >>> mc. The interpreter. From here. including are not allowed to exceed 45°C. and one with the normal Pi-Cam) will identified to inspire junior coders: Space conditions. Satellite dissipate (as happens naturally by convection rocket.html.0]) grade aluminium.create() probably isn’t the type of thing you want to do too much of by We’re assuming >>> mc.setBlocks(7. O. but we’ll describe what everything does as we use Coding Made Simple | 99 . -1. 7. 255. O. -2. O. blasting off from Baikonur cosmodrome Imaging and Remote Sensing. 5. -2. O. though: The mission On Thursday 19 November 2015. 15) O. X. This project still works with at a given set of co-ordinates. 0. text_colour = [0 Space case.postToChat("Hello world. O. -2. The module provides some simple and powerful functions for querying sensors and manipulating the LED array. O. X. 42) O. >>> mc. O. O. and get and set block X = [255. There heatsink for the Pi’s CPU – surfaces on the ISS Station. O. The flight case has been A nationwide coding competition was Getting the Raspberry Pi and Astro Pi precision-engineered to comply with rigorous launched for primary and secondary school approved for cargo is a complex process – vibration and impact tests. using the set_pixels() function. O. -1. 15) ap. 255] # White may need to install representation of a Raspberry Pi (it could be a Pi 2 or a Model the Pillow imaging B+). O. As so. -9. phone home. Spacecraft Sensors. It also acts as a giant code when he arrives at the International Space power supply has to be thoroughly tested. while phone home snippet at the top of the program. 8. 7. and thermal testing – in zero-G module. O. O. which in well as dealing with individual pixels. O.255. 35. plus the block type and optional block data arguments. This tip >>> mc = minecraft. -8. O. O. 8. -2. but if we wish to do interpreter or run it from the command line if you prefer. don’t ya know) will house the Pi on its space odyssey. -2. but thanks to the astro_pi Python module. X. -2. 15) O.T. sharp edges Pis (one with the infrared filtered Pi-Noir camera project possible. -2. and Data Fusion.setBlocks(4. -6. start Python The text_colour parameter here specifies the RGB 3 ($ python3) and enter the following: components of the colour. You can then import it into the colours.setBlock(-6. A number of themes have been assessment. -6.”. X. industry and education sectors are all manner of considerations. component by component: question_mark = [ library with sudo pip install Pillow. we can also work Quick >>> from mcpi import minecraft with the individual LEDs. O. 1. -2. 6. -9. O.

if you’ve still got a pixel art and the like. Left-clicking results in Steve hitting stuff Martin O’Hanlon. If $ sudo python3 rainbow. Hitting the sensors. Before we run it. You can also use the $ cd ~ virtual joystick to move the virtual assemblage in three Sword-wielding Steve stands ominously close to a USB port. Normally. To download the code to your sense. Instructions for this are at www. but this one is virtual device.load_image("~/astro-pi-hat/examples/space_invader. but it’s excellent for displaying make sure Minecraft is started. get_ run it through sudo: temperature() and get_pressure(). then displaying 15-bit colour depth (five bits for red. the LEDs are only capable of Python session open from the beginning of the follows: MinecraftInteractiveAstroPi. equipped with the Astro Pi HAT. which is given in terms of the pitch. who submitted the idea to the message telling you to hit the virtual Astro Pi by right-clicking Astro Pi competition. Minecraft allows you to fly by tapping and then The project we’re going to undertake is actually the brainchild holding Space.0. y and z positions. but they are nonetheless at right angles to each other some great examples in the ~/astro-pi/examples directory.php?t=109064. we need to self-explanatory functions get_humidity().md. 100 | Coding Made Simple WorldMags. You can also find out the it. and go in directions parallel to the ground plane. The (extensive) coding was done by it with your sword. Run these with. Also. and explain select parts of pressure.png") This downloads all the required project files into the Bear in mind the low resolution here – images with lots of ~/MinecraftInteractiveAstroPi/ directory. Don’t expect to understand everything in the code right orientation of the Astro Pi. Something about knives and toasters. So fly up to this and you’ll see an introduction of student Hannah Belshaw..raspberrypi. $ cd ~/MinecraftInteractiveAstroPi accelerometer and magnetometer are all integrated into a $ sudo python mcinteractiveastropi. just open up a terminal and issue: forums/viewtopic. it’ll serve as an excellent base calibrated the magnetometer for these readings to make for adding your own ideas. You can explore all the components of the Pi and the Astro Rather than have you copy out the code line by line. The project properly. so colours are dithered accordingly. but you can find all the relevant API of numbers which identify tiles by their x. Now and five for green). the which show off everything from joystick input to displaying a player will start at position 0.git The y co-ordinate measures directly on to the array by using the load_image() function as $ git clone https://github. The gyroscope. for example: co-ordinates in the upper-left corner). detail don’t work very well. You’ll also find define. we’re good to go. Bear in mind that you need to have you get a couple of footholds.0 (you can see your rainbow pattern. Because the Astro Pi libraries need GPIO We can also query the Astro Pi’s many inputs using the access. you will see that this partial eclipse is caused by the appearance of a blocky contraption that our code has The virtual interactive Astro Pi created. to whom we’re ever so grateful. and this in turn requires root privileges. the latter avails you of the local download it straight from GitHub. away – there’s a lot of stuff we haven’t covered – but once roll and yaw angles. in which case you $ cd ~/astro-pi-hat might notice that it suddenly got dark in Minecraft-world. temperature and humidity. calls in the documentation at https://github. WorldMags. We won’t be doing Everything in Minecraft is located by co-ordinates – triples any inertial so-called Inertial Measurement Unit (IMU). Also. so don’t do that. six for .org/ home directory. x and z are harder to astro-pi-hat/blob/master/docs/index. which would destroy the blocks that constitute our draws a Raspberry Pi (like we did earlier).py you look up. we’ll Pi. exit it now (Ctrl+D) so that things don’t get confused.

this ensures that “ humidity = {}. 1) there are a few more. y + j + 2.setPos(x. and mad props to Martin command line or just imported. #sleep for a bit query the Astro Pi hardware and display current readings. z = mc. minecraftstuff.setPos(). the resulting mc. def teleport(x=0. 46. For instance. We pass that we may not be interested in. So that the player can keep for allowing us to use his code. teleporting and TNT Even if you don’t have an Astro Pi. mcinteractiveastropi. When a block is hit. which reconciles the 16 colours of wool available with something that the LED array can understand.1) joystick even moves the Pi around. #each time a block is hit pass it to the interactive This probably which is a human-readable string describing the blocks in astro pi isn’t a safe question. try this one) statements and #keep reading the astro pi orientation data otherwise the appropriate action is taken. then use the . zedge_hi.getPos() chain reaction will be very taxing.5 + j between Python and Minecraft). we can move up in-game. if the mcap. We can use curly braces as placeholders for do.format() method to determine how construct usually used in conjunction with an except: for they are displayed. you can catch a glimpse of how things work. series of if and elif (short for else-if – in other words. It’s used to forth and do these things. if you prefer). the player to the coordinates of our choosing their explosions by using some additional block This sets the TNT to be live. But fret not – mature adults can get The magic is all in that final [code] 1 [/code]. Studying the code If you open up the main project file. Rather than using the setBlock() functions. you need to set up arguments takes Steve back to the origin (where xedge_hi = xedge_lo + 10 . then you’re If you’ve had a look at the various blocks zedge_hi = zedge_lo + 10 . the following string (from line catching errors and exceptions.postToChat(). Q Minecraft: Pi Edition API. y. ap. and the Astro Pi is reset. postToChat() and setBlocks() functions. We have already seen the dimensions: the button toggles whether it moves in the horizontal or vertical plane.pollBlockHits(): place to stand. and can in fact be instantiated as many times as you like.2 * j the mc object (which handles all communication the Astro Pi is drawn). either by Because the sensor data often has lots of decimal places pressing Ctrl+C or by killing the Minecraft program.2 * j good to go. This loop runs until it is forcefully interrupted. which in fact deals with all the components that can Bring TNT be hit. Some of the components just it goes out of sync display an informational message using mc.format(round(humidity. Hannah. We’ve already met the slightly odd if __name__ == “__ This is a really great project to explore and extend. y. WorldMags. In our case. you’ll no doubt have discovered TNT mc. we take advantage of the position of each block-hitting event to the interact() Python’s string formatting capabilities to round things function.5 + j you’ve imported the module. Once here. it is followed with 157) formats the readings for the combined humidity and a finally:. for discern whether the program has been executed from the coming up the idea in the first place. which figures out what has happened and what to appropriately.pos) previous condition didn’t hold. This is done in the interact() function. this property is checked using a for blockHit in mc.get_orientation() some. These have a property called tag. Here’s a function that’ll figure out Steve’s click it with your sword (or anything). The main loop is wrapped in try block. in a text editor (or IDLE. so that if you left- with player. so that calling teleport() with no xedge_lo = x . In this case.2). all you need to understand is that the board we draw in Minecraft is an instance of the object whose description begins with the class at line 19. the virtual Pi is round(temp. temperature = {}”. Quite early on is defined a list called LED_WOOL_COL. you ought to migrate to a safe distance. then it write and call a simple teleport function from position and then assemble a substantial begins to flash and pulsate ominously. but (block type 46). it changes colour and the corresponding LED on the array does likewise.setBlocks(xedge_lo. zedge_lo. Coding Made Simple | 101 . We won’t go into the specifics of object- oriented programming and classes. Also great work. This means that we can data. y+ j + 2.player. zedge_lo = z . z) file). the virtual exploring. y=0. this block of code contains a main loop which to life with the magic of Raspberry Pi is constructed of objects from the custom constantly polls for new events (the player hitting blocks): the Minecraft shapeBlock class (which you can explore in the while(True): Python API. Sadly. The particular instance created by the code is called mcap and is defined way down on line 272. such as the environmental and orientation sensors. When we hit a virtual LED block. At this within the interpreter: pyramid of live TNT above him: point. the sleep(0.interact( so go main__”: construct in our first tutorial on page 96. which is executed (whether or not an exception temperature sensor rounded to two decimal places: arises) when the try: completes. z=0): def tnt_pyramid(): Also. for the older. This object has its own variables and functions. single-core we kill our running code with Ctrl+C. you can still We’ve given some defaults for the arguments for j in range(5): have a lot of fun with the Minecraft API. For example. 2)) dematerialised. there isn’t a way to blow it xedge_hi. which is a variables.player.

sorting things (putting concepts. In theory. but it programs. because searching and indexing course. but this way we have a well-defined order (ascending data is much easier if it is in Sorting lists faster in Python We haven’t got time for this. W ithin the human species. you whatever ordering the user desires. listing tracks with the task (or give up and find something better to do). WorldMags. one could even re-enact Rob dedicated) in their approach. it enables us to show some of them into some kind of order) is perceived as Python’s advantages. albeit described in the purchased them) from the Nick Hornby book High Fidelity. When challenged with the drudgery-filled task of. All should not delve. Pseudocode is a freeform way of expressing code that A workaround Sorting may not be the most glamorous of programming lies somewhere in between human language and the is to add pylab. These enable a modern computer to suit by face value. say. Quick useful would be an unsorted telephone directory. We’ll sum up some of these with pseudocode box displays only a blank window. We’ve actually overlooked a couple of 102 | Coding Made Simple WorldMags. below. Imagine how much less numerical) to aim for. As such. be it lexicographical or Machines obviously need to be more systematic (and might find that chronological. and indeed Python’s built-in sorting methods will programming language. Code-folding and highlighting without the bloat. and eventually complete a new version Rhythmbox) library in a matter of seconds. including its no-nonsense syntax and anywhere between a necessity (things disordered the simplicity by which we can use graphics. Furthermore. albeit several orders of magnitude faster. by comparison. haphazard piling and re-arranging. it’s time to sort out that most fundamental of algorithm classes: sorting (sort of).001) after prove much faster than anything we program here. first by suit and then within each tip of computer science. It’s straightforward enough to the animation Fleming’s autobiographical ordering (the order in which he come up with a couple of sorting algorithms that work. most people will flounder around with some If you’re using happily sort a several thousand-strong iTunes (err. various sorting algorithms were developed early in the history putting 52 cards into order. serves as a great introduction to various programming becomes difficult. topics. Geany is a feature-packed text editor that’s great for editing Python code. of Matplotlib with Gnome. universally of the concepts apply equally well to any other kind of data. not very quickly. but don’t be disheartened when the translation each draw() call. we’re going to work exclusively with lists of integers. It’s a good way to plan your pause(0. To make things cause the most dire distress) and a dark ritual into which one easier. Computers. of prefer things to be .

is that this algorithm (like Selection lists. and much more exciting than the print selectionsort() and quicksort() too – just add k -= 1 statements we used earlier. we resume the outer loop. constant (which depends on the machine) times n^2. But in each loop iteration we must find a minimum element.set_ydata(a) data is redrawn after each list update). Time complexity notwithstanding.plot(x. Once we get back to Very often. complexity. This is – in other words.‘m. As it We again we can deduce O(n^2) complexity. Selection places. including Bubble Sort (aka for each position j in list Sinking Sort) and its parallel version Odd-Even Sort. WorldMags. as n gets large. WorldMags. inserting an item would require the whole list to be shunted down between the insertion and deletion points.1] not the fastest way to display graphics (all the function. which can do all manner of import pylab x = list(range(len(a))) plotting and graphing. was quickly swap numbers at positions k and k .net Coding Made Simple | 103 .a. the beginning.set_ydata() and pylab. visit http://pythontutor. at the beginning. rightfully. InsertionSort. but is outperform Quicksort for small notation to express the function’s complexity as a function of nonetheless minor details here. which is called linear. so the algorithm actually behaves with apparently Here is another naive sorting algorithm.log n) so that it can our sorting algorithms can be brought to life. you the input size. and sorting time. but for j in range(1. What is not immediately obvious. In this situation. having trickled down there by a lengthy swap Quicksort initially. This isn’t saying that Selection be swapped in. quickly. we can tell that SelectionSort will loop over items in the list at least once. As such. We’re going to use the #! /usr/bin/env python3 a = list(range(300)) Matplotlib package. sequence. we suppose our list has n items Sort) has sorted the first i entries after that many iterations can create a hybrid and the crude analysis above says that Selection Sort runs of the outer loop. It’s Here we’ve modified our insertionsort() l[k . Insertion Sort: There are a few other naive sorting algorithms that may InsertSort(list): be worthy of your perusal. We swap items that Quick can approximate how long an algorithm takes to run by are not in order.markersize=6) distros. Note that we swap elements here rather than insert them. the most Selection Sort. We met for loops way back on page 50. thanks to its swift O(n. but that will all be sorted out when we write our actual code.1]. The first loop iteration simply finds the smallest element in our list and places it. which proceeds simple algorithms each going over our whole list. which for the first few loops (where j is This time we are upfront about our two nested loops. It can be found in the from random import shuffle shuffle(a) python3-matplotlib package in Debian-based line. In our case. And so it goes on. this is so that we are only modifying two of our list items. the inner while loop terminates Sort gets pretty slow pretty quickly. until the work is done.draw() easy. We then start at the second item and see whether there is a smaller one further down the list. an out-of-order element may sorting algorithm with complexity O(n^2). list items are not too far from their rightful slightly disappointing news – in layman’s terms. l[k] = l[k]. and code. len(l)): Save this file as ~/animsorting. SelectionSort(list): for each position j in list find minimum element after position j if minimum element is smaller than element at j swap them Selection Sort is a fairly simple algorithm.ion() # turn on interactive mode discussed here. while k > 0 and l[k . There isn’t room here to even scratch the def insertionsort_anim(l): insertionsort_anim(a) surface of what’s possible with Matplotlib. the will pretty much have two loops – one nested inside the other. l[k . Here we can see Selection Sort in action.draw() calls after that can help visualise the sorting algorithms each line that modifies the list. Quicksort was developed in 1959 k-1 and. In Selection Sort’s worst case we continuing to swap out-of-order entries. k=j do chmod +x ~/animsorting. and then move backwards down the list tip looking at these details.’. but we k=j have much to get through so it’s time to look at a grown-up while number at position k is less then that at position method called Quicksort. pylab. It is markedly more involved than the algorithms Visualising sorting algorithms Python has some incredibly powerful modules the line. but in simplicity lies beauty.1] > l[k]: be run from the comfort of the command line. divided. and added some boilerplate code to set line. O(n). reverts to What we can say is that the relationship between input size in many situations. but it’s everything up. but by the end of the inner loop it will be in its which uses Sorting a list of one item will take one second (actually it right place. swapping if so. but as the list is takes 0 seconds) or a list of five items will take 25 seconds. will be less than some obvious one being where the list is nearly sorted to begin with for example. We use so-called big O towards the end. outperforms Selection Sort. so small) involves checking most of the list items individually.1 adopted as the default sorting algorithm in Unix and other k=k-1 and then we can show that with just a couple of extra lines. = pylab. which in the worst case would mean modifying every item in the list – a costly procedure if If you’re looking for an excellent resource for learning and debugging your said list is long. You are encouraged to modify pylab.

looks like: work on the two sublists to the left and right of the pivot. rather . high) briefly how to define functions in the prequel. so we have to do that manually in the last two lines.1: mostly because the tendency is to imagine some kind of If list[j] <= pivotVal: infinite chain of function calls. once it is complete. we are reduced to O(n^2) complexity. Neglecting the details of the partition operation the partition operation runs in O(n) time. our Quicksort pseudocode looks deceptively the partition operation divides the list into two roughly equal simple (excepting perhaps the recursion element). In an ideal situation. The Python code is quite different from the pseudocode. This is where the log(n) in the complexity comes from. So our partition operation. the base cases are the aforementioned lists of left (not necessarily in order). and for subsequent calls they are either from is possible for Quicksort to perform much slower than Elements the low element to the pivot element or from the pivot stated. If Quicksort had a motto. or if a more systematic dividing first and the conquering after. For is arranging the list so that items less than the pivot are to its Quicksort. It length of the list. Eventually. Typically. For the initial function call. which by definition are sorted. This pivot. (Mergesort. trickle one at a If low < high: time from right p = Partition(list. low. sorted list and always use the last (greatest) element as a Insertion Sort Quicksort(list. a decent recursive algorithm # put the pivot after all the lower entries ought to be good at how (and when) it calls itself. Incidentally. because if the condition is false (which would mean the minimum element was at position j). We saw at night-time as Quicksort(list. Unfortunately. an example of a recursive algorithm – Swap list[pivotPos] and list[high] an algorithm that calls itself. p) It’s time to translate our three algorithms into Python. these can be further condensed to a single 104 | Coding Made Simple WorldMags. that’s one of not terribly many reserved words in Python. to that function. but the rewards shall prove worthy of your choose a pivot. the division pivotVal = list[pivotPos] leads to sublists of size 0 or 1. WorldMags. While it’s entirely possible storePos = storePos + 1 to program such a monster. we of the pivot. it would be “Impera et to do this – ideally one would choose a value that is going to divide” because at each stage it does some sneaky end up about halfway in the sorted list. It takes. We have only one loop here. low. and then indent all the code that belongs counting sheep. for a moment. list. you can often get away with on them in isolation. low. a sublist rather than the whole list) and there are That may seem complicated. whereupon the recursion ceases. these are zero and the results in a singleton list. low. because we apply exactly the same pivotPos = choosePivot(list. Watch it Quicksort(list. And Partition(list. middle and final and divided according to a pivot value – all items less than the elements in the list. so length 0 or 1. In practice. In our pseudocode we referred to our list as. This is a particularly tricky storePos = low subject for the novice programmer to get their head around. so we’ll instead use l (for llama). high) methodology to our two smaller lists. though – for example. Swap list[storePos] and list[high] our recursive function calls involve smaller arguments (for Return storePos example. parts. Unfortunately. For each position j from low to high . Selection sort then looks like: def selectionsort(l): for j in range(len(l)): minelt = min(l[j :]) mindex = l. another algorithm. high) Coding it up to left. box function choosePivot(). then. but much of this is cosmetic. we’re doing an inplace sort here – we’ve modified the original list so we don’t need to return anything. which also returns the index stage is called the partition operation. which returns the index of the and all items greater than the pivot are moved to its right. the median of the first. high): pivot. p + 1. besides an unsorted list. There’s no explicit swap operation. low. does the choosing a random value hitherto explored. start the block an alternative to The first thing that the Partition() operation must do is with a def keyword. since These specify the low and high indices between which we halving a list of size n about log-to-the-base-two of n times should sort.index(minelt) if minelt < l[j]: l[mindex] = l[j] l[j] = minelt For simplicity. The if statement is actually superfluous here (we’ve left it in to better match the pseudocode). We use slicing to find the minimum element on or after position j and then use the index() method to find that minimum’s position in the list. there is no straightforward way attention. so at each stage of the recursion we half the list size. # put the pivot at the end of the list Quicksort is. if we start with an already undergoing element to the high element. but this cannot be rearranging and then divides the list into two sublists and acts achieved a priori.) The list is rearranged approach is preferred. then it would harmlessly swap a list item with itself. We’ll leave the pivot-choosing as a black pivot are moved to its left (nearer the beginning of the list). spiralling into the depths of Swap list[j] and list[storePos] oblivion and memory exhaustion. two extra parameters (low and high). but bear in mind all it’s doing so-called base cases where recursion is not used. high): here begins the real fun.

net Coding Made Simple | 105 .net Optional arguments and speed considerations Because our Quicksort() function needs the if high is None: algorithms are possible.shuffle(l) >>> sorting. Of course. l[storePos] = l[storePos]. Smaller elements final swap in the partition() function. which happily sort like quicksort(l. 2. To reload the module and apply the changes. so we don’t need to Python l[high]. 4. l[j] at http:// while k > 0 and l[k . unfortunately. 3. l[high] algorithms can def insertionsort(l): for j in range(low. 0]. we can’t use. or similar. l[k] = l[k]. the standard import statement won’t notice changes on already loaded modules. we need to use the importlib module’s reload() function. the initial call looks high = len(l) their own . Save this file as ~/sorting. for example.1).000 items instantly. For ongoing to find more. l[k . The workaround would be to make the seconds. We’ve used our swapping shortcut quicksort(l. simple and as close to the given pseudocode as an =.1] > l[k]: storePos += 1 sortvis. until the list is sorted. In general. particularly variables. low. Or you can just exit (Ctrl+D) and restart the interpreter. into Python code. 9. p . which took about 14 known for its speed. l[mindex]. So add a print(l) statement at the end of the loop.l[mindex] This means that the whole algorithm is done in four lines. high): be visualised as wave diagrams. We also add k > def quicksort(l. though many of its first part of the function look like: list. high): 0 to the while condition because the loop should stop before if low < high: k gets to file. high): animations. Exact timing depends on the particular when working with lists. 1. 5. Lists in Python have low and high parameters.000 items in about 0. high = None): (much) faster implementations of these through its C API. high) is short for k = k . we translate the pseudocode def partition(l. Python isn’t a language len(l) because we’re not allowed to use internal particularly Insertion Sort. which quicksort(l. possible. so that the pivot are swapped to the beginning of the list one place at a time element is plotted in the correct place. There are many more sorting algorithms. which does not look drastically different. then start the Python 3 interpreter in your home directory. However. for j in range(1. but it’s also worth noting that other functions and modules are implemented def quicksort(l. You should be able to import your module like so: >>> import('sorting') Assuming you didn’t see any error messages or make any typos. add print statements to either the for or while 103 – the pylab.1) from before and in the final line use the -= notation. l[storePos] k -= 1 return storePos We start the outer loop at 1 so that the l[k-1] comparison in the while statement doesn’t break things.draw() function should be called after the loops to see the algorithms progress. Try visualising this using the guide in the box on page Again. low. allow default values for arguments to be Quicksort’s benefits – we discovered that it We’ve tried to use code here that’s at once specified – you simply suffix the argument with could sort 10.1]. We have more fun lessons ahead. Besides Moving on to Insertion Sort. Swapping variables without this neat Pythonic trick would involve setting up a temporary variable to hold one of the values. with the same indentation so it is still within said loop. len(l)): if l[j] <= l[high]: Find out more k=j l[j]. The screenshot on page 103 shows the output for the list [6. l[storePos] = l[storePos].3 seconds. low = 0. low. l[high] = l[high].sort() method. We can see the list becoming sorted from left to right. 8. you can then apply your algorithm to a shuffled list. of course. storePos = low sorting Add this to the sorting. and research is The Quicksort implementation is a bit more involved. Q WorldMags. it’s nice to watch the algorithm progress. Python does You need some reasonably-sized lists to see about 50. len(a) . WorldMags. 7.l[j] = l[j]. We’ll use the random module to shuffle a list from 0 to 9 and test this: >>> import random >>> l = list(range(10)) >>> random. high) beginning of the list. rather than try (and fail) to retreat past the p = partition(l. worry about the first few lines of pseudocode. we’re going to take the bold step of shown you something of sorting as well as increased your just using the first element for the pivot. 0. p + 1. high = whereas the others took much longer.1] l[storePos].1.selectionsort(l) >>> l Voilà – a freshly sorted list. and that the last stage of the loop doesn’t do anything. but hopefully this introduction has the partition operation. l[k .

com/techradarpro IT INSIGHTS FOR BUSINESS THE ULTIMATE DESTINATION FOR BUSINESS TECHNOLOGY ADVICE Up-to-the-minute tech business news In-depth hardware and software reviews Analysis of the key issues affecting your business . WorldMags. .uk THE EASY WAY TO LEARN WINDOWS 100% JARGON FREE AVAILABLE IN STORE AND ONLINE www. WorldMags.

The latter net to your home . The ‘floor’ doesn’t really have any depth. WorldMags.1. and put all the API stuff in ~/picraft/minecraft. such as lines and polygons from dimensions a little later in this chapter. and we Subtleties arise when trying to translate standard will generalise this classic algorithm to three Isometric projection makes concepts. for instance. In order to service these our first task is to copy the provided library so that we don’t mess with the vanilla installation of Minecraft. have to startx. have a decimal part since you’re able to move continuously within AIR blocks. Minecraft requires the X more blocks than you can shake a stick at. so that’s what we’d recommend – your mileage such lacks any kind of life-threatening gameplay. Empty space has the BlockType AIR. and a few steps in the x and z kind of vector graphics: Say. He can move around of this problem occurs whenever you render any inside that block. whereas the y dimension denotes altitude. Minecraft-world fit on this page. On this rather short journey he will be in more than then unless the line is horizontal or vertical. which will change as you navigate the block-tastic environment. The earliest solution to this was contains most of him. provided by Jack Elton Bresenham in 1965. $ cp -r ~/mcpi/api/python/mcpi ~/picraft/minecraft Dude.tar. so is. 108 | Coding Made Simple WorldMags. to draw a line between two points on the screen. where’s my Steve? Here we can see our intrepid character (Steve) Euclidean space into discrete blocks. then. including such delights as GLOWING_OBSIDIAN and TNT. but all that clicking is hard work.gz and by dint of the edition including of an elegant Python API. See how smoothly it runs? Towards the top-left corner you can see your x. a one block at times. but the Minecraft API’s decision has to be made as to which pixels need to getTilePos() function will choose the block which be coloured in. but includes may vary with other distributions. to use the correct parlance) which makes up the landscape is described by integer co-ordinates and a BlockType. generously provided Minecraft: Pi Edition. Your player’s co-ordinates. $ tar -xvzf minecraft-pi-0. kids… actually do try this at home. $ cd mcpi you can bring to fruition blocky versions of your wildest $ . in contrast to those of the blocks. Open LXTerminal and issue the following directives: $ mkdir ~/picraft Don’t try this at Minecraft: Start hacking Use Python on your Pi to merrily meddle with Minecraft. A rguably more fun than the generously provided Assuming you’ve got your Pi up and running. you want directions will take Steve to the shaded blue block. We’ll make a special folder for all our mess called ~/picraft.minecraft. Start LXTerminal and extract and run the This means that there’s plenty of stuff with which to contents of the archive like so: unleash your creativity. y and z co-ordinates.0. and three types of server to be running so if you’re a boot-to-console type you’ll saplings from which said sticks can be harvested. The x and z axes run parallel to the floor. said to be made of tiles. A 2D version inside the block at (0. and as Raspbian. the first step Wolfram Mathematica: Pi Edition is Mojang’s is downloading the latest version from http://pi. The API enables you to connect to a running Minecraft instance and manipulate the player and terrain as befits your megalomaniacal tendencies.0).1. The authors stipulate the use of is a cut-down version of the popular Pocket Edition. Each block (or voxel. and there are about 90 other more tangible substances./minecraft-pi dreams with just a few lines of code. instead.

O’Hanlon’s website www. BlockType of what you’re stood on are displayed as you move We can also get data on what our character is standing about. 2 to grass.getTilePos() great examples of calling getBlock() on our current location should always x = posVec.postToChat(curBlock) but these are only any fun when used in conjunction with the Check out Martin Here. 0) while True: Assuming of course that you didn’t move since inputting the playerTilePos = mc.player.z with the Now without further ado. y .net Coding Made Simple | 109 . dabble with physics. and you can find all we’ll cover a couple of these. Until then.g.1 is rounded down to -2).postToChat(str(x) + ‘ ‘ + str(y) + ‘ ‘ + str(z) + ‘ ‘ + of improbable float to int coercions so we may as well use it. return 0. -1. z + 1.z mc. Go back to your Python session and type: Ctrl+C the Python program to quit. Quick curBlock = mc. Your character’s co-ordinates are available via mc. j. Before we sign off. let’s make our first Minecraftian modifications.player.create() posVec = mc. y – 1. It includes all the terminal and run your program: standard vector operations such as addition and scalar $ python gps. Comparing these with the co-ordinates at the top-left. so in t = mc. and go a bit crazy within the y = playerTilePos. Teleporting is fun! Q WorldMags.z As usual.5.postToChat(str(x)+’ ‘+ str(y) +’ ‘+ str(z)) Behold. We’ll start by running an interactive Python session alongside Minecraft. x + 5) put all your code into a file.setPos() function.y z = posVec. As before start Minecraft and a stuffaboutcode. Create the file ~/picraft/gps. Behold! A 10x5 wall of glowing obsidian has been erected import minecraft.create() obsidian wall like so: oldPos = minecraft.block as block mc = minecraft. z) All manner some ways getTilePos() is superfluous.y confines of our 256x256x256 world. the other block types in the file block.x just what the API is capable of. We subtract 1 from the y set up the mc object: includes some value since we are interested in what’s going on underfoot – posVec = mc.x y = mc. y. type: 0 refers to air. import the Minecraft and block modules. so open another tab in LXTerminal. Do the following in the Python tab: import minecraft. a nice class called Vec3 for dealing with three-dimensional Now fire up Minecraft.getBlock(x. We can also destroy blocks import minecraft. So we can make a tiny tunnel in our mc = minecraft. and com.setBlock(k. enter a in the ~/picraft/ Python session. These co-ordinates refer to the current block that your character multiplication.getTilePos() previous code. rewrite x = playerTilePos. and so have no decimal point. Once you’ve memorized all the BlockTypes (joke).getPos(). The API has str(t)) structures can be yours.Minecraft.block as block by turning them into air.setBlock(x.getBlock(x. 246) with the following code. but it saves three mc. such as our player’s position.player. z = posVec.y something solid or drowning.player.player.Vec3() mc. start Minecraft and enter a world then Alt-Tab back to the terminal and open up Python in the other tab. WorldMags. as well as some other more exotic stuff that The result should be that your co-ordinates and the will help us later on.minecraft as minecraft adjacent to your current location.Minecraft. since otherwise we would be embedded inside y = posVec. but the grown up way to do things is to for k in range(x .1. our location is emblazoned on the screen for a few moments (if not.minecraft as minecraft import minecraft. z + 1. z) We have covered some of the ‘passive’ options of the API. getBlock() returns an integer specifying the block more constructive (or destructive) options. you will see that these are just the result of rounding down those decimals to integers (e. if playerTilePos != oldPos: In the rest of this chapter. 1 to stone. on. running things in the Python interpreter is great for j in range(5): for playing around.x some of the laws thereof. try playing z = playerTilePos. tip mc. you’ve made a mistake). we’ll see how to build and oldPos = playerTilePos destroy some serious structures. which minecraft folder we created earlier. then open up a vectors.getTilePos() x = posVec.

which are selected using the blockData parameter. $ cd ~/mcpi For this tutorial we’re going to use the PIL We’re going to assume you’re using Raspbian. involving importing an image of each wool those giant pixels represented? In this tutorial we hark back colour into Gimp and using the colour picker tool to obtain to those halcyon days from the comfort of Minecraft-world. home directory): your home directory and then copy the api files Install it as follows: $ tar -xvzf ~/minecraft-pi-0.gz you’ll be familiar with the drill. which is old and and that everything is up to date. Remember all those blocky palette. multi. And the Raspberry Pi. but a giant raspberry floating in the sky. Also . For this tutorial we shall use these exclusively. It can import net. WorldMags. for your Minecraft project.png files. Just another day at the office.1. which involves specifying the Red. of coloured wool. The archive on the disk will extract into a your . In order to perform this T echnology has spoiled us with 32-bit colour. Not some sort of bloodshot cloud.gz in the following way: $ sudo apt-get install python-imaging 110 | Coding Made Simple WorldMags.tar. This would be a something called one’s imagination in order to visualise what tedious process. then open a terminal and unzip the file as there. and to copy the API project’s simple requirements. but you could further develop things to use some other blocks to add different colours to your palette. among others. Green and Blue sprites from days of yore. then from a terminal do: minecraft use in your code. colour quantization we first need to define our new restrictive megapixel imagery. Standard setup If you’ve used Minecraft: Pi Edition before All the files will be in a subdirectory called $ tar -xvzf Minecraft: Image wall importing Have you ever wanted to reduce your pictures to 16 colour blocks? You haven’t? Tough – we’re going to tell you how regardless. The process of reducing an image’s palette is an example of quantization – information is removed from the image and it becomes smaller. so there’s follows (assuming you downloaded it to your directory called mcimg. $ .tar.1. but if not this is mcpi. but fortunately someone has done we show you how to import and display graphics using blocks all the hard work already. You can It is a good idea to set up a working directory deprecated but is more than adequate for this download Minecraft from http://pi.minecraft.jpg and . as the component averages. so you can extract it to no need to fiddle around converting images. when one had to invoke components for each of the 16 wool colours. The most colourful blocks in Minecraft are wool (blockType 35): there are 16 different colours available. To run Minecraft you need to have first $ cp -r ~/mcpi/api/python/mcpi ~/mcimg/ how to install Minecraft and copy the API for started X./minecraft-pi (Python Imaging Library).

The provided archive includes the file test. The 46. # Green if width > height: 150.62.221.png") 65. Steve can draw anything he wants (inaccurately).0.56. This taking up all that space. so since we will convert one real consequence (phew). # Blue next codeblock proportionally resizes the image to 64 pixels 79.80. To ensure the aspect ratio is accurate we 107.56.0. # Magenta you are not happy. # Purple stack more than 64 high (perhaps for safety reasons). We make a new and compute the new image size. # Red rwidth = maxsize 25. The palette is given as a list single-pixel dummy image to hold this palette: of RGB values.188.110.22. which is in mcPalette = [ fact the Scratch mascot. Padding out the palette in this pixel to one block our image must be at most 256 pixels in its manner does however have the possibly unwanted side-effect largest dimension.size[0] 208.len(mcPalette) / 3) rwidth = int(rheight / ratio) Unfortunately the “/ 3” is missing from the code at If you have an image that is much longer than it is high.quant}ize.png.221. we will list our mcImagePal.31. # Lime Green width = mcImage. 177.141. # Black rheight = int(rwidth * ratio) ] else: rheight = maxsize"P".22.64. # Cyan As previously mentioned. and blocks cannot be stacked more happens because their value is closer to absolute black (with than 64 high. # Dark Grey ratio = height / float(width) 154. but you are encouraged to replace 221. # Brown in its largest dimension.0) * 256 .22). # White this line with your own images to see how they survive the though it is a mistake without any 256 blocks in each dimension. Coding Made Simple | 111 .0) above to (25.161. You can always TNT the bejesus out of them if 179.137.27. 53.138. so that there this behaviour. with one-line simplicity.52.161.70. However. # Orange {res. but we must first define the palette then the transparent parts will not get drawn.putpalette(mcPalette) colours in order of the blockData parameter. # Pink height = mcImage. To work around this aspect"test. A if it is too tall. We also need to resize our image – Minecraft-world is only http://bit. WorldMags. blocks in Minecraft-world do not With just 16 colours.extend(( of the required 8-bit order. you might not want your image of removing any really black pixels from your image. # Yellow mcImage = Image. which we then pad out with zeroes so that it is mcImagePal = Image. so the provided code resizes your image to 64 which we artificially extended the palette) than the very pixels in the largest dimension. but the resultant image will be missing its top are no longer any absolute blacks to match against.181.size[1] 64. maintaining the original slightly lighter colour of the ‘black’ wool.61. (1.132. For convenience. You can modify the maxsize variable to change you can change the (0. # Light Blue use a float in the division to avoid rounding to an integer.50. reasonable hack if you’re working with a transparent image is The PIL module handles the quantization and resizing to replace this value with your image’s background colour.125. # Light Grey maxsize = 64 46.

expanding on this idea.player. this strawberry/ cacodemon doesn’t spit fireballs at you.k + y. so as a position that befits your intended image. we will position our image close to Steve’s image file and the desired co-ordinates: location.setBlock(j + x + 5.quantize(palette = mcImagePal) this function some arguments too. rheight .rheight)) following could be useful as it enables you to specify the For simplicity.resize((rwidth.player. using the slow but trusty Just replace the mc.z y = into a function. If Steve is close to the positive x edge of the world. Something like the mcImage = mcImage. 1) If your image has an alpha channel then getpixel() will else: return None for the transparent pixels and no block will be mc. A good start is probably to put the mcImage = mcImage. pixel) achieve precisely this. Then it is a simple question of looping over both then you can use live TNT for the red pixels in your image. so to everyone – it is highly unstable and a few careful clicks on the avoid drawing upside-down we subtract the iterating variable TNT blocks will either make some holes in it or reduce it to k from rheight. rheight . This is good. to obtain an index into our palette.getpixel((j. z. x=None.k + y. To change this behaviour one could add an else mcPaletteBlocks[pixel]) clause to draw a default background colour. but you can have a lot of fun by our operations in lexicographical order. z.setBlock line inside the drawing loop getpixel() method.setBlock(j + x + 5.k + y. but we prefer to keep So that covers the code. 46.0) in the top-left corner.convert("RGB") contents of mcimg.k)) horizontal dimension and fix the height at then you may want to use more than 64 pixels in the pixel = mcImage. If you have a slight tendency towards destruction. resize first and the quantization last. then it’s good news.y x = playerPos. You might get better results by doing the $ python mcimg.z is used. Then open a not to confuse the quantize() method with transparency terminal and run: information. playerPos = mc. Image If you don’t like the resulting image. for j in range(rwidth): While Minecraft proper has a whole bunch of colourful for k in range(rheight): blocks. then parts of the image will sadly be lost. You might want to give mcImage = mcImage. z=None): precise. five blocks away and aligned in the x direction to be def drawImage(imgfile.y If no co-ordinates are specified. It depends how red your original image was. including five different types of wooden planks and Unlike in Doom.getPos() Getting Steve’s coordinates is a simple task: x = playerPos. 112 | Coding Made Simple WorldMags. 35. Replacing the if pixel < 16: above block with just the two lines of the else clause would mc. then the player’s position z = .getPos() y = playerPos. To do all the magic. drawn. y=None. co-ordinates start with (0. WorldMags. start Minecraft and move Steve to Now we convert our image to the RGB colourspace. rheight . and then force upon it our woollen palette and $ cd ~/mcimg new dimensions.x playerPos = mc. or if x == None: if he is high on a hill. z. dust. and with the following block: using the setBlocks() function to draw the appropriate if pixel == 14: colour at the appropriate place. dimensions of the new image.setBlock(j + x + 5.x z = playerPos.

Let’s see how fast he runs without those! stairs. WorldMags.(22.0).152.(57. You can see the whole presentation world comprising most of Great Britain. http://bit. Q More dimensions One of the earliest documentations of displaying counterpart has also done similar. palette. z. If you were to proceed custom images in Minecraft:Pi Edition is Dav of Minecraft-Denmark were sabotaged by with this. water will combine to create obsidian.234.61. There are some ] good candidates for augmenting your palette. use the We have hitherto had it easy insofar as the mcPalette following code inside the for loops: index aligned nicely with the coloured wool blockData pixel = mcImage. but Steve can import .81. rheight . O’Hanlon’s excellent 3d modelling project.201. Coding Made Simple | 113 .ly/1lP20E5. To use this in the drawing loop. Incidentally. though: mcPaletteLength = len(mcPalette / 3) then we can structure our lookup table as follows: Blockname Block ID Red Green Blue mcLookup = [] for j in range(16): Gold 41 241 234 81 mcLookup. so you could expand this tutorial in including a blockified Simpsons title sequence each block representing 50m.obj files (text files with vertex. Read all about it at Of course. This is slow and That’s right.25% more colours [gamut out of here .0).setBlock(j + x + 5. go for the ankles. and 16 colours of stained 116.j)) Lapis Lazuli 22 36 61 126 mcLookup += [(41. though parts to jump around on. we also have a temporal rendered. like so: mc. someone (Henry dimensional images are all very well.k)) parameter. tendency to turn into lava/waterfalls. the Pi Edition is a little more restrictive.244. a ly/1sutoOS . To this end and texture data) and display them in Minecraft: and has written Redstone – a Clojure interface the aforementioned Ordnance Survey team has Pi Edition. Another fine example is Martin everything pretty small – the drawing process Survey maps. face Garden) has already taken things way too far has a whole other axis to play with.0). bData) mcPalette = [ … In this manner you could add any blocks you like to your 241. Two. so we need a lookup table to do bType = mcLookup[pixel][0] the conversion. Its Danish that direction. giving Steve some animated gifs at http://bit.0)] Sandstone 24 209 201 152 Thus the list mcLookup comprises the blockType and Ice 79 118 165 244 blockData for each colour in our palette. emerald. to Minecraft which enables movies to be provided. Steve. And we now have Diamond 57 116 217 212 a phenomenal 31.126. but be careful with the lava and water ones: their 36. for the full version of Minecraft. Naturally.Ed] with which to play.getpixel((j. Now that we’re incorporating different blockTypes if pixel < mcPaletteLength: things are more complicated. six kinds of stone. Assuming we just tack these colours on to the bData = mcLookup[pixel][1] end of our existing mcPalette definition.k + y. Cold.217. hard obsidian. lava and 118.0). pleasing orange and blue hues belie an inconvenient 209.165.(24. then you’d probably have to make Stott’s excellent tutorial on displaying Ordnance miscreants.append((35.212 glass.(79. WorldMags. with dimension.

it’s perfect material for the next tip instalment in our Minecraft:Pi Edition series. Granted.3] insert random 2 or 4 tile if no move can be done: game over Our task now is to flesh out the English bits of the above code. always just beyond reach. Now we know what we’re dealing with. so our array tiles is comprised entirely of (small) integers. so we can use the exponent rather than the actual value here – for example. but flying around – but don’t worry. So dutifully read the rules in the box – they might text adventure by seem clumsily worded or overly complex. numbering the rows from top-to-bottom and the columns from left-to-right. You’d want to reset the pseudocode – this way we can see the shape of the program player’s position without getting bogged down in details. WorldMags. like so many hopeless lovers. for each row: like a cheat for Sonic the Hedgehog… 114 | Coding Made Simple WorldMags. The first co-ordinate will be the row number. much of the pleasure comes from the touch interface: there is an innate pleasure in orchestrating an elegant and board- clearing sequence of cascades with just a few well-executed swipes. We can represent empty tiles using 0. Python uses 0-based lists. Non-empty tiles will all be powers of Build 2048 in Minecraft We show you how to implement a crude 2048 clone in Minecraft. column] for x in column + 1 to 2: tile[row][x] = tile[row. for column 0 to 2: if tile[row. 32 will be represented by 5. for each row: but in principle move tiles left. the game has simple rules and is Quick based on blocks. but to do this we need to state how we’re going to represent the board and tiles. you’ll get a taste of the thrilling addition Minecraft functions to talk to those to do with the board and of successive powers of two and as an addict. We’ve gone for an object-oriented Y ou may have not encountered the opium-like approach here. Sometimes it’s easier to visualise the situation using player moves. Lovely. clearing empty space it’s quite a simple You even get a handy help command. You could make The first challenge is to understand the algorithm underlying this project a bit less of a Zork-esque the game.column + 1] = tile[row. This will be done using a 4x4 array called tiles. and the second the column number. you’ll be powerless to abandon the pursuit of the cherished 2048 tile. x + 1] empty tile[row. We’ll worry about how to draw and move the blocks later. but it kind of looks modification. which means that there will be a lot of self moreishness of the Android/iOS game 2048. so tiles[0][0] will be the the top- left hand tile. As such. Be that as it may. we can set about doing some actual Python. after each move. but rest assured writing a control they have been carefully crafted for easy translation to system based on .column]: double tile[row. it makes it easier for the once you do.

tiles[row][j] == 0 and not row_empty: The 2048 game was written by young for k in range(j. accruing else: over 4 million downloads within a week j += 1 of its release in The fruits of his isMove = True labour proved hugely popular.boardSize): Veewo Studio’s 1024 and conceptually for column in range(self.myfavouritemagazines. but even if The board is there’s only a single space (which will get filled by a new tile) updated twice for there still may be possible moves.tiles[j][k + 1]: com/files/ later with a very cunning trick.append([j. Let’s look at line 2 of our self.game_over = False value blocks justice: eg 128 is represented by black.boardSize): step animation by for k in range(self.randint(1. functions from the random module to help decide the where before and after and what is of the new tile.tiles[k + 1][j]: # check rest of row non-empty self. WorldMags.[row][k] != 0: row_empty = False 2048: An Open Source Odyssey if self. isMove = False # check col neighbours com/5zEZUfBS for row in range(self. since it was self.linuxformat.1): www.000 the pseudocode. Rather if self.boardSize .boardSize): if self.tiles[j][k] == self.2) the command interpreter. if len(empties) > 1: The standard wool colour numbers don’t really do high self. you empties = [] could use this to Things turn out to be simpler if we split off the third pseudocode block into its own function.drawBoard() any available empty tiles. def newTile(self): If you were feeling adventurous. Cirulli’s \ blog says he “didn’t feel good about and self.choice(empties) rnd_n = random. we can cater for them if self. and we also # check row neighbours need to keep track of whether we actually moved anything for j in range(self.boardSize): spacing out the tiles somehow.tiles[j][k] == 0: We were not feeling empties.tiles[row][self.game_over = True implement a two for j in range(self.tiles[row][column] != 0: keeping [the code] private.tiles[row][k + 1] who wanted to see if he could write a self. if self.1): Italian programmer Gabriele Cirulli.tiles[row][k + 1] spirit of open source. this spurred all self.1): while j < self. self.1: if self.boardSize .zip def leftMove(self): or over at: http://pastebin. return isMove For more great magazines head to www.self.self. self. Python does have a remove() The drawBoard() function is what will actually place the method for lists.tiles[row][column] == self. the same.boardSize . WorldMags. Numbers soared after mobile versions were released the Now we can deal with the situation in the second block in following May. We first Quick need a list of co-ordinates of all the empty tiles. possible after the tile is added is a little awkward: code! We don’t waste time fiddling with empty rows. finding two horizontally-adjacent tiles are simultaneous players at its peak. The game is described as a clone of for row in range(self.boardSize): j=0 for k in range(self. Honest. occupying self. blocks in Minecraft world.boardSize .tiles[rnd_pos[0]][rnd_pos[1]] = rnd_n pseudocode.game_over = False row_empty = True for k in range([row][column] += 1 heavily based off someone else’s work. any tile merging.tiles[row][column + 1] than profit from his success. with up to 50.game_over = False mine2048.” for k in range(column + 1.boardSize): You can find the code at http:// (through the boolean isMove).1] = 0 kinds of modifications and further isMove = True depleted global productivity.boardSize): for j in range(self.tiles[row][self. newTile(). In the self.1): Thus it is available to all at his GitHub http://bit. Checking whether moves are Get the so we’ll clear the zeroes from our row the old-fashioned way. We use a couple of a successful move.1] = 0 game in a weekend.tiles[row][k] = self. if there’s tip more than one then it’s certainly not Game Over. in which we move tiles in the row left.boardSize .tiles[k][j] == self. three other possible moves for Coding Made Simple | 115 .boardSize . but it only works on one element at a time.1): similar to the indie title Threes!.k]) adventurous. rnd_pos = random.boardSize .boardSize .tiles[row][k]= self. Also don’t worry about the for k in range(self.

applies with strategic substitution of row with populated. If it is all over. Starting with the tile on the is possible after this then it’s Game Over. the Python API from your Minecraft install (e. If there is still need specifics and exactitude. the same algorithm on it at random locations. for example left. which in turn will add a new tile and the player’s position. and all tiles column and right with left.g. A vague idea won’t cut it: we by moving all the numbered tiles left so that any second. if the tile to its right has the same value For other directions. The do_left() function will check if the left move is . Now we space then another 2 or 4 tile is added randomly semblance of frustrating. You may have seen this already in if if __name__ == “__main__”: you’ve ever made a Minecraft cannon and used cmd to command2048(). and sometimes Steve’s temper gets the better of him Amazingly. fait with all file from the download. When you enter a command. including setting up the mc object and using it to get updateBoard() function. Any class you write that instantiates this will inherit all Master and commander of its functionality. Initially two tiles are then the left-most of the pair will double in value. The command2048 class’s __init__() method sets up the and if so update the board. shifting the tiles up. free of any empty tiles are on the right of the row. into errors. Also you’ll need to make sure you’ve copied the page 114). This provides a reference point for Rules of the game A key tenet of programming anything is knowing moves. We start the tiles will change. third and fourth rows. We use the standard boilerplate to start We’ll use the cmd module to provide a simple command line things up when the program is executed: interface to our game. then the this process for the second and third tiles from program should behave in a given set of following algorithm applies: For every row start the left. This function is really part of our But if you’ve been following our Minecraft series you’ll be au board class. We even get a help command for free (see picture. This will instantiate our command interpreter when the We shall have a command for initialising the board. Ctrl-D. then we still need a means by which to input our moves. left or right. down. If no move consider how the game of 2048 works. and of course cheekily use raw_input() as a means to wait for the user to we need to render the results in Minecraft world. press Return.cmdloop() control it (You could always try making an image wall. let’s will look at each tile’s situation and decide how in one of the available empty spaces. Repeat what the rules are – knowing exactly how your Suppose the player chooses left. The player can make one of four the rightmost of the pair will vanish. that’s the guts of the code all dealt with. but we decide whether or not the game is up. hence we have a function do_left() which calls the same directory as the mine2048. four program is run with: directional commands and a command to quit. leftMove() function above. Repeat the whole process for the circumstances. The cmd module works by subclassing its Cmd class. with a 4x4 grid which has some 2s and some 4s end of file (EOF) character or the quick way to end a Python Minecraft must be running when you do this. aka the $ python mine2048. ~/mcpi/api/ cmd module will run the function with that name prefixed by python/mcpi) to a subdirectory called minecraft in the do_. via the imaginatively-titled basics. or you’ll run session. It can be WorldMags. p110). With that in mind. to the right will move one position left. up or down. 116 | Coding Made Simple WorldMags.

leftMove() We display only the exponents since (a) we’re lazy and (b) it self. once you figure out how to make a structural copy of Spotting wee tricks like this is great because they don’t our two-dimensional list: only make your program smaller (our provided code is def revTiles(self): about 160 lines long.transposeTiles() is exactly the same as reversing the rows.board. for def transposeTiles(self): example making fancy glowing obsidian blocks for the higher oldTiles = [j[:] for j in self. They also make it much for j in range(self. self.boardSize): the Up move by transposing our tiles array (replacing each for k in range( so not having another three very similar self. self. WorldMags. but feel free to add to it. self.z.board. self.board. The leftMove() function is by far the most for k in range(self.tiles[j][k] = oldTiles[j][self.revTiles() Coding Made Simple | 117 . move = self. if move: Change it if you like. moving the tiles to Note that this is the same as transposition.tiles] can sap hours from your life). and plus and minus signs. we also have a printTiles() self. an elephant in the room.board.board.boardSize . Note that our row[0] is the top one. and then reversing the rows again. But that would be silly.tiles[j][k] = oldTiles[k][j] The only way is Left Similarly we can complete our directional command set.leftMove() inefficiency here at Future Towers.board.revTiles() function which draws the board at the command terminal. Q You can change the boardSize variable. going self. right move the left. as everything will be def do_right(self. Make sure you’re not looking So then we can make implement the (ahem) right move. then performing our self.x + k. left move. 35.boardSize): self. observe that moving the tiles to the right self. We still haven’t dealt with making the Down move by a combination of transposition.boardSize): down. subtracting j from our y co-ordinate.y .boardSize): easier to debug.revTiles() looks nicer if most things occupy just a single character.k .setBlock(self.revTiles() up approach. First. which we will arbitrarily decide to be three blocks away in the z direction.transposeTiles() through all the incorrect combinations until we find one that self. But wait.args): backwards. Let us take a more grown. for k in range(self.1] functions is a considerable benefit. and we don’t tolerate such move = self.boardSize): row by its respective column). WorldMags. so we count for j in range(self. We could do this by row reversal. Reversing the rows and transposition. Transposition is tiles[j][k]) almost exactly as easy as row-reversal: This works reasonably.tiles] valued ones.board. self. For convenience.j. but it’s a bit of a different game in a larger drawing our board. leftMove() and transposing back again. We can construct for j in range(self. not bad for a whole mini-game that oldTiles = [j[:] for j in self.updateBoard() The drawBoard function uses different colours of wool else: (blockType 35) to represent the content of our array tiles: print “No move” def drawBoard(self): But the symmetry does not stop there. in the following way: at the back of the board. 75% of the moves allowed in 2048. is easy. row reversal and transposition: copying the leftMove() function and painstakingly changing def do_down(self.board.args): all the ranges and indices. though.boardSize): complicated.

Coding projects
Exciting and interesting coding
projects for you to write
Python 3.0 primer ..................................................120
Build a Gimp plug-in .........................................124
Image filters .............................................................................128
Sound filters ............................................................................134
Twitter scanner .............................................................138
Build a GUI 142
................................................................................... Coding Made Simple | 119
Python: Dive
into version 3.0
Join us as we investigate what is probably one of the least loved and
disregarded sequels in the whole history of programming languages.

Linux Format, certain authors, whether by habit, ignorance or
affection for the past, continue to provide code that is entirely
incompatible with Python 3. We won't do that in this article.
We promise.
So let's start with what might have been your first ever
Python program:
print 'Hello world'
Guess what – it doesn't work in Python 3 (didn't you just
promise...?). The reason it doesn't work is that print in Python
2 was a statement, while in Python 3 print is a function, and
functions are, without exception, called with brackets.
Remember that functions don't need to return anything
(those that don't are called void functions), so print is now a
void function which, in its simplest form, takes a string as
input, displays that string as text to stdout, and returns
nothing. In a sense, you can pretend print is a function in
Python 2, since you can call it with brackets, but a decision
was made to offer its own special syntax and a bracketless
shorthand. This is rather like the honour one receives in
mathematics when something named after its creator is no
longer capitalised – for example, abelian groups. But these
kind of exceptions are not a part of the Python canon
("Special cases aren't special enough to break the rules"), so
it’s brackets all the way. On a deeper level, having a function-
proper print does allow more flexibility for programmers – as
ay back in December 2008, Python 3.0 (also a built-in function, it can be replaced, which might be useful if

W known as Py3k or Python 3000) was released. Yet
here we are, seven years later, and most people
are still not using it. For the most part, this isn't because
you're into defying convention or making some kind of
Unicode-detecting/defying wrapper function. Your first
Python program should have been:
Python programmers and distribution maintainers are a
bunch of laggards, and the situation is very different from, for
example, people's failure/refusal to upgrade (destroy?)
Windows XP machines. For one thing, Python 2.7, while
certainly the end of the 2.x line, is still regularly maintained,
and probably will continue to be until 2020. Furthermore,
because many of the major Python projects (also many,
many minor ones) haven't been given the 3 treatment,
anyone relying on them is forced to stick with 2.7.
Early on, a couple of big projects – NumPy and
Django – did make the shift, and the hope was that
other projects would follow suit, leading to an
avalanche effect. Unfortunately, this didn't happen
and most Python code you find out there will fail
under Python 3. With a few exceptions, Python 2.7 is
forwards-compatible with 3.x, so in many cases it's
possible to come up with code that will work in both, but The Greek kryptos graphia, which translates as ‘hidden
still programmers stick to the old ways. Indeed, even in writing’, followed by a new line using the correct script.

120 | Coding Made Simple

this will require many UTF-16. Now when you try to print the lowercase character pi. via a system called Punycode. ligature Some of these characters are invisible teletype the problem elsewhere. Instead. Revolution box. forms and more. WorldMags. then plain ASCII wouldn't help. accounts for as many as possible of the set of backwards compatible with ASCII). which just 03c0 in hex notation. even those The PyStone benchmark will likely be slower in Python 3. slicing or reversing a string. To understand them. other languages. This accounts for over 100. it’s fairly common in answer: Unicode. both as a storage used character set (and the related (hence the divergence of codepoints and byte encoding standard and for internally processing Windows-1252) contains almost all the accents encodings). but there are many other. In the past. but it can live happily sharing it with could do the same. by default. end=" ") print ('one line') does just that. above) that covers all the Coding Made Simple | 121 .000 which gives you 128 characters to play with. Don’t be a Py3k refusenik without first trying your code. although internally these are >>> type(pi) all still encoded as ASCII. Most of the world doesn't speak English. distro. As a result. more than 256 characters. Print in Python 3 A significant proportion of Python programs could be made compatible with 3 just by changing the print syntax. but the same won’t regions that do tend to use different sets of accents to be true for all code. all the wrangling. Obviously. sometimes identically. but doesn't really solve characters. which uses two bytes for some emerged. This widely. You could use one of the The unicode type should be used for textual intercourse – to use Python 3 alternative encodings. most of the world doesn't even use a Latin character set. but in general you needed the Unicode codepoint for the lowercase Greek letter pi is in tandem with to turn to a word processor with a particular font. sometimes called Latin-1. we use the end parameter. bidirectional display order. Currently there are two codes (ASCII originated in the 1960s). things will go wrong. but it's for a greater good. are converted to whichever encodings have emerged. then sad news: this no longer works. of few distributions The Unicode revolution Traditionally. away with one character encoding to one byte has been widely adopted. For example. For any modern tip assigned a byte encoding. The most notorious of these is ISO. things that could go wrong. In fact. if we were to try this on a terminal without modules still won't play nicely with it. which uses one byte for we've counted the familiar alphanumeric encoding (or maybe a couple of them) that common characters (making it entirely characters. and 256-character extensions of the ASCII encoding wish to type. tabulating and its predecessor did not do the latter. as well Fortunately. there isn't really much room left. and we have an each character is encoded as a 7-bit codepoint. We can even have ϖ Unicode in our domain names. but will behave a scenario by starting Python with: unpredictably for codepoints above 127) or they can be of $ LC_ALL=C python type unicode. in which as the characters used in the romanisation of other rigmarole has been done. Thankfully. tests. You can simulate such be of type str (which handles ASCII fine. if you knew the people you were finding the length of. text was encoded in ASCII. As a result. Strings in Python 2 can Unicode support. but its >>> len(pi) handling of it is done fairly superficially (Unicode strings are 1 sneakily re-encoded behind the scenes) and some third-party However. besides the ASCII standard. we now have a the Python console like so. we must first be au fait with what really changed in Python 3. Unicode 8859-1. which by default is a new line. and each codepoint is and LC_* environment variables in Linux). so we'll have to do characters and four bytes for others. far less trivial. So we can define a unicode string from its predecessor moves the problem elsewhere. and up to Because we like things to be bytes. If you were a fan of using a comma at the end of your print statements (to suppress the newline character). several characters anyone on earth might conceivably four bytes for the more cosmopolitan ones. but it's definitely not something Arch Linux is one if you wanted to share a document with foreign characters in you should take for granted. the western hemisphere. this is probably UTF-8. Strings of type str are stored as bytes and. and once The correct solution would be a standard encodings in use: UTF-8. provided our terminal can handle (available in the widely adopted standard: Unicode (see The Unicode Unicode output and is using a suitable font: python2 package). decorate the characters. For example: print ('All on'. and is >>> pi = u'\u03c0' backwards compatible with ASCII and (as far as codepoints >>> print(pi) are concerned) its Latin-1 extension. <type 'unicode'> Python 2 is far from devoid of Unicode support. Each grapheme (an abstraction of encoding your system's locale specified (through the LANG Quick a character) is assigned a codepoint. The main raison d’être of Python 3 is that required for the Latin-scripted languages. you will WorldMags. numerous diverse and incompatible character when printed to a terminal. print ('Hello world') which is perfectly compatible with Python 2 and 3.

Python 3. We can escape type entirely. If you're reading Unicode text files. you can no longer use the ugly <> comparison operator to test for inequality – instead use the much more stylish != which is also available in Python 2. Python 3 does away with the old unicode encodes to the two bytes CF 80 in UTF-8. UTF-8 byte representation directly. but it really depends but it will suffice to simply accept that the pi character on your purposes. which could result in need to rewrite from the ground up how the language dealt tears.coding: utf-8 -*- will try and convert strings of type unicode to ASCII (its The main driving force for a new Python version was the default encoding) in these situations.0). the 2to3 tool. Shalom aleikhem. The third line uses the explicit floor arguments is a float (or complex). the numerator is a float and are ints. when printing to a file or a pipe. 1. Also. So we can also get a funky pi character by using its with strings and their representations to simplify this process. and returning an int. 1.7. at http://bit. There are rules for Some argue that it fails miserably (see Armin Ronacher's rant converting Unicode codepoints to UTF-8 (or UTF-16) bytes. brings about many other changes besides all this Unicode some of them provide new features. This helpful chap runs a predefined set of fixers The division bell One change in Python 3 that has the potential to two ints. For example. here's an second example. if you have Unicode strings in corresponding to how the string is encoded on the machine.coding decorator above) and the new bytes >>> type(strpi) object stores byte arrays. doesn't need to be compatible with 2. but this is trivial via the str. This means the / operator is now as close to >>> 3. then the >>> 3. In the changed: if both numerator and denominator operator / is different. but the longer cause harm. bottom p120). otherwise a float is returned with the >>> 3/2 returning what you'd intuitively expect half of correct decimal remainder. Python 2 # -*. But wait. run into a UnicodeEncodeError. The str type now stores Unicode understand bytes: codepoints. 122 | Coding Made Simple . your code. functions can now be passed keyword-only arguments. The latter mathematical division proper as we can hope. you'll need to add the appropriate declaration at This is what you should use if you're writing your strings to the top of your code: disk or sending them over a network or to a pipe. Python is trying So ϖ apparently now has two letters.encode() 2 method. other. thus in this case behaviour of the classic division operator has flummox is that the behaviour of the division the operator stands for integer division. Automating conversion with 2to3 For reasonably small projects. the language's default encoding is UTF-8 (so no >>> strpi = '\xCF\x80' need for the -*.7. it’s likely that your Python Aleph. and use the codecs module to change The str type in Python 2 is really just a list of bytes encodings as required. then an int is returned if one divides the excerpt from a Python 2 session the operator acts as floating point division. some of these are just the removal of legacy compatibility code (Python 3. there's more: for example. unlike 2. and unicode types. you'll supported by the primitive C locale).0 operator was actually backported to 2. like the old str type. The point is: if your and failing to coerce this to an ASCII character (the only type Python 2 code is doing stuff with Unicode characters. WorldMags. you'll need to open them in binary 'rb' mode and convert the bytes to a string using the converse bytes./2 division operator // which will return the behaviour is unchanged.5 rounded-down result as a float or an int. The new str <type 'str'> type will need to be converted to bytes if it's to be used for >>> len(strpi) any kind of file I/O. beth.decode() method (see the picture for details. even if they use the *args syntax to take variable length argument lists. since everything about Python 3 is now these with an \x notation in order to make Python Unicode-orientated.//2 depending on the arguments. Also. so its and issues involving unexpected ints will no which shows the first command operating on behaviour is the same in Python 3. and catching exceptions via a variable now requires the as keyword. Essentially. gimel… The 2to3 program shows us how to refactor our Python 2 2 code can be automatically made Python 3 compatible using code for Python 3. instead use str. If at least one of the 1 three to be. and some of them force programmers to do things differently. and those that aren't going to encounter any foreign characters. so don't use the unicode type You'll also have to handle your own conversions between str for these operations. Python 2 also tries to need to have all kinds of wrappers and checks in place to take perform this coercion (regardless of current locale settings) account of the localisation of whatever machine may run it.

There You can also use the -w option to overwrite your file – don't is another module. using the -f option. says that Python For example. is a version 3. An example is When Python 3. which you can verify the unichr() function is now chr(). This was not These two aren't entirely compatible. or the bottleneck features and syntaxes have already been backported to Coding Made Simple | 123 . and __future__ doesn't your fingers to add parentheses. module. Using it can be as simple as directive. with the goal of emitting bona fide behave like a standard module – instead it acts as a compiler Python 3 code. and the print line is reworked. because Unicode is now for yourself using the PyStone benchmark. It’s target one specific Python version. Q WorldMags. it drudgerous The popular matplotlib module has been Python 3 compatible since v1. because searching and in order to clean up the code base. But Another option is to create 'bilingual' code that is compatible don't be misled. machine in the office. for all your graphing and plotting requirements.3GHz processor would suggest. p122) shows the changes to a simple three-line program – Unfortunately. implicit. PyStone tests various Python internals. on would be nice if performance had since been improved. WorldMags.5 (which was released in September 2015). Using 2to3 can version and many special-case optimisations were removed save you a whole heap of effort. which isn't part worry. array access).7 will be supported until 2020. so you won't be to speed up code that is amenable to new features and learning the new syntax. math. but that's no excuse to using the following: postpone learning the new version now. or unicode_literals to make strings Unicode by default. $ 2to3 mypy2code. this hasn’t been the case. this middle ground is very important to test your code in both versions to get a more useful when you're porting and testing your code. You might accurate picture. because speed was not really a priority for the new be necessary in order to successfully migrate. Many Python 3 C translation (loops. the author of Python. on your Python 2 code. so some tweaking might surprising. Guido van Rossum. and many more can be enabled using the __future__ module. even if it uses % to We tested it (see the screenshot on p121) on an aging format We can likewise import division to get the new style division. confusingly called future. which in this case provides the modern print syntax. for instance. you can get the new-fangled print syntax by 2. Now that we're up to replacing print statements manually. it was generally regarded buffer which will replace all buffer types with memoryviews.0 was released.2. but can help ease transition issues. You can always use Cython (maintained at need to rework a few things in Python 2 while still enjoying the http://cython. The pictured example (over on the left. which will output a diff of any changes against the original file. which has now come back from the dead twice and hence possesses supernatural powers far Parlez-vous Python Trois? beyond its dusty 2. specify them explicitly. While you should really only which your code may or may not make extensive use. Half the work is retraining This is used with the from in this way. as being about 10% slower than its predecessor. of with both Python 2 and Python 3.7. Some fixers will only run if you of the standard library. Python 3 adoption is >>> from __future__ import print_function increasing. it will be backed up first.

'Layer0'. If type data. Note that in Python.RGB. ultitude of innuendoes aside. it is there.0) On Linux. since an image without layers is a pretty ineffable object.gimp_context_set_brush('Cell 01') 124 | Coding Made Simple WorldMags. Scheme). then we provide a list of the form [x1. though frankly adjusting colours. though.8. languages.gimp_image_insert_layer(image. height and menu. the hyphens in procedure names are replaced by underscores. gimp_pencil(). Hence our example draws a line from (80. xn. You can look up more information about these procedures in the Procedure Browser – try typing gimp-layer-new into the search box. If it’s not there. which and Mac friends will have these included as standard since requires parameters specifying width. GRAY or INDEXED).gimp_pencil(layer. then go ahead and click on it. there exist them in Python through the pdb object. gimp_layer_new(). You can check everything is ready by starting up (RGB. which works Gimp and checking for the Python-Fu entry in the Filters on a previously defined image and requires width. which is twice the number of points because each point has an x and a y component.gimp_layer_new(image. Then throw the following at the console: pdb. a nicely centred line. The Browse button in the console window will let you see all of these procedures. Mercifully.240. layer = pdb. as well as a .[80.None. Perl or Python.200. takes just the layer you want to draw on. which is probably most accessible of all these then displaying the image. and gimp_display_new(). If you wanted to be hardcore. what they operate on and what they spit out. most packages will ensure that all the required pdb.gimp_display_new(image) Python gubbins get installed alongside Gimp.layer. brushes and so forth are in the PDB too: doing this is unlikely to produce anything particularly useful. you’ll need to check your installation.100. which will display an image. and you will see all the different combine modes available. The syntax specifying the points is a little strange: first we specify the number of coordinates. your Windows So we have used four procedures: gimp_image_new(). so even if you have no prior coding experience you image = pdb. adding a layer to it. and last in this list.100 . since hyphens are reserved for subtraction.200. just like you could draw with the pencil tool. Gimp enables you to can do is registered in something called the Procedure M extend its functionality by writing your own plugins. y1. then you would write the plugins in C using the libgimp libraries. opacity and combine mode. Everything that Gimp You need to add layers to your image before you can do anything of note.4. without even a word about Gimp masks. First select a brush and a foreground colour that will look nice on your background. Tcl. let’s see how to make a simple of your dreams in Gimp’s own Script-Fu language (based on blank image with the currently selected background colour. yn]. with a image.RGB) should still get something out of it. WorldMags. prompt (>>>) hungry for your input. …. The procedures for selecting and You can customise lines and splodges to your heart’s content.gimp_image_new(320. softcore APIs to libgimp so you can instead code the plugin As a gentle introduction.RGB_IMAGE) Get started pdb.100]) Great.320. This tutorial will deal with the This involves setting up an image. pdb. The first parameter. If all goes to plan this gimp_image_insert_layer() to actually add the layer to the should open up an expectant-looking console window.100) to (240. We can access every single one of pretty off-putting or rage-inducing.100). but how do we actually draw something? Let’s start with a simple line. height and image type version 2. Draw the line All well and good. The search box will still understand you if you use underscores Python: Code a Gimp plugin Use Python to add some extra features to the favourite open source image- manipulation app. but that can be Database (PDB).

and hue suited to these fancy brushes than the hard-edged pencil. For simplicity. the highlights. reminiscent of lens flare. a more pleasing result may caused by light sources outside of the depth of field. ‘Bokeh’ derives from a Japanese word meaning blur layer remains untouched beneath these two. we have just used the defaults/current settings here.gimp_context_set_foreground('#00a000') in the highlights of the image. The bokeh plugin pdb.gimp_context_set_brush_size(128) effect you get in each case is a characteristic of the lens and has created pdb. one may also see a pleasing If you have the brush called ‘Cell 01’ available. If you don’t. blur radius. WorldMags. and in photography refers to the out-of-focus effects opacities of these two new layers. Download the code pack from ‘bokeh discs’ and another with http://bit.100]) the aperture – depending on design.2. and saturation Applying our pdb. and a advanced plugin for creating bokeh effects in your own layer with a blurred copy of the original image. then the polygonal and doughnut-shaped bokeh effects. It often be achieved. By adjusting the or haze. which we will assume to be single- gimp_brushes_get_list(‘’). a path on their image. you will see that you can configure “Our plugin creates a layer with gradients and fades and you will find a file linesplodge. a part of the results in uniformly coloured. we’ll stick with just circular ones. disc-shaped artefacts image should remain in focus and be free of discs. For this bokeh effect in above code will draw a green splodge in the middle of your exercise. so it may WorldMags. a blurred copy of the image” py which will register this a fully-fledged Gimp plugin. The paintbrush tool is more layered. replete with a few tweaks. blurred. They will specify disc diameter. then you’ll get an error message.[160. For more realistic bokeh effects. The original pictures. You can Our plugin will have the user pinpoint light sources using get a list of all the brushes available to you by calling pdb. canvas. and if you look in the procedure browser at the function gimp_paintbrush.gimp_paintbrush_default(layer. The result will be two new layers: For the rest of the tutorial we will describe a slightly more a transparent top layer containing the ‘bokeh discs’.net Coding Made Simple | 125 .

x1. It is recommended to turn the blur parameter to zero a number of options. This means Having extracted the point . height. 4. Here the second argument stands for the Here are our discs. they are quite handy strokes. The length of the list of points is our script in Gimp. "bokeh".radius. blur_layer. Provided the drawn. None.y0.y and select the average colour. in fact. Layers and channels Python lists start at 0.gimp_image_insert_layer(timg.. then further applications of our as two variables x and y. since it may not be indicative of its surroundings.gimp.gimp_image_insert_layer(timg. but don’t worry – all you need to understand is that modes and other arcana. Details are in the box There are a few constants that refer to various Gimp-specific below. which would rely on more home-brewed RGBA_IMAGE. 5. each describing a section of the path. so that we get require at least an image and a layer to work on. extracting the coordinates of each component point user doesn’t rename layers. 0) our circle by bucket filling a circular selection. They are easily identified by their the main for loop will proceed along the path in the order shouty case. This is slightly non-trivial since a pdb. disc. we use the range() function’s step parameter to things to have around because so many tools We’ll assume a simple path without any curves. 0) we start – somewhat counter-intuitively – by drawing a black For many. Rather than use the paintbrush tool. The PDB function parameters and still have all the flare-effect discs on the same for doing just that is called gimp_image_pick_color().y0. As you can be fruitful to erase parts of the blurred layer. For our blur layer. so there is only a single stroke from which to the xs in positions 0.x1. tip pdb. The bokeh layer is created much as in the previous example.x0. It has layer. 8 and the ys in positions So handy.gimp_layer_new(timg.y1. diameter) and changes of direction and allsorts. After initialising a few de rigueur variables. bokeh_layer. x . our next challenge that one can apply the function many times with different is to get the local colour of the image there. Since for j in range(0. Bring a bucket Quick blur_layer = pdb.. None.. we don’t need to mention this stroke as gpoints. CHANNEL_OP_ general path could be quite a complicated object. 100.4): them to your function. the object contains a series of hold curvature information.layers[0]. strokes.1) To draw our appropriately-coloured disc on the bokeh layer. but uniform colour works just fine. Our particular call has the program sample within blurring the already blurred layer. Paths. mirroring the dialog for the Colour after the first iteration. with curves REPLACE. width. original image and add a transparency channel. NORMAL_MODE) all possible users having consistent brush sets. If you’re feeling crazy you could add blends or gradients.gpoints[1]. In the code we refer to 1. a 10-pixel radius of the point x. because in other settings the list needs to and drawable) at the time our function was More specifically. twice. since otherwise the user would just be Picker tool. points. This list takes the form variables timg and tdraw. plugin will not burden them with further layers.gimp_layer_copy(timg. Each point is counted active image and layer (more correctly image much that can be applied equally well to both. the list of points is You will see a number of references to make up the class called drawables – the accessed as gpoints[2].]. WorldMags. many bokeh_layer = pdb. we copy our pixel. we set about This is preferable to just selecting the colour at that single making our two new layers. images and drawables Paths are stored in an object called vectors. 9. To avoid repetition.y1. which is really a tuple bequeathed to us in the second entry of gpoints them – it is assumed that you want to pass that has a list of points as its third entry.radius. vectors. we will make plugins.gimp_image_select_ellipse(timg. check out pdb. diameter. from the user’s chosen path. 126 | Coding Made Simple WorldMags. that when we come to register wrest our coveted points. y . These represent the abstraction is warranted here since there is [x0. The selection is the Gimp Plugin Our script’s next task of note is to extract a list of points achieved like so: Registry at http:// registry. increment by 4 on each iteration.

gimp_context_set_foreground(color) After we apply pdb. copyright. blur.gimp_layer_set_mode(bokeh_layer.8/ proc_name.” Coding Made Simple | 127 . true for any Gimp script. The menupath parameter specifies function as it appears in the code.False. date.g. such as in our example. The your plugin will be called in the PDB.0. Q Registering your plugin In order to have your plugin appear in the Gimp params. on some level at least. lightness. The dimensions are specified by giving the top left corner of the box that encloses the ellipse and the said box’s width.0.100. And just in case any black into a single undoable one.plug_in_gauss_iir2(timg. so we black it up first. GRAY*”. blur_layer. and survived the bucket fill. But pdb. WorldMags. #! /usr/bin/env python Python plugins have their own branch in the Finally. softly Finally we apply our hue and lightness adjustments. pdb. 0. since You could add any further scripts you come up with to this otherwise we would just blur our most-recently drawn disc.100.plug_in_colortoalpha(timg. save this file as (say) register( case “<Image>/Filters/Artistic/LineSplodge. image. author.“Draws a line and a splodge” of images the plugin works on. group the operations the bokeh layer to Soft-Light mode. results. we set its menupath to opacity of the that part of the image should stay in focus.0) And now the reason for using black: we are going to draw the discs in additive colour mode.ADDITION_ the filter.’ so that if it registers layer will bring work on this layer later so that it is less opaque at regions of correctly you will have a My Filters menu in the Filters menu. Critics may proffer otiose jibes about the usefulness of saturation) this script.gimp_edit_bucket_fill_full(bokeh_layer. possibly even in a better way.False. things MODE.True. imagetypes specifies what kind plug-ins for Linux (ensure it is executable with blurb. bokeh_layer. We said them. Softly. additive colour doesn’t really do anything on transparency. “python_fu_linesplodge” would suffice. we use the Color-To-Alpha plugin to reset any changed tool settings” squash it out. in a manner which vaguely resembles what goes on in photography.gimp_edit_bucket_fill_full(bokeh_layer. function is just the Python name of our from gimpfu import * taxonomy. and where To ensure that Gimp finds and registers your # code goes here your plugin will appear in the Gimp menu: in our plugin next time it’s or %USERPROFILE help. The trouble is. Once we’ve drawn all our discs in this way. it is necessary to define it as a Python function) # “myplugin” special Python-Fu types here such as PF_ function and then use the register() function. back some detail. In our case general form of such a thing is: is actually automatically prepended so that all (PF_IMAGE. We feather this selection by two pixels. This means that regions of overlapping discs will get brighter. so that lower layers are illuminated beneath the discs.0. but also to the fact that the current selection should be replaced by the specified elliptical one. you may want to ‘<Image>/Filters/My Filters/PyBokeh. In the register() function. and then all the black is undone by our new additive disc.0. and you’d have to be housekeeping to take care of.gimp-2. 0. pdb.gimp_hue_saturation(bokeh_layer. The list params replacing the version number as appropriate. specifies the inputs to your plugin: you can use menus. 2) in the plugins folder: ~/.. and restoring to preserve the colour addition. The results list describes in an appropriately laid out Python script.True. WorldMags. Then we bucket fill this new selection in Behind mode so as not to interfere with any other discs on the layer: pdb. We deselect everything before we do the fill. such as “RGB*.0) any tool settings that are changed by the script. chmod +x myplugin. just to take the edge off. 0. You error-prone – you’d have to keep a note of the coordinates will see from the code on the disc that there is a little bit of and colour of the centre of each disc. menupath. 0.BEHIND_ MODE. we do a good to tidy up after yourself and leave things as you found Changing the Gaussian blur – if requested – on our copied layer. ‘python_fu’ what your plugin outputs. imagetypes.. image.8\plug-ins\ for Windows users. The example images show the results of a pdb. interest. “LSImage”) would suffice. main() COLOR and PF_SPINNER to get nice interfaces The tidiest way to do this is to save all the code The proc_name parameter specifies what in which to input them.. and indeed it would be entirely possible to do pdb. SOFTLIGHT_ everything it does by hand. #.0. It is always get a bit blurry.gimp_selection_feather(timg. and then set the foreground colour to black. if anything. MODE) That is. '#000000') this manual operation would be extremely laborious and And that just about summarises the guts of our script. blur) couple of PyBokeh applications.gimp-2. namely grouping the whole incredibly deft with your circle superpositioning if you wanted series of operations into a single undoable one. menu to save yourself from cluttering up the already crowded if blur > 0: Filters menu. def myplugin(params): what kind of plugin you’re registering. or simply “” if it doesn’t operate on any %\. # e..gimp_context_set_foreground('#000000') number 2. and set “To finish.

png") This opens an image file named screenshot.size.resize((int(width/2). let’s doesn’t support Python 3. As with all Python libraries. if you want to see the size of the image. The open() function determines the format of the file based on its contents. we first assign the size and install Pillow . and has evolved to be a better. you can call the ‘format’ attribute. The library has a bunch of modules. To view the new image. remember to open it up first: scripts to act on a disk full of images and carry out extensive >>> newImage = Image. you can use the available attributes to examine the file. >>> newImage. you can open. With Pillow.format) (1366. Note creating images from scratch. The resize method works on an image object on the PIL code. more logically named variables. While it can be done manually. Remember to specify the appropriate path to an image on your system as an argument to the Image.png. Pillow is a fork of PIL that’s based modify them. Many of the existing PIL >>> reducedIM = Pillow: Edit images easily You can save time and effort by using Python to tweak your images in"screenshot. it returns an instance of class Image. you need to install the library with sudo pip In the interactive Python shell. was a popular and powerful Python library for handling Basic image manipulation images.jpg”) modifications based on a complex set of rules. Many of width of the image by extracting them from the tuple into the commonly used functions are found in the Image module. But it hasn’t been updated for over half a decade.png’) minimal or even no The Python Image Library. more friendly version of PIL.size similarity of the API between the two. >>> reducedIM. One and height: of the best advantages of Pillow for existing PIL users is the >>> width. The method accepts a two-integer tuple for the new width manipulate and save in all the popular image file formats. height = im. that the resize method accepts only integers in its tuple 128 | Coding Made Simple WorldMags. make sure you replace the following string ython’s multimedia prowess extends to images and with an appropriate path to your image file. im. use the save method of the Image class. 768) RGB PNG The size attribute is a 2-tuple that contains the image’s width and height in pixels. using Python enables you to automate the process by easily writing >>> im. and So now that we know how to open and save images. im. For (“changedformat. >>> print (im. either reduce both values by half. Launch the Python interpreter and type: >>> from PIL import Image >>> im = Image. commonly referred to as PIL. WorldMags. If the file can’t be‘reduced. int(height/2))) code that you’ll find on the internet will work with Pillow with >>> reducedIM. RGB is the mode for true colour method.jpg”) Use the show method to view the To get started. an IOError is . begin your code by importing the Pillow modules you want to use. such as: from PIL import Image You can now open an image with the Image. For saving an image. while calling the resize method. Again. processing other images. We then divide these by 2 to You can create instances of this class in several“changedformat. Now when you have an Image object. or The result is an image that’s half the size of the original. P includes mechanisms for manipulating snapshots in a variety of ways. by loading images from files. modern and and returns a new Image object of the specified dimensions. otherwise.

them. common trick is to create thumbnails: >>> size=(128.transpose(Image. where green and blue. just like the previous example.0. and a colour these values as integers. together with the adjustments.rotate(90). and the RGB system is the The total number of RGB colour values is coloured pixels.9). you can use the >>> im. which is the number of degrees to rotate the image by and.1) at the lower-right. increase the brightness We start by defining a tuple with the dimensions of the by 20% with: thumbnail.777.FLIP_LEFT_RIGHT). which the display required to represent the two colour values. height . The computer represents white monitors. only a single bit of memory was accessible by (x.Brightness(im).transpose( methods in the ImageEnhance For more advanced image enhancement. Early colour monitors could support the display Image.BLUR).save(‘OnItsSide.rotate(180). for example. (100. WorldMags.strftime(“%A. >>> ImageEnhance. replace the call to an image object and can be used to make various the show method with the save method. equal to all the possible combinations of three (0.rotate(230. 0) at the upper-left corner of an image to RGB stands for the colour components of red.enhance(-1. b). grey is When an image is loaded. the bits from the file into a rectangular area of represents a colour. Another colour >>> im. which describe the coordinates of the image you’re interested in contains several enhancement filters.filter(ImageFilter. The display area of the monitor is made an RGB value of 0. We’ve saved ourselves some effort by calling show() directly in the first two statements to view the >>> im. green is 0. to which the human retina is of its wide range of colours. such >>> top = int(height/4) as blur to apply a Gaussian blur effect to the image: >>> right = int(3 * width/4) >>> im. such as: will first have to import it with: >>> width. Pillow’s crop method can help you with. perhaps reduce contrast and save the results: changes the original image itself.127 and yellow is 255. you should component.5). When rotated at these two angles.right. The rotate method takes a single argument (either integer or float). and save() in the third to save the rotated >>> from PIL import ImageEnhance >>> im.png’) You can now use it to. you and discard the rest. so lines and shapes on this new image with Pillow.1. without modifying the original image. So black has distinct colour value is 24. You can also create a mirror version of the‘reducedContrast. The module returns Also.size >>> from PIL import ImageFilter >>> left = int(width/4) You can now use the various filters of the ImageFilter.127. a computer maps up of coloured dots called pixels. >>> Remember that unlike the previous methods. %d %B %Y %I:%M%p”) we’ve used Python’s datetime module to timestamp an image. value consists of the tuple (r. To use this module. returns a new Image object. The value 255 represents the represent each colour value. Each pixel 127. WorldMags. Pillow maintains its original dimensions. or 16. to save the flipped image. hardware translates into the colours we see.5 degrees. 200). values: 256 * 256 * 256. using the transpose method: >>> im. Note that if the image is rotated to any angle besides 90 or 270. y) coordinates.jpg’) >>> im. whereas the value 0 represents the the total number of bits needed to represent a understand how computers read and display total absence of that component. Pillow also includes a number of methods and Yet another common image-editing task is cropping modules that can be used to enhance your images. the second by‘thumbnail. Because (width .enhance(1. including changes to contrast.255.0. so 8 bits were needed to a new white image that’s 100 pixels wide and through argument. just like resize .filter(ImageFilter.128) Dressing up images >>> Coding Made Simple | 129 . To begin portions of an >>> bottom = int(3 * height/4) >>> im. swaps its width and height.thumbnail(size) Begin by importing the ImageEnhance module with: >>> im.bottom)).datetime. RGB is known as the width and height are the image’s dimensions in sensitive. unique colour Image processing 101 To manipulate images‘RGB’. and then use it to create the thumbnail in place. These are mixed together to form a true colour system.png’) The first statement rotates the image by 180 degrees. height = im.5) In addition to the more common image-editing >>> newImage.FLIP_TOP_BOTTOM). the image With datetime.crop((left.Contrast(im). which is why we’ve wrapped the reduced dimensions in an init() call. The coordinates range from most common scheme for representing colour.255.216.0. and the third by 90 degrees. ‘white’) creates Each colour component can range from 0 of 256 You can similarly change the orientation of the image by rotating it by a specified degree with the rotate method. Each colour 200 pixels long. You can now draw all kinds of maximum saturation of a given colour component of an RGB colour requires 8 bits. An image consists of a width and a height. thumbnail Or. >>> im. In the old days of black and pixels. sharpness and name of a new image g.jpg’) techniques.BLUR).save(‘blurred. let’s take a look at the ImageFilter module.

Modify the statement to include other >>> im=Image. (IMwidth . is done via the ImageDraw module.endswith(‘. if not (filename. text function to draw a string at the specified position that points to the top-left corner of the text ( 150x150 in our script). however.ttf”. The last bottom variables to 75.size centre of the original image.join(‘withLogo’. we use the truetype function in the ImageFont module. and the Y axis two arguments that’ll determine the location of the top-left would be the height of the image minus the height of the logo. For ease of use. The above statements help cut logoIm = Image. draw. PIL can use: bitmap fonts or OpenType/TrueType . For‘screenshot. height = im.png’) or filename.text((150. we use the draw. which is the exact centre of the original image.size >>> width.png’) image formats.fill=(128. This.paste(logoIm.jpg.paste(croppedIM.255.size That’s all the info we need to paste the logo and save the >>> left = int(width/4) resulting image in the directory we’ve just created: >>> top = int(height/4) print ('Adding the logo to %s’ %(filename)) >>> right = int(3 * width/4) im. pastes an image on top of another one. You can. In case we want to place the logo in the bottom-left The paste method takes the X and Y coordinates as the coordinates of the top-left corner for placing the‘croppedImage. So continue it’s best to make a copy of your image and then call paste on The additional if statement ignores files that don’t end that copy: with a . Remember. (0. int() wrapper makes sure the returned values of the Next we’ll loop over all the images in the current directory dimensions are integers and not floats. First. you can paste a from PIL import ImageDraw.logoWidth.path.copy() anything but image files in the directory. To load a OpenType/TrueType font. Simple image editor There are several other uses for the Pillow library. however.crop((left. draw = ImageDraw. Finally. logoHeight = logoIm. and the right and image and extracted its dimensions into a variable.paste(logoIm. with a for loop: Then there’s the paste method.crop((left. IMheight = im. modify the script Perhaps the most popular use of the paste method is to to import additional libraries: Tkinter is a watermark images. corner of the image being pasted (croppedIM) into the main In Python terms.png’) from PIL import Image The crop method takes a tuple and returns an Image object of the cropped image. the left Here we’ve imported the required library. that the paste method doesn’t return jpg’)): an Image object. The cropped image’s dimensions end up being half of the original image’s dimensions. Tkinter 130 | Coding Made Simple WorldMags.makedirs(‘withLogo’.save( subtract the width and height of the logo image from the real >>>‘‘logo. The font option specifies which font. just like we did in the previous im = Image. you can go a step further and wrap the script in a rudimentary interface cooked up with Python’s de-facto GUI library Tkinter. it’s expressed as: image (copyIM). we can also place a textual watermark over the images.bottom)). use its various functions and methods to modify and apply filters to any image. which is image.truetype(“DroidSans.endswith(‘. for example.Draw(im) a lightweight user import os font = ImageFont.listdir(‘.paste(croppedIM. Now load the image Now that we have a copy of our screenshot. which We’ve used the paste method to place the logo in the we’re going to paste over the copied image: bottom-right corner of the image. 150).png.0)). Thus. The fill option gives the RGB colour for the text. filename)) The cropped thumbnail image is in >>> im. we’ll first crop and extract its size information: a smaller bit from the image.500)).png’) image. Add a watermark which is useful for annotating (filename) section: IMwidth. Similarly.right. you end up with a 50 x 50 statement creates a directory called withLogo.128)) The first statement creates an object that will be used to draw over the image. WorldMags. After pasting the thumbnails twice at im. (400. leaving you with the logoWidth. With a simple exist_ok=True) example. 24) interface for your print (“Adding watermark to %s” % (filename)) Python scripts. the coordinates will be 0 for the X axis. IMheight - >>> bottom = int(3 * height/4) logoHeight)) >>> croppedIM=copyIM.’): probably guessed.right. we >>> copyIM. opened our logo and top variables will both be set to 25. if the image you’re cropping is 100 x 100.png’) out the outside edges of the image. IMheight .bottom)) or perhaps even drop it if you don’t have >>> copyIM=im. The where we’ll house the logo-fied images. (200. which as you have for filename in os.logoHeight)) different locations.png or . and instead modifies the image in place.“All Rights Reserved”. ImageFont wonderful toolkit custom watermark or logo over all the images you’ve ever to quickly cook up shot in a matter of minutes. we save the image as pastedIM. To determine the >>> copyIM.

ImageOps. so that we can place it on to the def initUI(self): canvas. The fill option makes sure the widgets fill the l.add_command(label=“Help Index”) def main(): helpmenu. Tkinter menus can The complete script is available on our GitHub at https:// be torn off. column=3) editmenu.parent. Using PhotoImage we convert the PIL image into a The initUI() function will draw the actual interface: Tkinter PhotoImage object..img = photo2 command=self. Q WorldMags. import the required libraries: However. We then create a image being opened and reset the geometry of the window pull-down menu: accordingly.BOTH. we can program self.__init__(self.parent.setImage() package for its superior arithmetic skills.label1. the rotate command with this: menu=editmenu) im = self. so we won’t go into details executes the associated custom function when the menu about it here.Tk() menubar.configure(image=photo2) editmenu. Since we don’t want that feature. manipulation app. filetypes = ftypes) ImageFilter filename = dlg. ImageEnhance.parent.gif')] from PIL import Image.add_command(label=“About.fn) self. We can add menu options as we expand as a framework to flesh out the image editor as you learn new our app. which we do in the next line. as we did in the last line. we have to open the image: import tkinter.PhotoImage(im) editmenu = tk. filemenu.Open(self. command= self.initUI() self. let’s define a custom function to modify it: filemenu.fn = filename Besides Tkinter and PIL.add_command(label=“Exit”.title(“Simple Photo Editor”) reference to the image object.add_command(label=“Save”) two parameters are x and y screen coordinates.rotate(45) ##rotate an image 45 degrees photo2 = ImageTk.pack(fill = tk.config(menu = menubar) root.mainloop() The add_command method adds a menu item to the menu. Remember to keep a self. parent): def setImage(self): tk. Now let’s create the Here we’ve defined the parameters for the Open dialog main class that’ll initialise the graphical interface: box to help us select an image. ‘*.label1 = geo = str(l)+“x”+str(h)+“+0+0” The expand option is used to ask the manager to assign self. menu=filemenu) im = self.grid(row=1.add_cascade(label=“Help”.png.filter(ImageFilter.geometry(geo) additional space to the widget box. expand = 1) don’t. which tricks and get familiar with the Pillow before we define the custom functions for import tkinter as tk editing the images. and the add_ if __name__ == ‘__main__’: cascade method creates a hierarchical menu by associating main() a given menu to a parent menu. tearoff=0) name__ == ‘__main__’ trick : helpmenu.label1. The last is covered in detail on page 142.parent = parent photo = ImageTk. as a nice convenience feature.size entire space by expanding both horizontally and vertically. WorldMags. border = 25) Moving on.filedialog..parent) the image we’ve asked it to open. we’ll turn it off by github. we’ve imported the NumPy self.Menu(self.img = Image. import numpy as np self. to begin execution.geometry(“300x200”) self. Use it setting tearoff=0 . h = self.Frame): function that displays the image in our Tkinter interface: def __init__(self.configure(image = photo) Flip to the Tkinter tutorial on page 142 for a detailed self. This feature can be added filemenu = tk.add_command(label=“Trace Contours”. column = 1) our editor to resize the image window according to the size of menubar = tk. dlg = tkinter. The first two onOpen) parameters are the width and height of the window.add_separator() canvas.label1. add_seperator adds a separator line. ImageTk. window and positions it on the screen.quit) def onRot (self): menubar.img.”) root = tk.Menu(menubar. This will help us resize the Here we’ve used NumPy to help calculate the size of the window to accommodate larger images. menu=helpmenu) ImageEditor(root) root.onCont) You can similarly create the onCont function by replacing menubar. command=self.label1. command=self.label1.add_command(label=“Open”.jpg *.img) and columns. Normally. the image won’t always show up.img.img) self.add_cascade(label=“File”. tearoff=0) self.asarray(self.img. self.PhotoImage(self. self.I = np.image = photo2 onRot) self.image = photo # keep a reference! explanation of the methods and functions we’ve used here. The geometry method sets a size for the filemenu.add_command(label=“Rotate”. If you self. parent) self. To start constructing our basic image item is clicked.grid(row = 1.add_cascade(label=“Simple Mods”.Menu(menubar. Each menu option has a command= option. tearoff=0) by adding the following bit of code in the setImage function The above code gives the app window a title and then uses before placing the image on to the canvas: the Pack geometry manager that helps pack widgets in rows self. we’ll use Python’s if __ helpmenu = Coding Made Simple | 131 .Frame.Label(self. *.label1.CONTOUR) As usual.Menu(menubar.filedialog def onOpen(self): import PIL ftypes = [(‘Image Files’. Next comes the setImage class ImageEditor(tk.add_command(label=“Close”) Now that we have opened and placed an image on the filemenu.

99 iPAD PRO Worth the upgrade? Master your tablet’s apps and system features EACH ISSUE JUST £2.99 / $ JOIN US ON TWITTER: @iPadUserMag . SUBSCRIPTIONS FROM £1.99 / $4. WorldMags.

net . Available from THE ONLY APPLE ACCESSORY YOU’LL EVER NEED! ON SALE NOW! The new & improved MacFormat magazine .com WorldMags. WorldMags.rebuilt from the ground up for all Apple enthusiasts.

input= True. The library can help you record audio as well as play .open (format=pyaudio. and open and close audio streams. and discard popular cross-platform PortAudio I/O library. rate defines the sampling frequency. Another advantage of reading data in chunks. For one. In a real program. we’ll also define a number of properties that can be altered to influence how the data is captured and recorded. WorldMags.PyAudio() stream = p.Stream class. see later on. The input=True parameter asks PyAudio to use the stream as input from the device. easily installed with a simple pip install pyaudio command. While initialising the stream.1 kHz. instead of a continuous amount because it involves handling a variety of devices.paInt16 parameter sets the bit depth to 16 bits. we use to define the length of the audio buffer. which is usually 44. working with multimedia is fun. It can be the rest. access audio devices. we will also define with the WAV library to capture (or play) audio in the lossless two variables: WAV format: record_seconds = 10 import pyaudio output_filename = ‘Monoaudio. captured in this buffer can then either be discarded or saved. input_device_index = 0. Frames_per_buffer is an interesting parameter. int(rate / chunk * record_seconds)): 134 | Coding Made Simple WorldMags. which A udio is an important means of communication and. you can quickly cobble together the code to open the PyAudio recording stream. which is mentioned with the input_device_index parameter. The data truth be told. rate=44100. PyAudio is generally complemented program as well. channels can be set to 1 for mono or 2 for stereo. which has a limited amount of PyAudio.PyAudio class is used to initiate and terminate PortAudio. reading data in and formats. you’ll want to define these parameters As with all programs. Along with the above. The pyaudio. standards of audio. frames_per_buffer = 1024) The pyaudio.wav’ import wave Now comes the code that does the actual audio capture: print (“ Now recording audio.paInt16. However. as we will back sounds without writing oodles of code. because they’ll be used in other places in the by importing the library. where the stream is opened with several parameters. which indicates that you are reading the data as 16-bit PyAudio: Detect and save audio Discover how Python can be used to record and play back sound. channels=1. p = pyaudio. Speak into the microphone. you need to begin any PyAudio program in variables. The real audio processing happens in the pyaudio. ”) Capture audio frames = [ ] Once you’ve imported the libraries. and make continuous flow of data from the microphone would just eat interactive apps. Recording a with Python to capture and manipulate sound. is that it enables us to analyse the data and only The PyAudio library provides Python bindings for the save those relevant bits that meet our criteria. There are several libraries that you can use chunks helps use resources efficiently. One of the better platform-independent up the processor and may lead to memory leaks on devices libraries to make sound work with your Python application is such as the Raspberry Pi. for i in range(0. for a couple of reasons. working with audio is a challenging task PyAudio uses chunks of data.

which sets evaluates the expression. channels=1. is initialised with the __init__ function. The popular PortAudio documentation to understand the there’s also the is_active() and is_stopped() ones are the sampling rate.writeframes(b‘ ’. rate=44100.setsampwidth(p. and finally terminates the PyAudio session. class Recorder(object): While the above code will work flawlessly and helps def __init__(self. In a real project. the variable given by as .setnchannels(channels) would look something like: wf. and assigns whatever __enter__ returns to the PyAudio’s get_sample_size() function. which the data as 16-bit integers. We discuss Python’s if __name__ == ‘__main__’ trick for Python opens the file in the write-only mode. while get_time() returns the stream’s or both. Moving on. as we’ve done. and setframerate. paInt24. This is followed by a bunch of wave write The above code is executed when the program is run directly. The for loop handles the task of recording the‘capture. there are several other parameters that can be or stopped. an output stream other formats include paInt8. paInt32 and frames. which return a Boolean value channels.close() p. exception.Stream class. The Recorder class opens a recording stream and defines you’ll have a 10-second WAV file named Monoaudio. The get_input_latency() list of the other popular ones. Here’s a depth to 16 bits. the code that begins the execution wf. when the with statement is executed. before closing the file. guard object’s __exit__ method. and then define a list variable named frames . ”) stream. value. audio hardware on your machine. Now that we have the audio data as a string of bytes in the frames list. the wave module. After executing the program. In addition to this. it calls the case is named frames. You can safely ignore these because they are the some setup and shutdown code to be executed – for result of PyAudio’s verbose interactions with the audio example. It brings in the data in correctly sized chunks and saves it into a list named frames .open(output_filename. In such a case. depending on whether the stream is active the sampling size and format.close() code and must be ironed out.close() recfile. WorldMags. objects. we’ll transform it and save it as a WAV file using the wave module: break up the tasks into various smaller tasks and write a class wf = wave. and selecting one for their application.wav’.0) This is where the data is actually written to an audio file. and calls the magic __enter__ the frame rate (44. irrespective of what happens in that code. to close the file in our case: hardware on your computer. WorldMags. ‘wb’) for each. What you should watch out for def __exit__(self. The __enter__ and If you run the program. latency.channels = channels how you’d program it in the real world. frames=1024): demonstrate the ease of use of the PyAudio library. Python channels (mono in our case). the number of frames per buffer.join(frames)) with rec. The setsamwidth object method on the resulting value (which is called a context sets the sample width and is derived from the format using guard). you’ll first notice a string of __exit__ methods make it easy to build code that needs data = stream. Finally. For managing the stream. function returns the float value of the input can either be an input stream. besides the You can pass several parameters to the stream are advised to spend some time with the start_stream() and stop_stream() functions. the number of nuances of these different formats before functions. traceback): are any Python exceptions that point to actual errors in the self. In our case. you’d self. which in our and.setframerate(rate) rec = Recorder(channels=1) wf. which sets the number of Now. this isn’t self. as defined by writing reusable code in the Tweepy tutorial (see page 138). We will now close the audio recording stream: print (“ Done recording audio. which sets the bit used to fetch information from a sound file while can use with the pyaudio.rate = rate Managing a PyAudio stream We’ve used some of the parameters that you we’ve used paInt16 format. then You can safely ignore all messages (except Exception errors) that appear whenever you run a PyAudio script – it’s simply the library discovering the closes the stream. such as setnchannels. The stream. the number of bytes a recording should have. indicating that you are reading initialising a stream.terminate() The above code first terminates the audio recording. ‘wb’) as recfile: wf.1kHz in our case). The for loop helps determines how many samples to record given the rate.stop_stream() stream. the loop makes 430 iterations and saves the captured audio data in the frames list. Audiophile developers time. In the tutorial. and the recording duration.join() method combines the bytes in a Coding Made Simple | 135 . Python then executes the code body b‘ ’.append(data) We first print a line of text that notifies the start of the recording.wav in its parameters: the current directory.get_sample_size(format)) if __name__ == ‘__main__’: wf.record(duration=10. while creating it.

When all the frames have been streamed.argv) < 2: stream. accessing system-specific functions and parameters.rate. We used the wave wide range of multimedia formats including WAV. we’re done. As long as there are chunks For more sys. One of the best features of the Pyglet module to read and write audio files in the WAV MP3. bunch of external ones. OGG.close() level is considered p = pyaudio. OGG/Vorbis and WMA.exit(-1) of data.write(data) print(“ The script plays the provided wav file. 136 | Coding Made Simple WorldMags. simplifying module. self. which multimedia frameworks with Python bindings. self. and contains the code to record data from the microphone into the file after setting up the stream parameters. The script will play any provided WAV file. we’ll use functions to extract details from described earlier. fname. There’s also installation. channels=wf. The GStreamer Python bindings allow as MP3. It enables multimedia and windowing library is that it needs audio format. processing capabilities. the while loop writes the current frame of audio accurate results. decode and nothing else besides Python.frames) If a filename is provided. to decide what wf = wave. the getnchannels Vocalise recordings method returns the number of audio channels. you can also train PyAudio to start recording as soon as it detects a voice. as reading a WAV file.wav” % sys. uses FFMPEG to support formats other than work with AVbin to play back audio formats such you can find the minimum and maximum values WAV. # read data import pyaudio data = wf. output=True) self.frames_per_buffer = frames getsampwidth()). developers to use the Gstreamer framework to formats such as DivX. the above code comes into action and prints the we’ll then terminate the stream and close PyAudio with: of sound frames proper usage information before exiting. Once we have all the details from the file. it’s opened in read-only mode The class defines the necessary parameters and then and its contents are transferred to a variable named wf.readframes(1024) Proper usage: %s filename. MPEG-2. recording. calculate the RMS value for a group provided.wav’) print(“Alrighty. WorldMags. Auto recorder In the scripts above. we’ll import the sys module for audio file.wav”) The record_to_file function receives the name of the file to record the sound data to. return RecordingFile (fname. ‘rb’) stream. when the . used for manipulating the raw audio encode all supported formats. stream. streaming modules for working with sound. which the PyAudio library is initialised. For example.264. we extract the argv[0]) frames in chunks of 1.argv[1]. def open(self. stream = p.\n data = wf.terminate() to be silence.getframerate().readframes(1024) import wave import sys # play stream (3) while len(data) > 0: if len(sys. which Other popular Python sound libraries Python has some interesting built-in multimedia PyMedia is a popular open source media library playback to video playback. and then writes the files using the for loop.PyAudio() p. Recorded to capture.channels. the getsampwidth method fetches the sample width of the file in bytes. mode. such as: print(“Start talking into the mic”) record_to_file(‘capture. multiplex. Then passes them to another class. DivX.024 bytes. If one isn’t data to the stream. mode=‘wb’): rate=wf. as well as a that supports audio/video manipulation of a and editing. captures we used earlier to define the parameters of the stream. we’ll initiate the script as usual with the if __name__ == ‘__main__': trick to print a message and then call the function to record the audio. WMV and There are also several third-party open source develop applications with complex audio/video Xvid. With a little bit of wizardry. Another popular library is Pygame. Unlike the open() function defines the record function that opens the stream.getnchannels(). In addition getframerate returns the sampling frequency of the wave to pyaudio and wave. which is a high-level audio interface that and other visually rich applications. from simple audio adds functionality on top of the SDL library. It also calls the record() function. and You can easily adapt the code to play back the file. For instance. demutiplex. and video of all the samples within a sound fragment. It’s popular for developing games data. There’s also the built-in audioop you to parse. and keep capturing the audio until we stop talking and the input stream goes silent once again. It can be used to perform several Pydub.get_format_from_width(wf. the file. H. DVD and more. we’ve seen how to use PyAudio to record from the microphone for a predefined number of seconds. Similarly. To do It can also operations on sound fragments. named RecordingFile.

We next check r. we’ll increment the num_silent variable.extend([0 for i in range(int(seconds*RATE))]) whether this recorded data contains silence by calling the return r is_silent function with silent = is_silent(snd_data) . among other things. if snd_started and num_silent > 100: input=True. we’ll set the snd_started num_silent = 0 variable to True to begin recording recording and pad the audio with 1. seconds): r. Adding silence is Coding Made Simple | 137 .PyAudio() stream = p. elif not silent and not snd_started: def record(): snd_started = True p = pyaudio.5 seconds of blank sound. we’ll call another function to manipulate the snd_data = array(‘h’. defined the is_silent (snd_data) function elsewhere in the com/geekybodhi/techmadesimple-pyaudio/. we’ll then subject it to several other Python libraries for playing sound. Although there are returns a value (either True or False). so have fun num_silent += 1 playing around with your sound! Q WorldMags.byteswap() def add_silence(snd_data.frames_per_buffer=CHUNK_ break SIZE) If the captured data is above the threshold of silence and we haven’t been recording yet. channels=1. Once the is_silent function the end and even from the start. snd_data. [0 for i in range(int(seconds*RATE))]) The function records words from the microphone and r. rate=RATE. checks the captured data for silence. It uses the max(list) Websites such as Program Creek help you find sample code for Python modules like PyAudio. But if we’ve been snd_started = False recording sound and the captured data is below the silence threshold. while 1: Next.extend(snd_data) returns the data as an array of signed shorts. PyAudio is further tests: one of the easiest to use with third-party audio toolkits that if silent and snd_started: you can use to capture and manipulate sound. When you script. This function will return True if the snd_data consequent frames until it detects a period of silence. Moving r = array(‘h’) on. A value lower than the threshold by writing a trim function that’ll trim the silent portion from intensity is considered silence. which returns the execute it. stream. it’ll save all maximum value. if it exists. From here on. we’ll stop recording if we’ve been recording but it’s been 100 frames since the last word was spoken. The threshold intensity defines The script also contains comments to help you extend it the silence-to-noise signal.extend(snd_data) r = array('h’. We’ve The complete script is on our GitHub at https://github. is below the silence threshold. it will detect and start capturing audio frames but elements from a list (snd_data in this case) with the discard them until it detects a voice. We’ll just read the recorded data into if byteorder == ‘big’: an array and then extend it by adding blank frames.

Twitter also offers a set of Quick Tweepy accesses Twitter via the OAuth standard for streaming APIs. You used the items method to iterate through our timeline. take a minute or two.twitter. To can. for example. which raw data passing over the network.items(): what the world is thinking.text) social network is powered by a wonderful API that The code will print all status updates in groups of 20 from enables users to drink from the firehose and capture all the your own timeline. WorldMags. however.Cursor(api. which you the tweets. interacting with Twitter via Python is You can easily install Tweepy with pip install tweepy . strings listed alongside API Key.API(auth) From this point can leave blank.Cursor(api.streaming import StreamListener html) for a list of Access Tokens tab and create an OAuth token. tweepy. We’ll Tweepy’s Twitter credentials. In this tutorial. you can supports several different types of objects. you need to import the following libraries in your Python script: import tweepy from tweepy. find trends related to specific keywords or limit the number of tweets you wish to print. Here we have use this data to mine all kinds of meaningful information. Once captured. Access Token and Access Token Secret. using Tweepy to capture any tweets that mention OggCamp. For that. you can access tip authorisation. we can use the api variable for interacting with Twitter. The public streams work Scroll through http://apps. you can tap into the collective consciousness and extract “valuable” information from it.set_access_token(access_token. Tweepy is one of the easiest libraries that you can use to user_timeline). and use these to connect to Twitter. we’ll be recent tweets. app has been created.items(10) . such as: consumer_key = “ENTER YOUR API KEY” consumer_secret = “ENTER YOUR API SECRET” access_token = “ENTER YOUR ACCESS TOKEN” access_secret = “ENTER YOUR ACCESS TOKEN SECRET” auth = OAuthHandler(consumer_key. API Secret. you’ll first have to head over to Twitter’s global stream of tweets. Now press the Create New App button import and modify Tweepy’s StreamListener class to fetch documentation (http://docs. This might from tweepy import OAuthHandler supported methods. which will only print the 10 most access the Twitter API with Python. you can read your own time with the following loop: T witter is a wonderful tool if you want to get a feel for for status in tweepy. you can hop over to the Keys and from tweepy. access_secret) api = tweepy. As you can see. reasonably straightforward. For example. To access the tweets. and fill in all the fields except for the Callback URL. consumer_secret) . change the statement to something like tweepy. We use Tweepy’s Cursor interface. and by using these.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream Next you need to paste in the API and Access tokens. you can also gauge sentiments during events. and then we’ll mine the data to print a list of the most Capture tweets frequently used hashtags. Once the from tweepy import Stream en/latest/ and sign in with your regular really well for following specific topics and mining data. Once it’s done. You’re now all set to access Twitter with Python. The visible 140-character print(status.user_timeline). and then click on the Create Tweepy: Create Twitter trends With some Python know-how. make a note of the 138 | Coding Made Simple WorldMags.

Once you have discovered the Here we use our stream class to filter the Twitter stream to Twitter ID. You can also filter results by combining Anatomy of a tweet The 140 characters of the tweet that are visible representation of the user who has contributed used (you) has marked the tweet as favourite or on your timeline are like the tip of the if the Python number of attempts to connect to the streaming API within a interpreter is running the source file as the main program. which lists the UTC time when the tweet Besides these. the connect will error out. your wait time. For example. ‘tuxradar’ information about what to do with the data once it comes or ‘LinuxFormat’. you can modify the above to say twitterStream. Here we begin by creating a class that inherits from StreamListener. Tweepy establishes a streaming session and routes All that gobbledygook is just one tweet! messages to the StreamListener Coding Made Simple | 139 . We place by @LinuxFormat. information that has been parsed out of the text Also important is the lang field. Then comes the text field. data): print(data) return True def on_error(self. Of this inside an if condition. the stream listener. Boolean fields that indicate fields contain information that points to the id_str fields. fetch only tweets that contain the word ‘oggcamp’. listener) You can modify the above to filter your results based on Once we’ve authenticated with Twitter. warnings. it When you’re interacting with Twitter via its API. and statements in a module can find out the name of data from status to the on_status() method.API(auth) class StdOutListener(StreamListener): def on_status(self. and passes name. It is followed by the id and the retweeted fields. Repeated attempts sets the special __name__ variable to have a value “__ will only aggravate Twitter and it will exponentially increase main__” . The modified StreamListener class is filter(track=[‘LXF’. This contains the that contain any of the three words specified: ‘LXF’. If you exceed the limited defines a few special variables. use Tweepy’s on_ __name__ is set to the module’s name. number of times the tweet has been favourited the tweet itself. or for creating a live feed using a site stream or user stream. such as URLs and hashtags. The if __name__ == “__main__”: these. it window of time. ‘LinuxFormat’]) will get tweets used to create a listener instance. For instance. if __name__ == ‘__main__’: you’ll first have to find out its Twitter ID using a web service twitterStream. back from the Twitter API call.OAuthHandler( auth = tweepy. A to the tweet. contains the two-character language identifier of field.filter(track=[“oggcamp”]) such as Twitterid. which will display any new tweet parameter is an array of search terms to stream. When the Python interpreter reads a source file. it to be mindful of rate limiting. Similarly. The track filter(follow=[‘255410383’]) . on_data() . ones will help you extract the relevant data. we can now start multiple keywords. WorldMags. which contains and retweeted respectively. which contain the more information and attributes in addition to contains the actual text of the status update. A knowledge of the important We’ve also use the entities field. twitterStream = Stream(auth. on_status() and on_error() are the most trick exists in Python. direct messages and so on. status): print(status) return False The Twitter streaming API is used to download Twitter messages in real time. its module. using twitterStream. which The JSON string begins with the created_at of the tweet. Every module has a statuses. if you wish to follow a particular Twitter account. ‘tuxradar’. so our Python files can act as reusable useful ones. To avoid such a situation.set_access_token(access_token. is being run standalone by the user and we can do listener = StdOutListener() corresponding appropriate actions. you have executes all the code found in it. It is useful for obtaining a high volume of tweets. Before executing the code. The place and geo was created. which are the integer and string whether the user whose credentials are being geographic location of the tweet. consumer_ secret) auth. In our case. such as en or de. as the error() method to print the error messages and terminate defined __name__ is ‘__main__’ it tells Python the module execution. Then there are the favorite_count complete tweet in its JSON form contains a lot we’ve used extensively in the tutorial – this and retweet_count fields. WorldMags. StreamListener has several methods. there’s the favorited and the tweet. If this file is being imported from another module. The on_data() method handles replies to modules or as standalone programs. which retweeted it.access_secret) api = tweepy.

It opens the output file.argv[1]) else: print(‘Usage: python top_tweets. you can simply redirect the output of class StdOutListener(StreamListener): the StreamListener to a file. Else the script prints the proper usage information if the user has forgotten to point to the JSON file.12775829999998223].tweet_data. self.tweet_data)) The StreamListener will remain open and fetch tweets various parameters. (https://dev. Begin by importing the relevant libraries: import sys import json import operator Now we’ll pass the .com and register a new app to get yourself def main(tweetsFile): some API keys and access tokens. After installing the connector. writes the Before you can process the tweets. just like we have done in the connect.twitter. tweets_file = open(tweetsFile) Save tweets to database Instead of collecting tweets inside a JSON file. and also print the values on the screen. For example. We’ll then scan each tweet for text. WorldMags.tweet)) store the username and the tweet. USE tweetTable.json file to the script from the command line. tweet in the stream. The large blobs of text on your screen return True are the tweets fetched by the streamlistener in the JSON Instead of printing the tweets to the screen. import io and closes the document. host=‘localhost’.open(‘oggcampTweets.write(u‘[\n’) block will import the io library and use it to append the data flowing from the StreamListener into a file named Process tweets for frequency oggcampTweets.tweet_data=[] We can now use the oggcampTweets.loads(data) provides a connector for Python 3 that you can import json if ‘text’ in all_data: easily install by using pip3 install mysql. use the following code to import the required class StdOutlistener(StreamListener): you can also directly connect to and save them Python libraries and connect to the database: def on_data(self. Head over to http://apps. If it finds a pointer to the JSON containing the tweets file. Take a look at Twitter’s official API documentation saveFile = io. CREATE TABLE tweets (username Once we’re connected.-0.connector all_data = json. connect = mysql. with a table named tweets that has two fields to and extract the tweet along with the username print((username.cursor() db. writes the JSON data as text to a file.json’. encoding=‘utf-8’) parameters) for a list of all the supported streaming request saveFile. we’ll create a tweet) VALUES (%s. The MySQL database import mysql. then inserts a closing square bracket. track=[‘linux’]) def on_data(self.json will save all tweets with def __init__(self): the word ‘oggcamp’ to a file named . db=connect.%s)”. Alternatively.5073509. username = all_data[“user”][“screen_name”] you can create a database and table for saving connect(user=‘MySQLuser’. You can now and screen name from the tweets: return True 140 | Coding Made Simple WorldMags. data): inside a MySQL database. python fetch_ oggcamp. StreamListener.json.tweet VARCHAR(140)). For example. ‘w’.json file to mine all kinds of data.write(‘.commit() This creates a database called tweetTable main tutorial.join(self. database=‘tweetTable’) table. twitterStream. you will have to save them opening square bracket.(username. Once we’ve extracted the information from a the tweets with: password=‘MySQLpassword’.’. tweet = all_data[“text”] connector-python .close() terminating the script.append(data) word ‘linux’. data): will fetch any tweets that originate in London and contain the self. For example. saveFile. the above format (see box below). it’s forwarded to the main() function.twitter. tweet)) VARCHAR(15). we can write these to the CREATE DATABASE tweetTable. let’s analyse this data to list the 10 most frequently used file-with-tweets.json’) The following code analyses the number of parameters passed from the command line.filter (location=[51.write(u‘\n]’) based on the specified criteria until you ask it to stop by saveFile. separated by commas. if __name__ == ‘__main__’: if len( > oggcampTweets.argv) == 2: main(sys.execute(“INSERT INTO tweets (username.

loads(tweet_line) key=operator. you can install over 200 system is called Conda. that people used if tweet_line.strip(): sortedHashTags = dict(sorted(tweets_hash.encode(“utf-8”) in tweets_hash. we’ll check whether the hashtag is GitHub repository at: https://github. and save it in a variable named the descending order of their occurrence.keys(): print(“#%s .encode(“utf-8”)] += 1 You’ll need to familiarise yourself with data structures and else: dictionaries in Python to make sense of the above code. if “entities” in tweet. These are the tweets_hash = {} increment its occurrence frequency. we’ll extract the results. To access tweetsFile variable. Each tweets_hash[ht[“text”]. You can use Miniconda to and install it with: you can use the familiar square brackets variable.items().kv[0]). grab the installer from ships with a package management system. Python also Of the two distributions. The code block will filter the top 10 tweets based on into a dictionary object. and print the tweet .net Coding Made Simple | 141 . WorldMags. Miniconda. Then close and re-open the terminal window for installing multiple versions of software packages. Next.value in sorted(sortedHashTags. includes Conda.keys(): hashtags = tweet[“entities”][“hashtags”] print(“\nHashtag . libraries and also installs Python. We then initiate a loop for every through the entire JSON file and scavenged data from all the individual tweet in the file. In case it is. Python. and it can be used for dependencies with the conda install already listed in our dictionary. we’ll just techmadesimple-tweepy. Python’s package management install over 200 scientific packages and their bash Miniconda3-latest-Linux-x86_64. Q Python’s package management Just like your Linux distribution. Anaconda.pydata. and http://conda. the JSON file is received as the curly braces.reverse=True): if ht[“text”].Occurrence\n”) for ht in hashtags: for count. while tweeting tweet = json. and it includes Conda and Conda-build. reverse=True)[:10]) about privacy. if ht != None: key=lambda kv: (kv[1].html helps install complex packages.items(). such as Anaconda and Miniconda. Keys are unique within a dictionary.decode(“utf-8”). Else. and the whole thing is enclosed in simple.%d times” % (count. and also over 100 packages list command to list the installed packages.itemgetter(1). we’ll add it to the top hashtags for tweet_line in tweets_file: dictionary and record the occurrence. Miniconda is the smaller install Miniconda. tweets_hash that will house the hashtags and their The above code comes into play after we have gone occurrence frequencies. on the other hand. the changes to take effect. Like can now install packages such as matplotdb distributions. which one. value)) tweets_hash[ht[“text”]. You application and instead ships with all Python and libraries that it installs automatically. To start with. the items are The above might look like a mouthful but it’s actually really separated by commas. If the tweet has a tag named ‘entities’. We then define a dictionary variable named along with the key to obtain its value.encode(“utf-8”)] = 1 key is separated from its value by a colon (:). The complete code for this tutorial is available in our hashtag value. We’ll first convert the JSON string tweets. which is then read by the tweets_file dictionary elements. To with conda install matplotdb . Now use the conda Conda isn’t available as a standalone Conda-build.

which states that ‘explicit is tip used to create the graphical app’s main window. it goes Quick We begin by first importing the Tkinter module.Tk() app = App(master=root) app. it’s important to note that we’ve interface to Tk. including an editable display. Tk was developed explicitly created an instance of Tk with root = tk.Button(self. # Insert code to add widgets used to correct mistakes and to enter symbols and com/h3eotvf).hi = tk. listed import tkinter as tk to write our graphical calculator.pack() self. before entering the main event loop to Graphical calculator vegaseat’s Updated take action against each event triggered by the user.hi[“text”] = “Hello World” self. which can be (http://tinyurl.pack(side=“top”) self.hi. JPython app.mainloop() and window = tk.Frame.EXIT. which is then against the spirit of Python.createWidgets() def createWidgets(self): self. Tkinter is the Python build our calculator. window. as a GUI extension for the Tcl scripting language in the early Tkinter starts a Tcl/Tk interpreter behind the scenes.__init__(self.EXIT = tk. and both are required in order for a Tkinter the Tk GUI toolkit. master=None): tk. create your first widget. Creating an instance of Tk initialises code. text=“EXIT”. such as wxPython. to learn than other toolkits.Tk() our calculator.title(‘Sample Application’) P ython provides various options for developing app. it doesn’t take much effort to drape a Python Tiny Tkinter example. explicitly initialise it. We’ll use the same principles Calculator. For Tkinter: Make a basic calculator Why not use Python’s default graphical toolkit to build a simple – yet easily extensible – visual calculator? Here’s a more practical example that creates a window with a title and two . One of the reasons for its popularity is that it’s easier then translates Tkinter commands into Tcl/Tk commands. one or more of the supported widgets (see box on page 143) The code in this tutorial is based on to the main window.Tk() . master) self. For example. because Tkinter is a set of wrappers that implement the this interpreter and creates the root window. you don’t need to write Tcl application to work. While this is perfectly fine. For As you can see. Tkinter is the standard GUI We’ll explain the individual elements of the code as we library that ships by default with Python. command=root.master.mainloop() hexadecimals not on our calculator’s keypad. We’ll add various widgets to on DaniWeb. If you don’t Tk widgets as Python classes. the GUI toolkit for Tcl/Tk. the following code will display a window: app with a graphical interface. WorldMags. Next we add better than implicit’. one of which quits the application when clicked: import tkinter as tk class App(tk. which 1990s. one will be implicitly created when you Creating a GUI application using Tkinter is an easy task. The main window of an application and this interpreter are Tkinter provides a powerful object-oriented interface to intrinsically linked.pack(side=“bottom”) root = tk. fg=“red”.geometry(“250x70+550+150”) graphical user interfaces. if 142 | Coding Made Simple WorldMags.master. To use Tkinter. Of these.Label(self) self.Frame): def __init__(self.destroy) self.

we initialise the instance parameters for the positioning and appearance of our Commonly used Tkinter widgets The Tkinter toolkit supports over a dozen types multiline and non-editable object that displays scrollbars on Entry widgets. The partial function from the functools module helps us write reusable Define the layout code. In other and trigonometric functions.Tk. The the user clicks on it. our calculator will words. automatically when you click the button. ( bg ). You have to declare it explicitly. The Menu widget can create such as the ones to define background colour Checkbutton widget is used to display a number different types of menus. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object. such as Listbox. the math library to handle the calculations. is automatically called when an object of that class is created. So when you call Calculator() . You can associated with a Menu widget. It is important to use We begin by importing the various libraries and functions the self parameter inside an object’s method if you want to for our calculator. a list of all the options supported by each of options. it’ll print the decimal equivalent. top. WorldMags. Every menubutton is w = <widgetname> (parent. we’ll also need persist the value with the object.. and can level and pull-down. which creates Listbox widget is useful for displaying a list of controller that is used to implement vertical tcc/help/pubs/tkinter/web/index. that is 170.. We’ll explain how we’ve used it later in the tutorial. the __init__ method is the constructor for a class in also have the ability to temporarily store and retrieve a result Python. In this section we define different Calculator class. the The Scrollbar widget provides a slide documentation (http://infohost. such as the logarithmic argument. method. it will be passed automatically.nmt. they also share several options. . The Canvas widget of controls or widgets that you can use in your texts. variables with the __init__ method in the class body. The basic idea is that it is a special method. but class Calculator(tk. the border ( bd ). the editable display can also be used to manually method is executed automatically when a new instance of the type in functions that aren’t represented on the keypad but class is created. and then passes it as the first parameter to the __init__ Tkinter library and its interactions with Python. import tkinter as tk The self variable and the __init__ method are both OOP from math import * constructs. the part of a drop-down menu that stays on the All these widgets have the same syntax: The Button widget is used to create buttons screen all the time. ) define a function for a button. WorldMags.Tk): Python does not. Refer to the Tkinter also display images in place of text. The Message widget provides a Text and Canvas. and the size of of options to a user as toggle buttons. including pop-up. Python creates an object for Let’s dissect individual elements to get a better grasp of the you. Besides the Tkinter Tkinter makes it relatively easy to build a basic graphical calculator in Python. To begin with.html) for items from which a user can select multiple scroll bars on other widgets. Furthermore. When you def __init__(self): create an instance of the Calculator class and call its tk. You can also create horizontal these widgets. text or other widgets. you enter Coding Made Simple | 143 . The first order of business is to create the graphical interface After importing the libraries. Here are some of the most Then there’s the Menubutton.__init__(self) methods. the type of border ( relief ). Similarly. creates an area that can be used to place graphical application. Python passes the instance as the first are defined in Python’s math module. that can display either text or images. which is called display the choices for that menubutton when Similarly. This Similarly. option1=value. commonly used ones. which can option2=value. and it is a convention to name it self. The self variable represents the instance of the from functools import partial object itself. The complete code for the calculator is available online. we begin defining the for the calculator. which from its memory bank.

and rotation. We use the geometry function to define the size and After creating the button. geometry managers. we increment the position of the position of the calculator’s window – it accepts a single string column and check if we’ve created four columns. we use the implement various kinds of buttons. ‘*’. By default. It includes hierarchy and comes with support for scaling websites.Entry(self. we use several Entry widget The Button widget is a standard Tkinter widget used to methods. The ‘4’. the entry. They are result = eval(self.calculate. Then functions from OpenGL. notebooks.tix there’s the TkZinc widget. and draw the next row of buttons. Else. also known as Pmw. editable display. display the result whenever the equal to (=) key is pressed. such used to implement items for displaying graphical distributions. You can also just the label and move on to the next button. Grid. which is pretty the passed expression as a Python expression. self. ‘3’.get()) listed in the order they’ll appear on the keypad. we implement a plain button. column=c) Calculator class with MyApp(). The calculation is handled by the eval function. In simpler straightforward to use. The btn_list array lists if key == ‘=’: the buttons you’ll find in a typical calculator keypad.create_widgets() around the boundaries of the button. such as anti-aliasing most popular Tkinter extension is the tkinter.title(“Simple Demo Calculator”) with one or more arguments already filled in.entry. If they aren’t available in your as a ComboBox and more. but the geometry manager always has which is part of the functools module. we call the partial Widgets can provide size and alignment information to function to pass the button number. it also provides be extended to provide even more widgets.calculate function. we just print have been added here for easier readability.entry. text=label. self. label)). self. offset coordinates. The r and c elif key == ‘C’: variables are used for row and column grid values. In our code. it can several widgets such as buttonboxes. r += 1 which does the actual calculation but hasn’t been defined yet. The partial function makes a new version of a function self. To add a value to the widget. The comboboxes. as the argument in the format: width x height + xoffset + then we reset the column variable and update the row yoffset . this means that the eval function makes a string with button contents (text from the array.entry. Once we’ve defined the look of the calculator window.geometry(“350x140+550+150”) the new version of a function documents itself.END. When the button is pressed. relief=‘ridge’. Within the self. In the next line. a button While Tkinter supports three geometry managers – appears raised and changes to a sunken appearance when it namely. Entry widget is a standard Tkinter widget used to enter or ‘1’. buttons.grid method helps us place the widget in r=1 the defined cell and define its length. key): create the layout for the calculator. columnspan=5) btn_list = [ The last bit of the calculator’s visual component is the ‘7’.Button(self. which we create using the Entry widget. The real string doesn’t contain any spaces. ‘5’. and you can associate a Python function or current value. Tkinter automatically calls that function or method. ‘Mem >’.delete(0. ‘/’. The c=0 command parameter refers to the self.’.Button function. distro. a mathematical equation. don’t forget to remove if c > 4: the command parameter from the tk. column=0. WorldMags. above code defines and creates the individual calculator you can define the calculate function. The create_widgets() method contains code to def calculate(self. 144 | Coding Made Simple WorldMags. ‘6’. Buttons can contain text insert method. in our case) and what integers in it. ‘+’. the Once you’ve perfected the look and feel of your . display a single line of text. width=33. helps write reusable the final say on positioning and size. function or method to call when the button is pressed using the command parameter.grid(row=r.grid(row=0. unlike the Canvas widget. while the get method is used to fetch the or images. bg="green") def create_widgets(self): self. ‘> Mem’. Because this setting doesn’t suit our calculator.entry = tk. Furthermore.entry.memory = 0 The relief style of the button widget defines the 3D effect self. If you call on the command=partial(self. width=5. If we have. we’ll first create a button using the Button function. The partial function. ‘2’. ‘8’. Pack and Place – we’ll use the Place manager. All you have to do is to specify the terms. Furthermore. The return value is the Popular Tkinter extensions While the Tkinter toolkit is fairly extensive. ‘. In the above calculation code. This process is set the position of the window by only defining the x and y repeated until the entire keypad has been drawn. Our calculator is now visually complete. which is very similar and more. grab and compile them following the Another popular toolkit is the Python the TkZinc widget can structure the items in a straightforward instructions on their respective megawidgets. We use a combination of these to calculate and method with each button. c=0 for label in btn_list: Define the special keys tk. components. ‘C’. However. which provides several modern widgets to the standard Canvas widget in that it can be extensions in the repositories of popular that aren’t available in the standard toolkit. ‘Neg’ ] length of the display and bg its background colour. ‘=’. which parses In our code.insert(tk. You can find some of these widget library.mainloop() it draws the c += 1 keypad of the calculator. “ = ” + str(result)) Next we create all buttons with a for loop.END) loop. Arranging widgets on the screen includes determining the size and position of the various components. dialog windows and more. tk. ‘9’. code. self. ‘-’. The width option specifies the ‘0’. which variable. is calculator. which is the simplest of the three and allows precise we’ve used the ridge constant. However. boundary around the individual buttons. which creates a raised positioning of widgets within or relative to another window.

the eval command.memory = self. The __import__ function accepts a module name ( os in this case) and imports it. if there’s an equal to (=) sign the square root of a number. after the following code block: calculator so committing a value to the memory. First add a key labelled ‘sqrt’ in in the Entry widget.entry. This means we calculate function and enter the following just above the final can now clear the entry and start a new calculation as soon else condition: as a number is punched. When the button labelled ‘> Mem’ is make the code compatible with the older Python 2. the code scans the equation and only saves the replace the lines at the top to import the Tkinter library with functions to your numbers after the equal to (=) sign.entry. To clear the current entry. you can can add more pressed.END.END) execute this command on the web server and print the self.entry.memory = self. you complete equation.entry. The risk with eval() is well documented and has to self.insert(tk. If this if ‘=’ in self. tk. self. schmuck! Stick to negative number. For example.END) import the library with its Python 3 name. The good can similarly extend the calculator by implementing other thing about Python and Tkinter is that they make it very easy maths functions as well. key) current working directory. then Python will attempt to self.insert(0. if ‘=’ in self. Q WorldMags. elif key == ‘sqrt': result = sqrt(eval(self. Instead of passing the contents of the field to beginning of the value. If there’s an equal to calculate function: (=) sign in the display.get())) Add more functionality self.“sqrt= “+str(result)) The above code implements a functional graphical calculator.”) negative sign.memory) elif key == ‘Mem >’: self.get()[0] == ‘-’: function.END. you can easily add a key to calculate conditions are met.delete(0. import Tkinter as tk more advanced Coding Made Simple | 145 . When you press the = key. the eval() function will self. when the code detects that the key labelled ‘Mem except ImportError: calculations.insert(tk. You purposes.insert(tk.delete(0) do with the fact that it evaluates everything passed to it as else: regular Python code.entry.memory: val = self. which is how it was referred to in Python 2.entry. In this case.get(): getcwd() .memory. then the key will insert a negative sign to the the display field.END. WorldMags.get(): operation throws an ImportError. We use these to clear the contents of the editable display at the top whenever the C button is pressed. This code block will first attempt to import the Tkinter elif key == ‘Neg’: library. If the value already contains a self. Then scroll down to where you define the completed and the result has been displayed. elif key == ‘ > Mem’: self. it copies the number saved in its buffer import tkinter as tk to the editable display.get() if ‘=’ in self. however. then that means a calculation has been the btn_list array. pressing the ‘Neg’ button will remove the calculations. it’ll be executed on the server and can except IndexError: wreck havoc. Another way to extend the calculator is to add more which is triggered when none of the previously mentioned functions. Secondly.title(‘Memory =’ + self.find(‘=’) self. pressing the key labelled ‘Neg’ will clear if ‘_’ in self.entry. This brings us to end of our code and the Else condition.insert(tk.memory[val+2:] self. “Nice try. write __import__('os'). try: Another weak point in the code is its use of the eval() if self. For better control. For instance.entry. tk. run the calculator and in else: the display result of the evaluated expression. both the above two conditions This code is triggered when it detects an underscore (_) in aren’t met. So if the user enters a valid Python shell self. we use the delete method.mainloop() operating system.entry.entry.entry. it changes the title of the try: it’s capable of calculator window to reflect the contents of the memory. instead of a number. the Entry widget also allows you to specify character positions in a number of ways.delete(0. When the code is triggered. tricky. if you wish to extensibility.entry. The conditions in the above listed code block are a little To prevent such exploitations of the eval() function.get(): the contents of the display. pass To get an idea of what happens. We then use app = Calculator() the imported module to run commands on the underlying app. there’s always scope for improvement. If. >’ has been pressed. The current value in the buffer is the to extend and improve the code.entry. END corresponds to the position just after the last character in the Entry widget. ‘-’) string into the function. it’ll calculate the square root But as it is with every piece of code written for demonstration of the number in the display field and print the results. The code at the top of this code block comes into play you can insert the following code while defining the when the key labelled ‘Neg’ is pressed. the code displays a warning.END. we define the actions for saving Thanks to and retrieving a calculated value from the calculator’s Tkinter’s memory banks.entry.memory) In this part of the code.

146 | Coding Made Simple . then ‘How do I download my reward?’ and enter the voucher code WQBA7 *Requires an iPad or iPhone and the Apple App and tap Help on the bottom menu bar. Offer ends 18 June GET YOUR FREE * DIGITAL EDITION Experience this great book on your iPad or iPhone completely free! To get your digital copy of this book simply download the free Linux Format app from http://myfavm. WorldMags.

net .net WorldMags.WorldMags.

Visit 9000 .. t Pick up the basics with Python tricks and t Teach kids code on the Raspberry Pi tutorials t Hack Minecraft! Build a GUI! Scan Twitter! Learn as you code with stacks of Get to grips with hacking and coding Take coding concepts further with our example-packed guides with the amazing Raspberry Pi exciting and easy-to-follow projects 9001 Like this? Then you’ll also love. today! Build essential programming skills from the ground up Everyone can code with these plain-English guides – you’ll learn core programming concepts and create code to be proud of! Dozens of expert tutorials 148 pages of tips.