Monk, S. (2013) Programming the Raspberry Pi – Getting Started with Python, McGraw-Hill
Download eBook PDF (PDF 16,608KB)
Download Source Code from https://github.com/simonmonk/monk_raspberrypi/tree/master/edition_1
Companion Web Site: http://simonmonk.org/programming-raspberry-pi-ed1/
Create innovative programs and fun games on your tiny yet powerful Raspberry Pi. In this book, electronics guru Simon Monk explains the basics of Raspberry Pi application development, while providing hands-on examples and ready-to-use scripts. See how to set up hardware and software, write and debug applications, create user-friendly interfaces, and control external electronics. Do-it-yourself projects include a hangman game, an LED clock, and a software-controlled roving robot.
- Boot up and configure your Raspberry Pi
- Navigate files, folders, and menus
- Create Python programs using the IDLE editor
- Work with strings, lists, and functions
- Use and write your own libraries, modules, and classes
- Add Web features to your programs
- Develop interactive games with Pygame
- Interface with devices through the GPIO port
- Build a Raspberry Pi Robot and LED Clock
- Build professional-quality GUIs using Tkinter
- What is the Raspberry Pi?
- What can you do with a Raspberry Pi?
- A Tour of the Raspberry Pi
- Setting Up
- Booting Up
- Summary
- Linux
- The Desktop
- The Internet
- Applications
- Internet Resources
- Summary
- What is a Programming Language?
- IDLE
- Numbers
- Variables
- For Loops
- Simulating Dice
- If
- While
- Summary
- String Theory
- Lists
- Functions
- Hangman
- Dictionaries
- Tuples
- Exceptions
- Summary of Functions
- Summary
- Modules
- Object-Orientation
- Defining Classes
- Inheritance
- Summary
- Tkinter
- Hello World
- Temperature Converter
- Other GUI Widgets
- Dialogs
- Menus
- The Canvas
- Summary
- What is Pygame?
- Hello Pygame
- A Raspberry Game
- Summary
- GPIO Pin Connections
- Direct connection to GPIO Pins
- Expansion Boards
- Prototyping Boards
- Arduino and Pi
- Summary
- What You Need
- Hardware Assembly
- Software
- Phase Two
- Summary
- What You Need
- Phase 1. A Basic Rover
- Hardware Assembly
- Phase 2. Adding a Rangefinder and Screen
- Summary
- Linux Resources
- Python Resources
- Raspberry Pi Specific Resources
- Other Programming Languages
- Applications and Projects
- Summary
Sweigart, A. (2012) Making Games with Python and Pygame – A guide to programming with graphics animation and sound, CreateSpace Independent Publishing Platform
Download eBook PDF (PDF 4,457KB)
Download Source Files (ZIP 5,143KB)
Companion web site: http://inventwithpython.com/pygame/
Read the Book Online at http://inventwithpython.com/pygame/chapters/
Making Games with Python & Pygame is a programming book that covers the Pygame game library for the Python programming language. Each chapter gives you the complete source code for a new game and teaches the programming concepts from these examples. The book is available under a Creative Commons license and can be downloaded in full for free from http://inventwithpython.com/pygame This book was written to be understandable by kids as young as 10 to 12 years old, although it is great for anyone of any age who has some familiarity with Python.
Making Games with Python & Pygame covers the Pygame library with the source code for 11 games. Making Games was written as a sequel for the same age range as Invent with Python. Once you have an understanding of the basics of Python programming, you can now expand your abilities using the Pygame library to make games with graphics, animation, and sound.
The book features the source code to 11 games. The games are clones of classics such as Nibbles, Tetris, Simon, Bejeweled, Othello, Connect Four, Flood It, and others.
Roffey, C. (2012) Coding Club: Python Basics Level 1, Cambridge, University Press
Download Source Code (ZIP 4KB)
Download Python Basics – Answers (ZIP 5KB)
Companion Web Site: http://www.codingclub.co.uk/
A unique series that provides a framework for teaching coding skills. Learn the basics of coding quickly! This lively book is an introduction to the world of coding and to Python 3 – a fantastic language to start coding with. Young programmers will learn how to code and customise several fun applications including their own Magic8Ball and an Etch A Sketch® game. The fun challenges and Quick Quizzes help to consolidate new skills and the companion web site provides the full source code for all the projects and challenges as well as help for readers.
Roffey, C. (2013) Coding Club: Next Steps Level 2, Cambridge, University Press
Download Source Code (ZIP 23KB)
Download Python Next Steps – Answers (ZIP 21KB)
Companion Web Site: http://www.codingclub.co.uk/
A unique series that provides a framework for teaching coding skills. Take your Python coding to the next level! Book 2 continues seamlessly on from Python Basics, offering full support and progressive tasks for students who have some basic programming experience and are ready to move on to slightly more challenging material. You will learn how to program and customise a simple calculator and, most importantly, learn essential new programming ideas that will make you a much more accomplished coder. The code is suitable for Mac, Windows and Linux users and therefore compatible with the Raspberry Pi.
Roffey, C. (2012) Coding Club: Programming BIG Apps Level 3, Cambridge, University Press
Download Source Code (ZIP 45KB)
Download Python Building BIG Apps – Answers (ZIP 29KB)
Companion Web Site: http://www.codingclub.co.uk/
A unique series that provides a framework for teaching coding skills. Build more sophisticated apps with level 3 of Coding Club! Following on from Python: Next Steps, this lively book explains how to break down projects into manageable chunks, guiding and supporting you with building larger, more exciting projects. Activities include building a version of Pong and, using the classes created for Pong, building a Breakout game and an Invaders game, developing and learning the necessary skills to build larger apps on the way. The code is suitable for Mac, Windows and Linux users and therefore compatible with the Raspberry Pi.
Lambert, K. (2013) Fundamentals of Python – Data Structures, Delmar Cengage Learning
Download eBook PDF (PDF 3,575KB)
Download Source Code (ZIP 170KB)
Companion Web Site: http://home.wlu.edu/~lambertk/python/cs2python/index.html
Written for computer programming students, hobbyists, and professionals, FUNDAMENTALS OF PYTHON: DATA STRUCTURES is an introduction to object-oriented design and data structures using the popular Python programming language. The level of instruction assumes at least one semester of programming in an object-oriented language such as Java, C++, or Python. Through the step-by-step instruction and exercises in this book, you’ll cover such topics as the design of collection classes with polymorphism and inheritance, multiple implementations of collection interfaces, and the analysis of the space/time tradeoffs of different collection implementations (specifically array-based implementations and link-based implementations). Collections covered include sets, lists, stacks, queues, trees, dictionaries, and graphs. Get ready to dig into Python data structures with FUNDAMENTALS OF PYTHON: DATA STRUCTURES.
- Covers the design of collection classes with polymorphism and inheritance.
- Covers multiple implementations of collection interfaces.
- Covers the analysis of the space/time tradeoffs of different collection implementations.
1. Basic Python Programming.
2. An Overview of Collections.
3. Searching, Sorting, and Complexity Analysis.
4. Arrays and Linked Structures.
5. Interfaces, Implementations, and Polymorphism.
6. Inheritance and Abstract Classes.
7. Stacks.
8. Queues.
9. Lists.
10. Trees.
11. Sets and Dictionaries.
12. Graphs.
Zelle, J. (2010) Python Programming: An Introduction to Computer Science, Second Edition, Franklin, Beedle & Associates Inc
Download eBook PDF (PDF 2,139KB)
Download Source Code (ZIP 55KB)
Companion Web Site: http://mcsp.wartburg.edu/zelle/python/
This is the second edition of John Zelle’s Python Programming, updated for Python 3. This book is designed to be used as the primary textbook in a college-level first course in computing. It takes a fairly traditional approach, emphasizing problem solving, design, and programming as the core skills of computer science. However, these ideas are illustrated using a non-traditional language, namely Python. Although Python is used as the language, teaching Python is not the main point of this book. Rather, Python is used to illustrate fundamental principles of design and programming that apply in any language or computing environment. In some places, I have purposely avoided certain Python features and idioms that are not generally found in other languages. There are already many good books about Python on the market; this book is intended as an introduction to computing. Features include the following:
- Extensive use of computer graphics.
- Interesting examples.
- Readable prose.
- Flexible spiral coverage.
- Just-in-time object coverage.
- Extensive end-of-chapter problems.
Payne, J. (2010) Beginning Python: Using Python 2.6 and Python 3.1 (Wrox Programmer to Programmer)
Download eBook PDF (PDF 5,689KB)
Download Source Code from http://www.wrox.com/WileyCDA/WroxTitle/Beginning-Python-Using-Python-2-6-and-Python-3-1.productCd-0470414634,descCd-DOWNLOAD.html
Beginning Python: Using Python 2.6 and Python 3.1 introduces this open source, portable, interpreted, object–oriented programming language that combines remarkable power with clear syntax. This book enables you to quickly create robust, reliable, and reusable Python applications by teaching the basics so you can quickly develop Web and scientific applications, incorporate databases, and master systems tasks on various operating systems, including Linux, MAC OS, and Windows. You′ll get a comprehensive tutorial that guides you from writing simple, basic Python scripts all the way through complex concepts, and also features a reference of the standard modules with examples illustrating how to implement features in the various modules. Plus, the book covers using Python in specific program development domains, such as XML, databases, scientific applications, network programming, and Web development.
Introduction.
Part I: Dipping Your Toe into Python.
Chapter 1: Programming Basics and Strings.
Chapter 2: Numbers and Operators.
Chapter 3: Variables –– Names for Values.
Part II: Python Language and the Standard Library.
Chapter 4: Making Decisions.
Chapter 5: Functions.
Chapter 6: Classes and Objects.
Chapter 7: Organizing Programs.
Chapter 8: Files and Directories.
Chapter 9: Other Features of the Language.
Chapter 10: Building a Module.
Chapter 11: Text Processing.
Part III: Putting Python to Work.
Chapter 12: Testing.
Chapter 13: Writing a GUI with Python.
Chapter 14: Accessing Databases.
Chapter 15: Using Python for XML.
Chapter 16: Network Programming.
Chapter 17: Extension Programming with C.
Chapter 18: Numerical Programming.
Chapter 19: An Introduction to Django.
Chapter 20: Web Applications and Web Services.
Chapter 21: Integrating Java with Python.
Part IV: Appendices.
Appendix A: Answers to the Exercises.
Appendix B: Online Resources.
Appendix C: What’s New in Python 3.1.
Appendix D: Glossary.
Python Tutorial from TutorialsPoint
(http://www.tutorialspoint.com/python/)
Download eBook PDF (PDF 5,075KB)
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). This tutorial gives enough understanding on Python programming language.
Rhodes, B. (2014) Foundations of Python Network Programming – The comprehensive guide to building network applications with Python, Third Edition, Apress
Download eBook PDF (PDF 3,795KB)
Download Source Code (ZIP 147KB)
Foundations of Python Network Programming, Third Edition, covers all of the classic topics found in the second edition of this book, including network protocols, network data and errors, email, server architecture, and HTTP and web applications, plus updates for Python 3.
Some of the new topics in this edition include:
• Extensive coverage of the updated SSL support in Python 3
• How to write your own asynchronous I/O loop.
• An overview of the “asyncio” framework that comes with Python 3.4.
• How the Flask web framework connects URLs to your Python code.
• How cross-site scripting and cross-site request forgery can be used to attack your web site, and how to protect against them.
• How a full-stack web framework like Django can automate the round trip from your database to the screen and back.
If you’re a Python programmer who needs a deep understanding of how to use Python for network-related tasks and applications, this is the book for you. From web application developers, to systems integrators, to system administrators—this book has everything that you need to know.
• Extensive coverage of the updated SSL support in Python 3
• How to write your own asynchronous I/O loop.
• An overview of the “asyncio” framework that comes with Python 3.4.
• How the Flask web framework connects URLs to your Python code.
• How cross-site scripting and cross-site request forgery can be used to attack your web site, and how to protect against them.
• How a full-stack web framework like Django can automate the round trip from your database to the screen and back.
• Updated coverage of network protocol layers and data encodings
• How Python 3 works with network exception handling
• How to use the requests library instead of urllib2
• Expanded coverage of Python web frameworks
• How to work with web applications and email
If you’re a Python programmer who needs a deep understanding of how to use Python for network-related tasks and applications, this is the book for you. From web application developers, to systems integrators, to system administrators—this book has everything that you need to know.
- Introduction to Client/Server Networking
- UDP
- TCP
- Socket Names and DNS
- Network Data and Network Errors
- TLS and SSL
- Server Architecture
- Caches, Message Queues, and Map-Reduce
- HTTP
- Screen Scraping
- Web Applications
- E-mail Composition and Decoding
- SMTP
- POP
- IMAP
- Other technologies: Telnet, SSH, and FTP
- RPC
- System Administration
Barry, P. (2011) Head First Python, O’Reilly Media
Download eBook PDF (PDF 28,877KB)
Download Source Code (ZIP 385KB)
Companion Web Site: http://www.headfirstlabs.com/books/hfpython/
Ever wished you could learn Python from a book? Head First Python is a complete learning experience for Python that helps you learn the language through a unique method that goes beyond syntax and how-to manuals, helping you understand how to be a great Python programmer. You’ll quickly learn the language’s fundamentals, then move onto persistence, exception handling, web development, SQLite, data wrangling, and Google App Engine. You’ll also learn how to write mobile apps for Android, all thanks to the power that Python gives you.
We think your time is too valuable to waste struggling with new concepts. Using the latest research in cognitive science and learning theory to craft a multi-sensory learning experience, Head First Python uses a visually rich format designed for the way your brain works, not a text-heavy approach that puts you to sleep.
- Meet Python: Everyone Loves Lists
- Sharing Your Code: Modules of Functions
- Files and Exceptions: Dealing with Errors
- Persistence: Saving Data to Files
- Comprehending Data: Work That Data!
- Custom Data Objects: Bundling Code with Data
- Web Development: Putting it All Together
- Mobile App Development: Small Devices
- Manage Your Data: Handling Input
- Scaling Your Webapp: Getting Real
- Dealing with Complexity: Data Wrangling
This is a learning experience, not a reference book. We deliberately stripped out everything that might get in the way of learning whatever it is we’re working on at that point in the book. And the first time through, you need to begin at the beginning, because the book makes assumptions about what you’ve already seen and learned.
This book is designed to get you up to speed with Python as quickly as possible.
As you need to know stuff, we teach it. So you won’t find long lists of technical material, no tables of Python’s operators, not its operator precedence rules. We don’t cover everything, but we’ve worked really hard to cover the essential material as well as we can, so that you can get Python into your brain quickly and have it stay there. The only assumption we make is that you already know how to program in some other programming language.
This book targets Python 3.
We use Release 3 of the Python programming language in this book, and we cover how to get and install Python 3 in the first chapter. That said, we don’t completely ignore Release 2, as you’ll discover in Chapters 8 through 11. But trust us, by then you’ll be so happy using Python you won’t notice that the technologies you’re programming are running Python 2.
We put Python to work for you right away
We get you doing useful stuff in Chapter 1 and build from there. There’s no hanging around, because we want you to be productive with Python right away.
The activities are NOT optional.
The exercises and activities are not add-ons; they’re part of the core content of the book. Some of them are to help with memory, some are for understanding, and some will help you apply what you’ve learned. Don’t skip the exercises.
The redundancy is intentional and important.
One distinct difference in a Head First book is that we want you to really get it. And we want you to finish the book remembering what you’ve learned. Most reference books don’t have retention and recall as a goal, but this book is about learning, so you’ll see some of the same concepts come up more than once.
The examples are as lean as possible.
Our readers tell us that it’s frustrating to wade through 200 lines of an example looking for the two lines they need to understand. Most examples in this book are shown within the smallest possible context, so that the part you’re trying to learn is clear and simple. Don’t expect all of the examples to be robust, or even complete—they are written specifically for learning, and aren’t always fully-functional.
We’ve placed a lot of the code examples on the Web so you can copy and paste them as needed. You’ll find them at two locations:
http://www.headfirstlabs.com/books/hfpython/ and http://python.itcarlow.ie
The Brain Power exercises don’t have answers.
For some of them, there is no right answer, and for others, part of the learning experience of the Brain Power activities is for you to decide if and when your answers are right. In some of the Brain Power exercises, you will find hints to point you in the right direction.
Donat, W. (2014) Learn Raspberry Pi Programming with Python, Apress
Download eBook PDF (PDF 12,990KB)
Download Source Code (ZIP 7KB)
Learn Raspberry Pi Programming with Python will show you how to program your nifty new $35 computer to make a web spider, a weather station, a media server, and more. You’ll learn how to program in Python on your Raspberry Pi with hands-on examples and fun projects.
Even if you’re completely new to programming in general, you’ll figure out how to create a home security system, an underwater photography system, an RC plane with a camera, and even a near-space weather balloon with a camera.
You’ll learn how to make a variety of fun and even useful projects, from a web bot to search and download files to a toy to drive your pets insane. You’ll even learn how to use Pi with Arduino as well as Pi with Gertboard, an expansion board with an onboard ATmega microcontroller.
- Raspberry Pi and electronics basics
- Quick intro to Linux
- Python basics to get you started on a set of projects
- How to make a variety of Pi and Python projects, including servers and gadgets with cameras
- How to use Pi with Arduino and Gertboard
Readers who want to learn Python on a fun platform like the Pi and pick up some electronics skills along the way. No programming or Linux skill required, but a little experience with Linux will be helpful.
1. Introducing the Raspberry Pi
2. Linux by the Seat of Your Pants
3. Introducing Python
4. Electronics at 100mph
5. The WebBot
6. The Weather Station
7. The Media Server
8. The Home Security System
9. The Cat Toy
10. The Radio-controlled Airplane
11. The Weather Balloon
12. The Submersible
13. The Gertboard
14. The Raspberry Pi and the Arduino
Summerfield, M. (2009) Programming in Python 3: A Complete Introduction to the Python Language (Developer’s Library), Second Edition, Addison Wesley
Download eBook PDF (PDF 7,254KB)
Download Source Code (ZIP 403KB)
Companion Web Site: https://www.qtrac.eu/py3book.html
A Fully Revised Edition Featuring New Material on Coroutines, Debugging, Testing, Parsing, String Formatting, and More
Python 3 is the best version of the language yet: It is more powerful, convenient, consistent, and expressive than ever before. Now, leading Python programmer Mark Summerfield demonstrates how to write code that takes full advantage of Python 3’s features and idioms. Programming in Python 3, Second Edition, brings together all the knowledge you need to write any program, use any standard or third-party Python 3 library, and create new library modules of your own.
Summerfield draws on his many years of Python experience to share deep insights into Python 3 development you won’t find anywhere else. He begins by illuminating Python’s “beautiful heart”: the eight key elements of Python you need to write robust, high-performance programs. Building on these core elements, he introduces new topics designed to strengthen your practical expertise–one concept and hands-on example at a time. Coverage includes
- Developing in Python using procedural, objectoriented, and functional programming paradigms
- Creating custom packages and modules
- Writing and reading binary, text, and XML files, including optional compression, random access, and text and XML parsing
- Leveraging advanced data types, collections, control structures, and functions
- Spreading program workloads across multiple processes and threads
- Programming SQL databases and key―value DBM files
- Debugging techniques–and using Test Driven Development to avoid bugs in the first place
- Utilizing Python’s regular expression mini-language and module
- Parsing techniques, including how to use the third-party PyParsing and PLY modules
- Building usable, efficient, GUI-based applications
- Advanced programming techniques, including generators, function and class decorators, context managers, descriptors, abstract base classes, metaclasses, coroutines, and more
Programming in Python 3, Second Edition, serves as both tutorial and language reference. It assumes some prior programming experience, and it is accompanied by extensive downloadable example code–all of it tested with Python 3 on Windows, Linux, and Mac OS X.
Introduction
Chapter 1: Rapid Introduction to Procedural Programming
Creating and Running Python Programs
Python’s “Beautiful Heart”
Examples
Summary
Exercises
Chapter 2: Data Types
Identifiers and Keywords
Integral Types
Floating-Point Types
Strings
Examples
Summary
Exercises
Chapter 3: Collection Data Types
Sequence Types
Set Types
Mapping Types
Iterating and Copying Collections
Examples
Summary
Exercises
Chapter 4: Control Structures and Functions
Control Structures
Exception Handling
Custom Functions
Example: make_html_skeleton.py
Summary
Exercise
Chapter 5: Modules
Modules and Packages
Overview of Python’s Standard Library
Summary
Exercise
Chapter 6: Object-Oriented Programming
The Object-Oriented Approach
Custom Classes
Custom Collection Classes
Summary
Exercises
Chapter 7: File Handling
Writing and Reading Binary Data
Writing and Parsing Text Files
Writing and Parsing XML Files
Random Access Binary Files
Summary
Exercises
Chapter 8: Advanced Programming Techniques
Further Procedural Programming
Further Object-Oriented Programming
Functional-Style Programming
Example: Valid.py
Summary
Exercises
Chapter 9: Debugging, Testing, and Profiling
Debugging
Unit Testing
Profiling
Summary
Chapter 10: Processes and Threading
Using the Multiprocessing Module
Using the Threading Module
Summary
Exercises
Chapter 11: Networking
Creating a TCP Client
Creating a TCP Server
Summary
Exercises
Chapter 12: Database Programming
DBM Databases
SQL Databases
Summary
Exercise
Chapter 13: Regular Expressions
Python’s Regular Expression Language
The Regular Expression Module
Summary
Exercises
Chapter 14: Introduction to Parsing
BNF Syntax and Parsing Terminology
Writing Handcrafted Parsers 519
Pythonic Parsing with PyParsing
Lex/Yacc-Style Parsing with PLY
Summary
Exercise
Chapter 15: Introduction to GUI Programming
Dialog-Style Programs
Main-Window-Style Programs
Summary
Exercises
Hetland, M. A. (2010) Python Algorithms Mastering Basic Algorithms in the Python Language – Learn to implement classic algorithms and design new problem-solving algorithms using Python, Apress
A newer edition is available
Download eBook (PDF 4,828KB)
Download Source Code (ZIP 29KB)
Python Algorithms, Second Edition explains the Python approach to algorithm analysis and design. Written by Magnus Lie Hetland, author of Beginning Python, this book is sharply focused on classical algorithms, but it also gives a solid understanding of fundamental algorithmic problem-solving techniques.
The book deals with some of the most important and challenging areas of programming and computer science in a highly readable manner. It covers both algorithmic theory and programming practice, demonstrating how theory is reflected in real Python programs. Well-known algorithms and data structures that are built into the Python language are explained, and the user is shown how to implement and evaluate others.
What you’ll learn
- How to transform new problems to well-known algorithmic problems with efficient solutions, or show that the problems belong to classes of problems thought not to be efficiently solvable
- How to analyze algorithms and Python programs using both mathematical tools and basic experiments and benchmarks
- How to understand several classical algorithms and data structures in depth, and be able to implement these efficiently in Python
- How to design and implement new algorithms for new problems, using time-tested design principles and techniques
- How to speed up implementations, using a plethora of tools for high-performance computing in Python
The book is intended for Python programmers who need to learn about algorithmic problem-solving, or who need a refresher. Data and computational scientists employed to do big data analytic analysis should find this book useful. Game programmers and financial analysts/engineers may find this book applicable too. And, students of computer science, or similar programming-related topics, such as bioinformatics, may also find the book to be quite useful.
Python Algorithms explains the Python approach to algorithm analysis and design. Written by Magnus Lie Hetland, author of Beginning Python, this book is sharply focused on classical algorithms, but it also gives a solid understanding of fundamental algorithmic problem-solving techniques. The book deals with some of the most important and challenging areas of programming and computer science, but in a highly pedagogic and readable manner. The book covers both algorithmic theory and programming practice, demonstrating how theory is reflected in real Python programs. Well-known algorithms and data structures that are built into the Python language are explained, and the user is shown how to implement and evaluate others himself. What you’ll learn Transform new problems to well-known algorithmic problems with efficient solutions, or show that the problems belong to classes of problems thought not to be efficiently solvable. Analyze algorithms and Python programs both using mathematical tools and basic experiments and benchmarks. Prove correctness, optimality, or bounds on approximation error for Python programs and their underlying algorithms. Understand several classical algorithms and data structures in depth, and be able to implement these efficiently in Python. Design and implement new algorithms for new problems, using time-tested design principles and techniques. Speed up implementations, using a plethora of tools for high-performance computing in Python. Who this book is for The book is intended for Python programmers who need to learn about algorithmic problem-solving, or who need a refresher. Students of Computer Science, or similar programming-related topics, such as bioinformatics, may also find the book to be quite useful.
1. Introduction
2. The Basics
3. Counting 101
4. Induction and Recursion … and Reduction
5. Traversal: The Skeleton Key of Algorithmics
6. Divide, Combine, and Conquer
7. Greed Is Good? Prove It!
8. Tangled Dependencies and Memoization
9. From A to B with Edsger and Friends
10. Matchings, Cuts, and Flows
11. Hard Problems and (Limited) Sloppiness
12. Pedal to the Metal: Accelerating Python
13. List of Problems and Algorithms
14. Graph Terminology!
15. Hints for Exercises
Garnaat, M. (2012) Python and AWS Cookbook, O’Reilly Media
Download eBook PDF (PDF 3,787KB)
Download Source Code (ZIP 76KB)
If you intend to use Amazon Web Services (AWS) for remote computing and storage, Python is an ideal programming language for developing applications and controlling your cloud-based infrastructure. This cookbook gets you started with more than two dozen recipes for using Python with AWS, based on the author’s boto library.
You’ll find detailed recipes for working with the S3 storage service as well as EC2, the service that lets you design and build cloud applications. Each recipe includes a code solution you can use immediately, along with a discussion of why and how the recipe works. You also get detailed advice for using boto with AWS and other cloud services.
This book’s recipes include methods to help you:
- Launch instances on EC2, and keep track of them with tags
- Associate an Elastic IP address with an instance
- Restore a failed Elastic Block Store volume from a snapshot
- Store and monitor your own custom metrics in CloudWatch
- Create a bucket in S3 to contain your data objects
- Reduce the cost of storing noncritical data
- Prevent accidental deletion of data in S3
Chapter 1: General Info
1.1 A Quick Note About Python
1.2 Installing boto
1.3 Getting Started with Amazon Web Services
1.4 Using boto with Eucalyptus
1.5 Using boto with Google Cloud Storage
1.6 Finding Available Regions for AWS
1.7 Enabling Debug Output with boto
1.8 Controlling Socket Timeouts in boto
Chapter 2: EC2 Recipes
2.1 Launching an Instance
2.2 Keeping Track of Instances with Tags
2.3 Accessing the Console Log
2.4 Uploading Your Own SSH Keypair
2.5 Synchronizing SSH Keypairs Across EC2 Regions
2.6 Associate an Elastic IP Address with an Instance
2.7 Attach a Persistent EBS Volume to an Instance
2.8 Back Up Your EBS Volumes
2.9 Restore a Volume from a Snapshot
2.10 Clone an Existing Instance
2.11 Find All Running EC2 Instances
2.12 Monitoring the Performance of Your Instance
2.13 Getting Notifications
2.14 Storing Custom Data in CloudWatch
2.15 Executing Custom Scripts upon Instance Startup
Chapter 3: S3 Recipes
3.1 Create a Bucket
3.2 Create a Bucket in a Specific Location
3.3 Store Private Data
3.4 Store Metadata with an Object
3.5 Computing Total Storage Used by a Bucket
3.6 Copy an Existing Object to Another Bucket
3.7 Modify the Metadata of an Existing Object
3.8 Find Out Who Is Accessing Your Data
3.9 Reduce the Cost of Storing Noncritical Data
3.10 Generating Expiring URLs for S3 Objects
3.11 Preventing Accidental Deletion of Data from S3
3.12 Hosting Static Websites on S3
3.13 Uploading Large Objects to S3|
Beazley, D. and Jones, B. K. (2013) Python Cookbook, Third Edition, O’Reilly Media, Inc.
Download eBook PDF (PDF 10,241KB)
Download Source Code (ZIP 2,355KB)
If you need help writing programs in Python 3, or want to update older Python 2 code, this book is just the ticket. Packed with practical recipes written and tested with Python 3.3, this unique cookbook is for experienced Python programmers who want to focus on modern tools and idioms.
Inside, you’ll find complete recipes for more than a dozen topics, covering the core Python language as well as tasks common to a wide variety of application domains. Each recipe contains code samples you can use in your projects right away, along with a discussion about how and why the solution works.
Topics include:
- Data Structures and Algorithms
- Strings and Text
- Numbers, Dates, and Times
- Iterators and Generators
- Files and I/O
- Data Encoding and Processing
- Functions
- Classes and Objects
- Metaprogramming
- Modules and Packages
- Network and Web Programming
- Concurrency
- Utility Scripting and System Administration
- Testing, Debugging, and Exceptions
- C Extensions
- Chapter 1 Data Structures and Algorithms
- Unpacking a Sequence into Separate Variables
- Unpacking Elements from Iterables of Arbitrary Length
- Keeping the Last N Items
- Finding the Largest or Smallest N Items
- Implementing a Priority Queue
- Mapping Keys to Multiple Values in a Dictionary
- Keeping Dictionaries in Order
- Calculating with Dictionaries
- Finding Commonalities in Two Dictionaries
- Removing Duplicates from a Sequence while Maintaining Order
- Naming a Slice
- Determining the Most Frequently Occurring Items in a Sequence
- Sorting a List of Dictionaries by a Common Key
- Sorting Objects Without Native Comparison Support
- Grouping Records Together Based on a Field
- Filtering Sequence Elements
- Extracting a Subset of a Dictionary
- Mapping Names to Sequence Elements
- Transforming and Reducing Data at the Same Time
- Combining Multiple Mappings into a Single Mapping
- Chapter 2 Strings and Text
- Splitting Strings on Any of Multiple Delimiters
- Matching Text at the Start or End of a String
- Matching Strings Using Shell Wildcard Patterns
- Matching and Searching for Text Patterns
- Searching and Replacing Text
- Searching and Replacing Case-Insensitive Text
- Specifying a Regular Expression for the Shortest Match
- Writing a Regular Expression for Multiline Patterns
- Normalizing Unicode Text to a Standard Representation
- Working with Unicode Characters in Regular Expressions
- Stripping Unwanted Characters from Strings
- Sanitizing and Cleaning Up Text
- Aligning Text Strings
- Combining and Concatenating Strings
- Interpolating Variables in Strings
- Reformatting Text to a Fixed Number of Columns
- Handling HTML and XML Entities in Text
- Tokenizing Text
- Writing a Simple Recursive Descent Parser
- Performing Text Operations on Byte Strings
- Chapter 3 Numbers, Dates, and Times
- Rounding Numerical Values
- Performing Accurate Decimal Calculations
- Formatting Numbers for Output
- Working with Binary, Octal, and Hexadecimal Integers
- Packing and Unpacking Large Integers from Bytes
- Performing Complex-Valued Math
- Working with Infinity and NaNs
- Calculating with Fractions
- Calculating with Large Numerical Arrays
- Performing Matrix and Linear Algebra Calculations
- Picking Things at Random
- Converting Days to Seconds, and Other Basic Time Conversions
- Determining Last Friday’s Date
- Finding the Date Range for the Current Month
- Converting Strings into Datetimes
- Manipulating Dates Involving Time Zones
- Chapter 4 Iterators and Generators
- Manually Consuming an Iterator
- Delegating Iteration
- Creating New Iteration Patterns with Generators
- Implementing the Iterator Protocol
- Iterating in Reverse
- Defining Generator Functions with Extra State
- Taking a Slice of an Iterator
- Skipping the First Part of an Iterable
- Iterating Over All Possible Combinations or Permutations
- Iterating Over the Index-Value Pairs of a Sequence
- Iterating Over Multiple Sequences Simultaneously
- Iterating on Items in Separate Containers
- Creating Data Processing Pipelines
- Flattening a Nested Sequence
- Iterating in Sorted Order Over Merged Sorted Iterables
- Replacing Infinite while Loops with an Iterator
- Chapter 5 Files and I/O
- Reading and Writing Text Data
- Printing to a File
- Printing with a Different Separator or Line Ending
- Reading and Writing Binary Data
- Writing to a File That Doesn’t Already Exist
- Performing I/O Operations on a String
- Reading and Writing Compressed Datafiles
- Iterating Over Fixed-Sized Records
- Reading Binary Data into a Mutable Buffer
- Memory Mapping Binary Files
- Manipulating Pathnames
- Testing for the Existence of a File
- Getting a Directory Listing
- Bypassing Filename Encoding
- Printing Bad Filenames
- Adding or Changing the Encoding of an Already Open File
- Writing Bytes to a Text File
- Wrapping an Existing File Descriptor As a File Object
- Making Temporary Files and Directories
- Communicating with Serial Ports
- Serializing Python Objects
- Chapter 6 Data Encoding and Processing
- Reading and Writing CSV Data
- Reading and Writing JSON Data
- Parsing Simple XML Data
- Parsing Huge XML Files Incrementally
- Turning a Dictionary into XML
- Parsing, Modifying, and Rewriting XML
- Parsing XML Documents with Namespaces
- Interacting with a Relational Database
- Decoding and Encoding Hexadecimal Digits
- Decoding and Encoding Base64
- Reading and Writing Binary Arrays of Structures
- Reading Nested and Variable-Sized Binary Structures
- Summarizing Data and Performing Statistics
- Chapter 7 Functions
- Writing Functions That Accept Any Number of Arguments
- Writing Functions That Only Accept Keyword Arguments
- Attaching Informational Metadata to Function Arguments
- Returning Multiple Values from a Function
- Defining Functions with Default Arguments
- Defining Anonymous or Inline Functions
- Capturing Variables in Anonymous Functions
- Making an N-Argument Callable Work As a Callable with Fewer Arguments
- Replacing Single Method Classes with Functions
- Carrying Extra State with Callback Functions
- Inlining Callback Functions
- Accessing Variables Defined Inside a Closure
- Chapter 8 Classes and Objects
- Changing the String Representation of Instances
- Customizing String Formatting
- Making Objects Support the Context-Management Protocol
- Saving Memory When Creating a Large Number of Instances
- Encapsulating Names in a Class
- Creating Managed Attributes
- Calling a Method on a Parent Class
- Extending a Property in a Subclass
- Creating a New Kind of Class or Instance Attribute
- Using Lazily Computed Properties
- Simplifying the Initialization of Data Structures
- Defining an Interface or Abstract Base Class
- Implementing a Data Model or Type System
- Implementing Custom Containers
- Delegating Attribute Access
- Defining More Than One Constructor in a Class
- Creating an Instance Without Invoking init
- Extending Classes with Mixins
- Implementing Stateful Objects or State Machines
- Calling a Method on an Object Given the Name As a String
- Implementing the Visitor Pattern
- Implementing the Visitor Pattern Without Recursion
- Managing Memory in Cyclic Data Structures
- Making Classes Support Comparison Operations
- Creating Cached Instances
- Chapter 9 Metaprogramming
- Putting a Wrapper Around a Function
- Preserving Function Metadata When Writing Decorators
- Unwrapping a Decorator
- Defining a Decorator That Takes Arguments
- Defining a Decorator with User Adjustable Attributes
- Defining a Decorator That Takes an Optional Argument
- Enforcing Type Checking on a Function Using a Decorator
- Defining Decorators As Part of a Class
- Defining Decorators As Classes
- Applying Decorators to Class and Static Methods
- Writing Decorators That Add Arguments to Wrapped Functions
- Using Decorators to Patch Class Definitions
- Using a Metaclass to Control Instance Creation
- Capturing Class Attribute Definition Order
- Defining a Metaclass That Takes Optional Arguments
- Enforcing an Argument Signature on *args and **kwargs
- Enforcing Coding Conventions in Classes
- Defining Classes Programmatically
- Initializing Class Members at Definition Time
- Implementing Multiple Dispatch with Function Annotations
- Avoiding Repetitive Property Methods
- Defining Context Managers the Easy Way
- Executing Code with Local Side Effects
- Parsing and Analyzing Python Source
- Disassembling Python Byte Code
- Chapter 10 Modules and Packages
- Making a Hierarchical Package of Modules
- Controlling the Import of Everything
- Importing Package Submodules Using Relative Names
- Splitting a Module into Multiple Files
- Making Separate Directories of Code Import Under a Common Namespace
- Reloading Modules
- Making a Directory or Zip File Runnable As a Main Script
- Reading Datafiles Within a Package
- Adding Directories to sys.path
- Importing Modules Using a Name Given in a String
- Loading Modules from a Remote Machine Using Import Hooks
- Patching Modules on Import
- Installing Packages Just for Yourself
- Creating a New Python Environment
- Distributing Packages
- Chapter 11 Network and Web Programming
- Interacting with HTTP Services As a Client
- Creating a TCP Server
- Creating a UDP Server
- Generating a Range of IP Addresses from a CIDR Address
- Creating a Simple REST-Based Interface
- Implementing a Simple Remote Procedure Call with XML-RPC
- Communicating Simply Between Interpreters
- Implementing Remote Procedure Calls
- Authenticating Clients Simply
- Adding SSL to Network Services
- Passing a Socket File Descriptor Between Processes
- Understanding Event-Driven I/O
- Sending and Receiving Large Arrays
- Chapter 12 Concurrency
- Starting and Stopping Threads
- Determining If a Thread Has Started
- Communicating Between Threads
- Locking Critical Sections
- Locking with Deadlock Avoidance
- Storing Thread-Specific State
- Creating a Thread Pool
- Performing Simple Parallel Programming
- Dealing with the GIL (and How to Stop Worrying About It)
- Defining an Actor Task
- Implementing Publish/Subscribe Messaging
- Using Generators As an Alternative to Threads
- Polling Multiple Thread Queues
- Launching a Daemon Process on Unix
- Chapter 13 Utility Scripting and System Administration
- Accepting Script Input via Redirection, Pipes, or Input Files
- Terminating a Program with an Error Message
- Parsing Command-Line Options
- Prompting for a Password at Runtime
- Getting the Terminal Size
- Executing an External Command and Getting Its Output
- Copying or Moving Files and Directories
- Creating and Unpacking Archives
- Finding Files by Name
- Reading Configuration Files
- Adding Logging to Simple Scripts
- Adding Logging to Libraries
- Making a Stopwatch Timer
- Putting Limits on Memory and CPU Usage
- Launching a Web Browser
- Chapter 14 Testing, Debugging, and Exceptions
- Testing Output Sent to stdout
- Patching Objects in Unit Tests
- Testing for Exceptional Conditions in Unit Tests
- Logging Test Output to a File
- Skipping or Anticipating Test Failures
- Handling Multiple Exceptions
- Catching All Exceptions
- Creating Custom Exceptions
- Raising an Exception in Response to Another Exception
- Reraising the Last Exception
- Issuing Warning Messages
- Debugging Basic Program Crashes
- Profiling and Timing Your Program
- Making Your Programs Run Faster
- Chapter 15 C Extensions
- Accessing C Code Using ctypes
- Writing a Simple C Extension Module
- Writing an Extension Function That Operates on Arrays
- Managing Opaque Pointers in C Extension Modules
- Defining and Exporting C APIs from Extension Modules
- Calling Python from C
- Releasing the GIL in C Extensions
- Mixing Threads from C and Python
- Wrapping C Code with Swig
- Wrapping Existing C Code with Cython
- Using Cython to Write High-Performance Array Operations
- Turning a Function Pointer into a Callable
- Passing NULL-Terminated Strings to C Libraries
- Passing Unicode Strings to C Libraries
- Converting C Strings to Python
- Working with C Strings of Dubious Encoding
- Passing Filenames to C Extensions
- Passing Open Files to C Extensions
- Reading File-Like Objects from C
- Consuming an Iterable from C
- Diagnosing Segmentation Faults
- Appendix Further Reading
- Online Resources
- Books for Learning Python
- Advanced Books
McKinney, W. (2012) Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython, O’Reilly Media
Download eBook PDF (PDF 16,407KB)
Download Source Code (ZIP 41,003KB)
Python for Data Analysis is concerned with the nuts and bolts of manipulating, processing, cleaning, and crunching data in Python. It is also a practical, modern introduction to scientific computing in Python, tailored for data-intensive applications. This is a book about the parts of the Python language and libraries you’ll need to effectively solve a broad set of data analysis problems. This book is not an exposition on analytical methods using Python as the implementation language.
Written by Wes McKinney, the main author of the pandas library, this hands-on book is packed with practical cases studies. It’s ideal for analysts new to Python and for Python programmers new to scientific computing.
- Use the IPython interactive shell as your primary development environment
- Learn basic and advanced NumPy (Numerical Python) features
- Get started with data analysis tools in the pandas library
- Use high-performance tools to load, clean, transform, merge, and reshape data
- Create scatter plots and static or interactive visualizations with matplotlib
- Apply the pandas groupby facility to slice, dice, and summarize datasets
- Measure data by points in time, whether it’s specific instances, fixed periods, or intervals
- Learn how to solve problems in web analytics, social sciences, finance, and economics, through detailed examples
- Chapter 1 Preliminaries
- What Is This Book About?
- Why Python for Data Analysis?
- Essential Python Libraries
- Installation and Setup
- Community and Conferences
- Navigating This Book
- Acknowledgements
- Chapter 2 Introductory Examples
- 1.usa.gov data from bit.ly
- MovieLens 1M Data Set
- US Baby Names 1880-2010
- Conclusions and The Path Ahead
- Chapter 3 IPython: An Interactive Computing and Development Environment
- IPython Basics
- Using the Command History
- Interacting with the Operating System
- Software Development Tools
- IPython HTML Notebook
- Tips for Productive Code Development Using IPython
- Advanced IPython Features
- Credits
- Chapter 4 NumPy Basics: Arrays and Vectorized Computation
- The NumPy ndarray: A Multidimensional Array Object
- Universal Functions: Fast Element-wise Array Functions
- Data Processing Using Arrays
- File Input and Output with Arrays
- Linear Algebra
- Random Number Generation
- Example: Random Walks
- Chapter 5 Getting Started with pandas
- Introduction to pandas Data Structures
- Essential Functionality
- Summarizing and Computing Descriptive Statistics
- Handling Missing Data
- Hierarchical Indexing
- Other pandas Topics
- Chapter 6 Data Loading, Storage, and File Formats
- Reading and Writing Data in Text Format
- Binary Data Formats
- Interacting with HTML and Web APIs
- Interacting with Databases
- Chapter 7 Data Wrangling: Clean, Transform, Merge, Reshape
- Combining and Merging Data Sets
- Reshaping and Pivoting
- Data Transformation
- String Manipulation
- Example: USDA Food Database
- Chapter 8 Plotting and Visualization
- A Brief matplotlib API Primer
- Plotting Functions in pandas
- Plotting Maps: Visualizing Haiti Earthquake Crisis Data
- Python Visualization Tool Ecosystem
- Chapter 9 Data Aggregation and Group Operations
- GroupBy Mechanics
- Data Aggregation
- Group-wise Operations and Transformations
- Pivot Tables and Cross-Tabulation
- Example: 2012 Federal Election Commission Database
- Chapter 10 Time Series
- Date and Time Data Types and Tools
- Time Series Basics
- Date Ranges, Frequencies, and Shifting
- Time Zone Handling
- Periods and Period Arithmetic
- Resampling and Frequency Conversion
- Time Series Plotting
- Moving Window Functions
- Performance and Memory Usage Notes
- Chapter 11 Financial and Economic Data Applications
- Data Munging Topics
- Group Transforms and Analysis
- More Example Applications
- Chapter 12 Advanced NumPy
- ndarray Object Internals
- Advanced Array Manipulation
- Broadcasting
- Advanced ufunc Usage
- Structured and Record Arrays
- More About Sorting
- NumPy Matrix Class
- Advanced Array Input and Output
- Performance Tips
- Appendix Python Language Essentials
- The Python Interpreter
- The Basics
- Data Structures and Sequences
- Functions
- Files and the operating system
Cox, T. (2014) Raspberry Pi Cookbook for Python Programmers, PACKT Publishing
Download eBook PDF (PDF 31,269KB)
Download Source Code (ZIP 2,300KB)
Over 50 easy to comprehend tailor made recipes to get the most out of the Raspberry Pi and unleash its huge potential using Python About This Book Install your first operating system, share files over the network, and run programs remotely Unleash the hidden potential of the Raspberry Pi’s powerful Video Core IV graphics processor with your own hardware accelerated 3D graphics Discover how to create your own electronic circuits to interact with the Raspberry Pi Interface with purpose-built add-ons and adapt off-the-shelf household devices Who This Book Is For The aim of this book is to bring you a broad range of Python 3 examples and practical ideas which you can develop to suit your own requirements. By modifying and combining the examples to create your own projects you learn far more effectively with a much greater understanding. Each chapter is designed to become a foundation for further experimentation and discovery of the topic, providing you with the tools and information to jump right in. Readers are expected to be familiar with programming concepts and Python (where possible Python 3 is used), although beginners should manage with the help of a good Python reference book and background reading. No prior knowledge of the Raspberry Pi or electronics is required; however for the hardware sections you will need some basic electronic components/household tools to build some of the projects. What You Will Learn Set up and run Raspberry Pi for the first time Develop desktop applications, and handle images and process files with ease Make use of graphics and user control to develop your own exciting games Create 3D worlds by using the Raspberry Pi’s powerful GPU Discover how to create your own electronic circuits to interact with the Raspberry Pi Use the Raspberry Pi Camera to create animations and time lapses Design and build your own Raspberry Pi controlled robots Take control of the real world and interface
The Raspberry Pi foundation has been selling their computers since 2012 with the aim of inspiring programmers and engineers.
Raspberry Pi Cookbook for Python Programmers is a practical guide for getting the most out of this little computer. It will guide you through the many uses of the Raspberry Pi and allow you to showcase the best it has to offer. Discover what the Raspberry Pi has to offer using detailed Python 3 examples that you can adapt and extend; see where your creativity takes you!
“Raspberry Pi Cookbook for Python Programmers” begins by guiding you through setting up the Raspberry Pi, performing tasks using Python 3 and introduces the first steps to interface with electronics. As you work through each chapter you will build up your skills and knowledge and apply them as you progress throughout the book, delving further and further into the unique abilities and features of the Raspberry Pi.
Later, you will learn how to automate tasks by accessing files, build applications using the popular Tkinter library and create games by controlling graphics on screen. You will harness the power of the built-in graphics processor by using Pi3D to generate your own high quality 3D graphics and environments. Connect directly to the Raspberry Pi’s hardware pins to control electronics from switching on LEDs and responding to push buttons right through to driving motors and servos. Learn how to monitor sensors to gather real-life data and use it to control other devices, and view the results over the Internet. Apply what you have learnt by creating your own Pi-Rover or Pi-Hexipod robots. Finally, we will explore using many of the purpose-built add-ons available for the Raspberry Pi, as well as interfacing with common household devices in new ways.
The “Raspberry Pi Cookbook for Python Programmers” will allow you to discover the vast range of abilities this micro-computer has. By following the clear examples you can pick up many new skills and arm yourself with the tools to create your own exciting and interesting projects.
What You Will Learn
- Set up and run Raspberry Pi for the first time
- Develop desktop applications, and handle images and process files with ease
- Make use of graphics and user control to develop your own exciting games
- Create 3D worlds by using the Raspberry Pi’s powerful GPU
- Discover how to create your own electronic circuits to interact with the Raspberry Pi
- Use the Raspberry Pi Camera to create animations and timelapses
- Design and build your own Raspberry Pi controlled robots
- Take control of the real world and interface with physical hardware, combining hardware and software for your own needs