Learn Python Visually: Creative Coding with Processing.py
By Tristan Bunn
()
About this ebook
This beginners book introduces non-programmers to the fundamentals of computer coding within a visual, arts-focused context. Tristan Bunn’s remarkably effective teaching approach is designed to help you visualize core programming concepts while you make cool pictures, animations, and simulations using Python Mode for the open-source Processing development environment.
Right from the first chapter, you'll produce and manipulate colorful drawings, shapes and patterns as Bunn walks you through a series of easy-to-follow graphical coding projects that grow increasingly complex. You’ll go from drawing with code to animating a bouncing DVD screensaver and practicing data-visualization techniques. Along the way, you’ll encounter creative-yet-practical skill-building challenges that relate to everything from video games, cars, and coffee, to fine art, amoebas, and Pink Floyd. As you grow more fluent in both Python and programming in general, topics shift toward the mastery of algorithmic thinking, as you explore periodic motion, Lissajous curves, and using classes to create objects.
You’ll learn about:
In addition to giving you a good grounding in general programming, the skills and knowledge you’ll gain in this book are your entry point to coding for an ever-expanding horizon of creative technologies.
Related to Learn Python Visually
Related ebooks
Beginning Graphics Programming with Processing 3 Rating: 0 out of 5 stars0 ratingsGraphic Guide to R with Processing.R 4: Graphic Guide to Programming Rating: 0 out of 5 stars0 ratingsA Student's Guide to Python for Physical Modeling: Second Edition Rating: 0 out of 5 stars0 ratingsMATLAB Made Easy: Project-Based Learning for Young Innovators Rating: 0 out of 5 stars0 ratingsPython Graphics Rating: 0 out of 5 stars0 ratingsScientific Computing with Python 3 Rating: 0 out of 5 stars0 ratingsPython Essentials Rating: 5 out of 5 stars5/5NumPy Cookbook Rating: 5 out of 5 stars5/5LaTeX Cookbook: Over 100 practical, ready-to-use LaTeX recipes for instant solutions Rating: 4 out of 5 stars4/5PyQt6 101: A Beginner’s guide to PyQt6 Rating: 0 out of 5 stars0 ratingsMastering Algorithm in Python Rating: 0 out of 5 stars0 ratingsPython Mini Manual Rating: 0 out of 5 stars0 ratingsPython Programming For Beginners: Python Programming Language Tutorial Rating: 0 out of 5 stars0 ratingsmatplotlib Plotting Cookbook Rating: 5 out of 5 stars5/5Python for Beginners Rating: 0 out of 5 stars0 ratingsMastering Python: A Comprehensive Crash Course for Beginners Rating: 0 out of 5 stars0 ratingsTeach Yourself VISUALLY Python Rating: 0 out of 5 stars0 ratingsPython The Complete Reference: Comprehensive Guide to Mastering Python Programming from Fundamentals to Advanced Techniques Rating: 0 out of 5 stars0 ratingsPython Made Easy: A First Course in Computer Programming Using Python Rating: 0 out of 5 stars0 ratingsAbsolute Beginner's Python Programming: The Illustrated Guide to Learning Computer Programming Rating: 1 out of 5 stars1/5Mastering matplotlib Rating: 0 out of 5 stars0 ratingsComputer Graphics in Python Rating: 0 out of 5 stars0 ratingsPython Made Simple: A Practical Guide with Examples Rating: 0 out of 5 stars0 ratingsMastering MATLAB: A Comprehensive Journey Through Coding and Analysis Rating: 0 out of 5 stars0 ratingsAdvanced Data Structures in Python: Mastering Complex Computational Patterns Rating: 0 out of 5 stars0 ratingsStatistics and Data with R: An Applied Approach Through Examples Rating: 3 out of 5 stars3/5Mastering Objectoriented Python Rating: 5 out of 5 stars5/5IPython Notebook Essentials Rating: 0 out of 5 stars0 ratings
Programming For You
SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsPython Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5HTML in 30 Pages Rating: 5 out of 5 stars5/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Python Machine Learning By Example Rating: 4 out of 5 stars4/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsLearn SQL in 24 Hours Rating: 5 out of 5 stars5/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5A Slackers Guide to Coding with Python: Ultimate Beginners Guide to Learning Python Quick Rating: 0 out of 5 stars0 ratingsCoding with JavaScript For Dummies Rating: 0 out of 5 stars0 ratings
Reviews for Learn Python Visually
0 ratings0 reviews
Book preview
Learn Python Visually - Tristan Bunn
Learn Python Visually
Creative Coding with Processing.py
by Tristan Bunn
nsp_logo_black_rkSan Francisco
LEARN PYTHON VISUALLY. Copyright © 2021 by Tristan Bunn.
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher.
ISBN-13: 978-1-7185-0096-9 (print)
ISBN-13: 978-1-7185-0097-6 (ebook)
Publisher: William Pollock
Executive Editor: Barbara Yien
Production Editor: Katrina Taylor
Developmental Editors: Annie Choi and Jill Franklin
Cover Design: Gina Redman
Interior Design: Octopod Studios
Technical Reviewer: Paddy Gaunt
Copyeditor: Sharon Wilkey
Compositor: Craig Woods, Happenstance Type-O-Rama
Proofreader: Emelie Battaglia
Indexer: BIM Creatives, LLC
For information on book distributors or translations, please contact No Starch Press, Inc. directly:
No Starch Press, Inc.
245 8th Street, San Francisco, CA 94103
phone: 1-415-863-9900; [email protected]
www.nostarch.com
Library of Congress Control Number: 2020950273
No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The information in this book is distributed on an As Is
basis, without warranty. While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it.
About the Author
Tristan Bunn kicked off his web design career back in the days of PlayStation 1, grunge music, and dial-up modems. Since then, he’s worked on a diverse range of digital projects for varied clients. He’s currently involved in lecturing, research, and work that blends code, interaction, interface design, and creativity. Tristan has years of experience teaching coding for art, games, web, and other creative technologies.
About the Tech Reviewer
Paddy Gaunt studied engineering at Cambridge University (UK), working in the chemical and gas industries as well as textile manufacturing. Much of the time, he had the responsibility of implementing IT systems as these became a more significant part of management and marketing. Since its launch in 2012, he has been the chief maintainer of the pi3d Python module for fast 3D graphics on the Raspberry Pi microcomputer.
Acknowledgments
I’ve been a fan of No Starch Press books for years, and I’m thrilled to have them publish my first book. I’d like to thank everybody there, in particular my editors, Jill Franklin and Annie Choi, for their invaluable feedback and direction. Thanks to Paddy Gaunt, the technical reviewer, for checking over all my code and offering some excellent suggestions to improve it.
Additionally, I’d like to thank the creators, maintainers, and community surrounding Processing and its related projects, and also the developers of the Python programming language. You’ve inspired my students and me, and it’s a privilege to share your hard work with everybody who reads this book.
Introduction
When I first encountered programming code, I stared, amazed and bewildered, at a screen of obscure commands and symbols and wondered how anybody could understand it, let alone write it. I’d hit the F5 key, and the program would magically spawn a cityscape in which two players, depicted as gorillas, could hurl explosive bananas at each other. I tried changing a few lines to see what would happen, and on occasion, it was something predictable or cool. More often than not, the game would simply fail to run. In a futile attempt to be helpful, the computer would diagnose my errors, rambling on about syntax and illegal
operations of varying description.
For some years thereafter, I was content to avoid learning to program. That began to change when I became interested in making my creative work more interactive. You may already have encountered a few of the same barriers that frustrated me. Maybe you were getting by just fine with visual tools but then hit a wall. Or to your disappointment (and horror?), you discovered that what you sought to accomplish required delving into code.
Software applications, with all of their graphical widgets, make us feel like we’re in control. The illusion, however, soon fades when you discover that the tool you desire is missing. Through learning to program, you gain a true mastery of your computer.
Who Is This Book For?
This book assumes no prior programming experience. It strives to make the process of learning to program as visual and entertaining as possible. The content is based on my extensive experience teaching first-time coders, designers, and interactive media students. The skills and knowledge you’ll gain are fundamental to programming for an ever-expanding horizon of creative technologies, such as games, the web, augmented/virtual reality, and even visual effects for films.
If you’re an artist, student, designer, researcher, or just somebody keen on picking up coding skills, Python Mode for Processing is excellent for learning to program in a visual context.
For anybody with prior programming experience, this book would be useful for learning Python, Python Mode for Processing, or creative coding techniques.
You may have experience with another visual programming language—something like Scratch, where you connect together graphical elements like boxes, icons, and arrows. Python is not such a language—rather, it is a textual programming language that requires you to type code. To make learning visual, though, you’ll focus on writing code that produces drawings, patterns, animations, data visualizations, user interfaces, and simulations. This approach not only makes for cool-looking graphics, but also helps you visualize the underlying concepts of programming.
What Is Python Mode for Processing?
Python Mode for Processing combines the Python programming language and Processing, a development environment for interactive and graphics programming. You’ll also see Python Mode for Processing referred to as Processing.py. The project started as a command line tool named Processing.py, but its developer decided to label it Python Mode when it was made available for the Processing development environment. In this book, you can consider the terms largely interchangeable.
Python is one of the most popular programming languages in use today. There are many good reasons for this, but here’s why you should care. First, Python is a beginner-friendly language. It’s more approachable than languages like Java or C++, so you’ll find it easier to read, write, and understand. Second, it’s a general-purpose language, suitable for programming artificial intelligence (AI), games, simulations, web applications, and just about everything in between.
Processing, which has been around since the early 2000s, is composed of a programming language and an editor for writing and compiling code. It provides a collection of special commands that allow you to draw, animate, and handle user input by using code. The creators, Casey Reas and Ben Fry, developed Processing to make programming more accessible for designers and artists, although its thriving user base has grown to include researchers, hobbyists, and educators.
Java is the basis for the original Processing programming language, but other variants have since appeared, including JavaScript (p5.js) and Ruby (JRubyArt) versions. In 2010, Jonathan Feinberg created Processing.py, which you can think of as a sort of extension for Processing that allows you to write Python instead of Java-esque code.
Both Python and Processing are open source and won’t cost you a cent. What’s more, you can use them on just about any platform, including Linux, macOS, and Microsoft Windows.
What Are Algorithms?
You’ll encounter the term algorithm frequently in the domain of programming. You can think of an algorithm as a set of rules a computer or machine must follow to achieve a particular goal. As an example, an algorithm for making a cup of instant coffee would read as follows:
Place one teaspoon of coffee granules in a mug.
Fill the kettle with water.
Switch on the kettle.
Once the water has boiled, add 240 ml boiling water to the mug.
Add one level teaspoon of sugar to the same mug.
Stir the contents.
Serve.
However, this set of steps is insufficient for programming a real-life coffee-making robot. Should the sizes of the mugs vary, smaller ones would overflow. Furthermore, the robot would ignore any requests for milk or extra sugar. Computers cannot make any assumptions, and require explicit and unambiguous direction, communicated in a language that machines understand—like Python. Learning the Python language may be the hurdle you face initially, but as you grow more fluent, the challenge will shift toward the mastery of algorithmic thinking.
What Is Creative Coding?
Creative coding is computer programming for creative output. This broad term encompasses, but is not limited to, computer-generated audio and visual art, interactive installations, experimental games, and data visualizations.
Take, for example, Frederic Brodbeck’s Cinemetrics project. Using Python, Brodbeck developed a program that analyzes DVD movie data to generate visual fingerprints of films. The fingerprint is an open ring formed from many segments; a single segment represents a span of 10 shots, and the concentric bands show the color breakdown for each of those segments. The diagonal length of each segment indicates the amount of motion. Figure 1 is a Cinemetrics fingerprint for the film Quantum of Solace (2008).
f00001Figure 1: Quantum of Solace fingerprint, created by Frederic Brodbeck. Screenshot from http://cinemetrics.site/.
The fingerprints can also be animated, in which case motion is instead visualized using pulsating segments. An interactive interface provides a selection of presets and filters so that you can arrange fingerprints alongside one another and make comparisons—for example, between originals and remakes, different genres, the works of a single director, and so forth. Figure 2 compares (from left to right) 2001: A Space Odyssey (1968), The Simpsons Movie (2007), and a soccer match.
f00002Figure 2: Fingerprints comparing (left to right) 2001: A Space Odyssey, The Simpsons Movie, and a soccer match. Screenshots from http://cinemetrics.site/.
Many creative coding projects employ a similar underlying approach, in which data is fed into a program to influence how it controls output. Music visualizations with real-time audio synchronization—like those featured in popular media player software—are a good example. However, you can experiment with plenty of other data sources, such as web feeds, fitness trackers, environmental sensors, and a plethora of public datasets.
In some instances, it’s useful to opt for randomized data values. Consider procedurally generated game content. As opposed to constructing levels manually, you can program games to generate dungeon layouts, terrain, narrative elements, and enemy spawn locations automatically. Of course, such games should include sensible constraints; for instance, a cap on the total number of enemies that can appear at once, and algorithms for ensuring that stage layouts are not impossible to traverse.
Game characters may be composed using a random selection of modular components, or generated entirely from shapes and formulas. As an example, I’ve written a Processing Python program that generates the randomized microbial beasties displayed in Figure 3. The code—an adaptation of Lieven Menschaert’s NodeBox script Aquatics!—spawns a creature with a random fill color, shape (defined by something named the superformula), and no fewer than three eyes. There’s a 70 percent chance that hair will grow along the creature’s edges, which can be swayed by the force of a randomly directed current.
f00003Figure 3: A Processing.py adaption of Lieven Menschaert’s NodeBox script Aquatics!
Countless examples of cool, creative coding projects exist—from robots that doodle and write poetry, to evolutionary simulators, and even a program that pores over satellite imagery in search of architecture or infrastructure that resembles letters (The Aerial Bold Project by Benedikt Groß and Joey Lee, 2016).
Perhaps this creative coding thing sounds a bit too artsy for you? Processing also isn’t ideal for that race car sim you’ve always dreamed of building, and it’s definitely no good for backend web development. That’s okay. Creative coding with Processing’s Python Mode need not be the ultimate goal of reading this book. Think of it as a starting point for exploring Python, other frameworks, creative applications for coding, and programming in general.
Where Can I Find Help?
Programming is rewarding, in part because it’s challenging. If you find yourself struggling with something, do not stress; that’s normal! With a little perseverance, you’ll soon grasp whatever has you snagged.
Online Resources
If you’re getting nowhere, reach out to online communities. You’ll find a dedicated category for Processing.py in the official Processing forum at https://discourse.processing.org/. You’ll often discover that somebody has already encountered and received a solution for the challenge you’re facing; if not, go ahead and create a new topic. Incidentally, the author of this book is known to lurk about in this friendly and welcoming corner of the internet.
The official Python Mode reference is available at https://py.processing.org/reference/. Each entry includes a description and brief code example. It’s handy to keep this web page open while you work in the Processing development environment.
Source Code and Solutions
You’ll be typing a lot of code. This is a good thing because the best way to learn is by doing. At times, however, you might mistype something or be unable to figure why your code refuses to work. In such instances, it can be helpful to have access to a complete, working version of the file. You can access all of the code in this book, as well as solutions to the challenges in each chapter, at https://github.com/tabreturn/processing.py-book/. You can also find any updates to this book at https://www.nostarch.com/Learn-Python-Visually/.
What’s in This Book?
This book begins with the basics and builds up toward more advanced topics as you progress. Each chapter, therefore, requires a grasp of the concepts introduced in the chapters preceding it. You’ll be working, step by step, through a series of practical tasks. You’ll also find some theory, plenty of visuals, and challenges to consolidate what you’ve learned.
The following outline provides a brief overview of the contents in each chapter:
Chapter 1: Hello, World! This chapter covers the installation and setup procedure for the book and introduces the basics of drawing with code. You’ll also learn how computers manage color, how you can store and reuse values (using variables), and how to perform basic arithmetic operations using Python.
Chapter 2: Drawing More Complicated Shapes Having covered some drawing essentials in the first chapter, you’ll move on to drawing more organic shapes, as opposed to geometric ones. You’ll learn to define shapes by using points (or vertices) and curves, which enable you to draw just about any shape with code.
Chapter 3: Introduction to Strings and Working with Text In this chapter, you’ll learn how to use Python’s string features to manipulate text. You’ll also learn how to use Processing functions to draw text to the display window, in different styles and colors, and in different fonts.
Chapter 4: Conditional Statements This is where you really begin to think like a programmer. In this chapter, you’ll introduce control flow to your programs. In other words, you’ll learn how to write programs that can make decisions, executing different actions to respond to different situations.
Chapter 5: Iteration and Randomness In this chapter, you’ll learn how to write programs that can repeat an operation a specified number of times or until a certain requirement is met. Toward the end of the chapter, you’ll experiment with randomness and creating tiled patterns.
Chapter 6: Motion and Transformation This chapter focuses primarily on adding motion to your Processing programs and transforming the drawing space. You’ll also learn how to save frames as images and how to get time values from your computer. You’ll use these skills to create an animated screensaver and analog clock.
Chapter 7: Working with Lists and Reading Data Python lists will unlock powerful ways to manage and manipulate values in collections. You’ll explore techniques for data visualization. You’ll also learn to read in list data from external files. For the final task, you’ll render a chart by using a CSV file.
Chapter 8: Dictionaries and JSON Dictionaries are similar to lists in that they store collections of items. With dictionaries, however, you access items by using a key (usually a word) instead of referring to the item position. Once again, you’ll get to use your new dictionary skills for data visualization. You’ll also learn to work with JSON data.
Chapter 9: Functions and Periodic Motion You’ll use functions to divide a program into named sections of reusable code. This will make your code more modular, and easier to read and modify. You’ll also delve into some trigonometry for generating elliptical and wave-type motions.
Chapter 10: Object-Oriented Programming and PVector You can use object-oriented programming to structure programs by modeling real-world objects. In this chapter, you’ll employ an object-oriented approach to building an amoeba simulation. You’ll also learn to program the amoebas’ motion by using Processing’s PVector class.
Chapter 11: Mouse and Keyboard Interaction In this chapter, you’ll add interactivity to your programs. Processing can handle input from various devices, but here you’ll focus on mouse and keyboard input to build a paint app. In the process, you’ll learn about event functions and how to control Processing’s draw loop behavior.
Let’s Go!
The speed at which you progress through these chapters is likely to be influenced by your prior experience in similar areas. If you’ve done any type of programming before, Python or otherwise, you’ll encounter some familiar concepts. That said, it’s not a race! Enjoy the ride, stop for breaks, and if you’re feeling really inspired, feel free to head off-road.
1
Hello, World!
When learning a new programming language, it’s a long-standing tradition that the first code you write is to display the message ‘Hello, World!’ In keeping with that tradition, you’ll do that here too—but that’s not all. This chapter introduces everything you need to understand the fundamentals of Processing, and you’ll quickly move on from a simple ‘Hello, World!’ to drawing with code.
To get started, you’ll set up Python Mode for Processing so you can create your own sketches. Along the way, you’ll learn the basic rules of writing code in Processing, as well as how to deal with errors, use variables, and perform arithmetic operations. You’ll also learn about how Processing handles color and how to measure angles using radians. By the end of this chapter, you’ll be comfortable drawing colorful geometric shapes by using various Processing functions. Let’s get started.
Processing Installation and Python Mode Setup
Before writing any code, you first need to set up Python Mode for Processing. Head over to the Processing downloads web page (https://processing.org/download/) and grab the version of Processing appropriate for your system (Windows, Linux, or macOS). As of January 2021, Processing 3.5.4 is the latest stable release.
Processing does not employ an installation program. Instead, you simply extract the file you have downloaded (usually a .zip archive) and run the application. The exact process varies slightly between operating systems:
On Windows, unzip all of the contents by right-clicking the file and selecting Extract All, and then follow the instructions. Extract or move the folder to any location on your computer, including your Program Files folder or Desktop.
On macOS, unzip the file by double-clicking it, and then move the extracted app to any location on your computer, including your Applications folder or Desktop.
TheLinux version of Processing is a .tar archive. Extract or move the folder to any location on your computer, including your home folder or desktop.
Once you’re finished, open the newly extracted folder. Figure 1-1 shows an abridged listing of what you can expect to see in your file manager. Next, locate and run the executable file named processing. On macOS, you’ll just have a single file named processing.
f01001Figure 1-1: The contents of a freshly extracted processing folder for Windows or Linux
The application layout may vary slightly among systems and Processing versions, but the key elements are outlined in Figure 1-2. If you’re a Mac user, you’ll find the menu bar in its usual position at the top of your screen. Note that the upper right button in the Processing interface is labeled Java. This is because Processing comes bundled with Java mode as the default.
f01002Figure 1-2: The Processing interface
Next, activate Python Mode. Click the Java button and select Add Mode from the drop-down menu; then, from the Contribution Manager window that appears, choose Python Mode for Processing. Finally, click Install. You can now change between Python and Java mode by using the drop-down menu. Switch to Python (Figure 1-3).
f01003Figure 1-3: The button to the right indicates that Python Mode is activated.
You’re now ready to write your first lines of code!
NOTE
For a demonstration of what Processing can do, take a look at the Python examples (File▶Examples) included with Processing. To run any example, use the play (▶) button.
Your First Sketch
Processing refers to programs as sketches. Given the visual and artistic nature of what you are likely