Get Programming: Learn to code with Python
By Ana Bell
()
About this ebook
This book works perfectly alongside our video course Get Programming with Python in Motion, available exclusively at Manning.com: www.manning.com/livevideo/get-programming-with-python-in-motion
Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications.
What's Inside
- Programming skills you can use in any language
- Learn to code—no experience required
- Learn Python, the language for beginners
- Dozens of exercises and examples help you learn by doing
About the Reader
No prior programming experience needed.
Table of Contents
LEARNING HOW TO PROGRAM
Lesson 1 - Why should you learn how to program?
Lesson 2 - Basic principles of learning a programming language
UNIT 1 - VARIABLES, TYPES, EXPRESSIONS, AND STATEMENTS
Lesson 3 - Introducing Python: a programming language
Lesson 4 - Variables and expressions: giving names and values to things
Lesson 5 - Object types and statements of code 46
Lesson 6 - Capstone project: your first Python program-convert hours to minutes
UNIT 2 - STRINGS, TUPLES, AND INTERACTING WITH THE USER
Lesson 7 - Introducing string objects: sequences of characters
Lesson 8 - Advanced string operations
Lesson 9 - Simple error messages
Lesson 10 - Tuple objects: sequences of any kind of object
Lesson 11 - Interacting with the user
Lesson 12 - Capstone project: name mashup
UNIT 3 - MAKING DECISIONS IN YOUR PROGRAMS
Lesson 13 - Introducing decisions in programs
Lesson 14 - Making more-complicated decisions
Lesson 15 - Capstone project: choose your own adventure
UNIT 4 - REPEATING TASKS
Lesson 16 - Repeating tasks with loops
Lesson 17 - Customizing loops
Lesson 18 - Repeating tasks while conditions hold
Lesson 19 - Capstone project: Scrabble, Art Edition
UNIT 5 - ORGANIZING YOUR CODE INTO REUSABLE BLOCKS
Lesson 20 - Building programs to last
Lesson 21 - Achieving modularity and abstraction with functions
Lesson 22 - Advanced operations with functions
Lesson 23 - Capstone project: analyze your friends
UNIT 6 - WORKING WITH MUTABLE DATA TYPES
Lesson 24 - Mutable and immutable objects
Lesson 25 - Working with lists
Lesson 26 - Advanced operations with lists
Lesson 27 - Dictionaries as maps between objects
Lesson 28 - Aliasing and copying lists and dictionaries
Lesson 29 - Capstone project: document similarity
UNIT 7 - MAKING YOUR OWN OBJECT TYPES BY USING OBJECT-ORIENTED PROGRAMMING
Lesson 30 - Making your own object types
Lesson 31 - Creating a class for an object type
Lesson 32 - Working with your own object types
Lesson 33 - Customizing classes
Lesson 34 - Capstone project: card game
UNIT 8 - USING LIBRARIES TO ENHANCE YOUR PROGRAMS
Lesson 35 - Useful libraries
Lesson 36 - Testing and debugging your programs
Lesson 37 - A library for graphical user interfaces
Lesson 38 - Capstone project: game of tag
Appendix A - Answers to lesson exercises
Appendix B - Python cheat sheet
Appendix C - Interesting Python libraries
Ana Bell
Ana Bell is an MIT lecturer and scientist who teaches the popular course, Introduction to Computer Science and Programming Using Python.
Related to Get Programming
Related ebooks
Tiny Python Projects: Learn coding and testing with puzzles and games Rating: 4 out of 5 stars4/5Python Workout: 50 ten-minute exercises Rating: 0 out of 5 stars0 ratingsThe Quick Python Book Rating: 0 out of 5 stars0 ratingsClassic Computer Science Problems in Python Rating: 0 out of 5 stars0 ratingsPractices of the Python Pro Rating: 0 out of 5 stars0 ratingsMath for Programmers: 3D graphics, machine learning, and simulations with Python Rating: 4 out of 5 stars4/5Python 3 Object Oriented Programming Rating: 4 out of 5 stars4/5Hello World! Third Edition: Computer Programming for Kids and Other Beginners Rating: 0 out of 5 stars0 ratingsGet Programming with JavaScript Rating: 0 out of 5 stars0 ratingsReal-World Functional Programming: With examples in F# and C# Rating: 0 out of 5 stars0 ratingsiOS Development with Swift Rating: 0 out of 5 stars0 ratingsFunctional Programming in Java: How functional techniques improve your Java programs Rating: 0 out of 5 stars0 ratingsDeep Learning with JavaScript: Neural networks in TensorFlow.js Rating: 0 out of 5 stars0 ratingsPython Handbook For Beginners. A Hands-On Crash Course For Kids, Newbies and Everybody Else Rating: 0 out of 5 stars0 ratingsIntroduction to Python 2018 Edition Rating: 4 out of 5 stars4/5Think Like a Data Scientist: Tackle the data science process step-by-step Rating: 0 out of 5 stars0 ratingsPython from the Very Beginning Rating: 0 out of 5 stars0 ratingsPython GUI Programming Cookbook - Second Edition Rating: 5 out of 5 stars5/5Adventures in Python Rating: 0 out of 5 stars0 ratingsLearn Python in One Hour: Programming by Example Rating: 3 out of 5 stars3/5Learning Python Rating: 5 out of 5 stars5/5Web Scraping with Python Rating: 4 out of 5 stars4/5Python Projects for Beginners: A Ten-Week Bootcamp Approach to Python Programming Rating: 0 out of 5 stars0 ratingsPython: Programming for Intermediates: Learn the Fundamentals of Python in 7 Days Rating: 4 out of 5 stars4/5Python: Journey from Novice to Expert Rating: 5 out of 5 stars5/5Mastering Python Regular Expressions Rating: 5 out of 5 stars5/5An Introduction to Statistics with Python: With Applications in the Life Sciences Rating: 0 out of 5 stars0 ratings
Programming For You
Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5C Programming For Beginners: The Simple Guide to Learning C Programming Language Fast! Rating: 5 out of 5 stars5/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. 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/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/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 ratingsBeginning Programming with C++ For Dummies Rating: 4 out of 5 stars4/5Coding with JavaScript For Dummies Rating: 0 out of 5 stars0 ratingsNarrative Design for Indies: Getting Started Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5C# 7.0 All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsExcel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5C All-in-One Desk Reference For Dummies Rating: 5 out of 5 stars5/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5C Programming for Beginners: Your Guide to Easily Learn C Programming In 7 Days Rating: 4 out of 5 stars4/5
Reviews for Get Programming
0 ratings0 reviews
Book preview
Get Programming - Ana Bell
Copyright
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact
Special Sales Department
Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964
Email:
orders@manning.com
©2018 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine.
Development editor: Elesha Hyde
Tecchnical development editor: Frances Buontempo
Review editor: Aleksandar Dragosavljević
Project editor: David Novak
Copy editor: Sharon Wilkey
Proofreader: Melody Dolab
Technical proofreader: Ignacio Beltran Torres
Typesetter: Dottie Marsico
Cover designer: Monica Kamsvaag
ISBN 9781617293788
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – EBM – 23 22 21 20 19 18
Dedication
To my sons, James and Thomas
Brief Table of Contents
Copyright
Brief Table of Contents
Table of Contents
Preface
Acknowledgments
About this Book
About the author
Unit 0. Learning how to program
Lesson 1. Why should you learn how to program?
Lesson 2. Basic principles of learning a programming language
Unit 1. Variables, types, expressions, and statements
Lesson 3. Introducing Python: a programming language
Lesson 4. Variables and expressions: giving names and values to things
Lesson 5. Object types and statements of code
Lesson 6. Capstone project: your first Python program—convert hours to minutes
Unit 2. Strings, tuples, and interacting with the user
Lesson 7. Introducing string objects: sequences of characters
Lesson 8. Advanced string operations
Lesson 9. Simple error messages
Lesson 10. Tuple objects: sequences of any kind of object
Lesson 11. Interacting with the user
Lesson 12. Capstone project: name mashup
Unit 3. Making decisions in your programs
Lesson 13. Introducing decisions in programs
Lesson 14. Making more-complicated decisions
Lesson 15. Capstone project: choose your own adventure
Unit 4. Repeating tasks
Lesson 16. Repeating tasks with loops
Lesson 17. Customizing loops
Lesson 18. Repeating tasks while conditions hold
Lesson 19. Capstone project: Scrabble, Art Edition
Unit 5. Organizing your code into reusable blocks
Lesson 20. Building programs to last
Lesson 21. Achieving modularity and abstraction with functions
Lesson 22. Advanced operations with functions
Lesson 23. Capstone project: analyze your friends
Unit 6. Working with mutable data types
Lesson 24. Mutable and immutable objects
Lesson 25. Working with lists
Lesson 26. Advanced operations with lists
Lesson 27. Dictionaries as maps between objects
Lesson 28. Aliasing and copying lists and dictionaries
Lesson 29. Capstone project: document similarity
Unit 7. Making your own object types by using object-oriented programming
Lesson 30. Making your own object types
Lesson 31. Creating a class for an object type
Lesson 32. Working with your own object types
Lesson 33. Customizing classes
Lesson 34. Capstone project: card game
Unit 8. Using libraries to enhance your programs
Lesson 35. Useful libraries
Lesson 36. Testing and debugging your programs
Lesson 37. A library for graphical user interfaces
Lesson 38. Capstone project: game of tag
Appendix A. Answers to lesson exercises
Appendix B. Python cheat sheet
Appendix C. Interesting Python libraries
Thinking like a programmer: big ideas
Index
List of Figures
List of Tables
List of Listings
Table of Contents
Copyright
Brief Table of Contents
Table of Contents
Preface
Acknowledgments
About this Book
About the author
Unit 0. Learning how to program
Lesson 1. Why should you learn how to program?
1.1. Why programming matters
1.1.1. Programming isn’t just for professionals
1.1.2. Improve your life
1.1.3. Challenge yourself
1.2. Where you are now and where you’ll be
1.3. Our plan for learning how to program
1.3.1. First steps
1.3.2. Practice, practice, practice, practice
1.3.3. Think like a programmer
Summary
Lesson 2. Basic principles of learning a programming language
2.1. Programming as a skill
2.2. A parallel with baking
2.2.1. Understand the task bake a loaf of bread
2.2.2. Find a recipe
2.2.3. Visualize the recipe with flowcharts
2.2.4. Use an existing recipe or make one up?
2.3. Think, code, test, debug, repeat
2.3.1. Understanding the task
2.3.2. Visualizing the task
2.3.3. Writing pseudocode
2.4. Writing readable code
2.4.1. Using descriptive and meaningful names
2.4.2. Commenting your code
Summary
Unit 1. Variables, types, expressions, and statements
Lesson 3. Introducing Python: a programming language
3.1. Installing Python
3.1.1. What is Python?
3.1.2. Downloading Python version 3.5
3.1.3. Anaconda Python Distribution
3.1.4. Integrated development environments
3.2. Setting up your workspace
3.2.1. The IPython console
3.2.2. The file editor
Summary
Lesson 4. Variables and expressions: giving names and values to things
4.1. Giving names to things
4.1.1. Math vs. programming
4.1.2. What the computer can and can’t do
4.2. Introducing variables
4.2.1. Objects are things that can be manipulated
4.2.2. Objects have names
4.2.3. What object names are allowed?
4.2.4. Creating a variable
4.2.5. Updating a variable
Summary
Lesson 5. Object types and statements of code
5.1. Types of things
5.2. Basic type of objects in programming
5.2.1. Integers as whole numbers
5.2.2. Floating point as decimal numbers
5.2.3. Booleans as true/false data
5.2.4. Strings as sequences of characters
5.2.5. The absence of a value
5.3. Working with basic types of data values
5.3.1. Building blocks of expressions
5.3.2. Converting between different types
5.3.3. How arithmetic impacts object types
Summary
Lesson 6. Capstone project: your first Python program—convert hours to minutes
6.1. Think-code-test-debug-repeat
6.2. Divide your task
Code to set up the input
Code to set up the output
6.3. Implement the conversion formula
6.3.1. How many hours?
6.3.2. How many minutes?
6.4. Your first Python program: one solution
6.5. Your first Python program: another solution
Summary
Unit 2. Strings, tuples, and interacting with the user
Lesson 7. Introducing string objects: sequences of characters
7.1. Strings as sequences of characters
7.2. Basic operations on strings
7.2.1. Creating a string object
7.2.2. Understanding indexing into a string
7.2.3. Understanding slicing a string
7.3. Other operations on string objects
7.3.1. Getting the number of characters in a string with len()
7.3.2. Converting between letter cases with upper() and lower()
Summary
Lesson 8. Advanced string operations
8.1. Operations related to substrings
8.1.1. Find a specific substring in a string with find()
8.1.2. Find out whether a substring is in the string with in
8.1.3. Count the number of times a substring occurs with count()
8.1.4. Replace substrings with replace()
8.2. Mathematical operations
Summary
Lesson 9. Simple error messages
9.1. Typing up statements and trying things out
9.2. Understanding string error messages
Summary
Lesson 10. Tuple objects: sequences of any kind of object
10.1. Tuples as sequences of data
10.1.1. Creating tuple objects
10.2. Understanding operations on tuples
10.2.1. Getting the tuple length with len()
10.2.2. Indexing into and slicing a tuple with []
10.2.3. Performing mathematical operations
10.2.4. Swapping objects inside tuples
Summary
Lesson 11. Interacting with the user
11.1. Showing output
11.1.1. Printing expressions
11.1.2. Printing multiple objects
11.2. Getting user input
11.2.1. Prompting the user
11.2.2. Reading the input
11.2.3. Storing the input in a variable
11.2.4. Converting the user input to a different type
11.2.5. Asking for more input
Summary
Lesson 12. Capstone project: name mashup
12.1. Understanding the problem statement
12.1.1. Drawing a sketch of the problem
12.1.2. Coming up with a few examples
12.1.3. Abstracting the problem into pseudocode
12.2. Splitting up first and last names
12.2.1. Finding the space between the first and last name
12.2.2. Using variables to save calculated values
12.2.3. Testing what you have so far
12.3. Storing the halves of all names
12.3.1. Finding the midpoint of names
12.4. Combining the halves
Summary
Unit 3. Making decisions in your programs
Lesson 13. Introducing decisions in programs
13.1. Making decisions with conditionals
13.1.1. Yes/no questions and true/false statements
13.1.2. Adding a condition to a statement
13.2. Writing the code to make the decision
13.2.1. Coding up a decision—an example
13.2.2. Coding up a decision—a general way
13.3. Structuring your programs
13.3.1. Making many decisions
13.3.2. Making decisions based on another decision’s outcomes
13.3.3. A more complicated example with nested conditionals
Summary
Lesson 14. Making more-complicated decisions
14.1. Combining multiple conditions
14.1.1. Conditionals are made up of true/false expressions
14.1.2. Operator precedence rules
14.2. Choosing which lines to execute
14.2.1. Do this or that
14.2.2. Putting it all together
14.2.3. Thinking in terms of code blocks
Summary
Lesson 15. Capstone project: choose your own adventure
15.1. Outlining the game rules
15.2. Creating different paths
15.3. More choices? Yes, please!
Summary
Unit 4. Repeating tasks
Lesson 16. Repeating tasks with loops
16.1. Repeating a task
16.1.1. Adding nonlinearity to programs
16.1.2. Infinite repetitions
16.2. Looping a certain number of times
16.2.1. for loops
16.3. Looping N times
16.3.1. Loops over the common sequence 0 to N – 1
16.3.2. Unrolling loops
Summary
Lesson 17. Customizing loops
17.1. Customizing loops
17.2. Looping over strings
Summary
Lesson 18. Repeating tasks while conditions hold
18.1. Looping while a condition is true
18.1.1. Looping to make a guess
18.1.2. while loops
18.1.3. Infinite loop
18.2. Using for loops vs. while loops
18.3. Manipulating loops
18.3.1. Exiting early out of a loop
18.3.2. Going to the beginning of a loop
Summary
Lesson 19. Capstone project: Scrabble, Art Edition
19.1. Understanding the problem statement
19.1.1. Change the representation of all valid words
19.1.2. Making a valid word with the given tiles
19.2. Dividing your code into pieces
Summary
Unit 5. Organizing your code into reusable blocks
Lesson 20. Building programs to last
20.1. Breaking a big task into smaller tasks
20.1.1. Ordering an item online
20.1.2. Understanding the main points
20.2. Introducing black boxes of code in programming
20.2.1. Using code modules
20.2.2. Abstracting code
20.2.3. Reusing code
20.3. Subtasks exist in their own environments
Summary
Lesson 21. Achieving modularity and abstraction with functions
21.1. Writing a function
21.1.1. Function basics: what the function takes in
21.1.2. Function basics: what the function does
21.1.3. Function basics: what the function returns
21.2. Using functions
21.2.1. Returning more than one value
21.2.2. Functions without a return statement
21.3. Documenting your functions
Summary
Lesson 22. Advanced operations with functions
22.1. Thinking about functions with two hats
22.1.1. Writer hat
22.1.2. User hat
22.2. Function scope
22.2.1. Simple scoping example
22.2.2. Scoping rules
22.3. Nesting functions
22.4. Passing functions as parameters
22.5. Returning a function
22.6. Summary
Lesson 23. Capstone project: analyze your friends
23.1. Reading a file
23.1.1. File format
23.1.2. The newline character
23.1.3. Remove the newline character
23.1.4. Using tuples to store information
23.1.5. What to return
23.2. Sanitizing user inputs
23.3. Testing and debugging what you have so far
23.3.1. File objects
23.3.2. Writing a text file with names and phone numbers
23.3.3. Opening files for reading
23.4. Reusing functions
23.5. Analyzing the information
23.5.1. The specification
23.5.2. Helper functions
Summary
Unit 6. Working with mutable data types
Lesson 24. Mutable and immutable objects
24.1. Immutable objects
24.2. The need for mutability
Summary
Lesson 25. Working with lists
25.1. Lists vs. tuples
25.2. Creating lists and getting elements at specific positions
25.3. Counting and getting positions of elements
25.4. Adding items to lists: append, insert, and extend
25.4.1. Using append
25.4.2. Using insert
25.4.3. Using extend
25.5. Removing items from a list: pop
25.6. Changing an element value
Summary
Lesson 26. Advanced operations with lists
26.1. Sorting and reversing lists
26.2. Lists of lists
26.3. Converting a string to a list
26.4. Applications of lists
26.4.1. Stacks
26.4.2. Queues
Summary
Lesson 27. Dictionaries as maps between objects
27.1. Creating dictionaries, keys, and values
27.2. Adding key-value pairs to a dictionary
27.2.1. Short diversion into restrictions on keys
27.3. Removing key-value pairs from a dictionary
27.4. Getting all the keys and values in a dictionary
27.4.1. No ordering to dictionary pairs
27.5. Why should you use a dictionary?
27.5.1. Keeping count with frequency dictionaries
27.5.2. Building unconventional dictionaries
Summary
Lesson 28. Aliasing and copying lists and dictionaries
28.1. Using object aliases
28.1.1. Aliases of immutable objects
28.1.2. Aliases of mutable objects
28.1.3. Mutable objects as function parameters
28.2. Making copies of mutable objects
28.2.1. Commands to copy mutable objects
28.2.2. Getting copies of sorted lists
28.2.3. A word of caution when iterating over mutable objects
28.2.4. Why does aliasing exist?
Summary
Lesson 29. Capstone project: document similarity
29.1. Breaking the problem into tasks
29.2. Reading file information
29.3. Saving all words from the file
29.4. Mapping words to their frequency
29.5. Comparing two documents by using a similarity score
29.6. Putting it all together
29.7. One possible extension
Summary
Unit 7. Making your own object types by using object-oriented programming
Lesson 30. Making your own object types
30.1. Why do you need new object types?
30.2. What makes up an object?
30.2.1. Object properties
30.2.2. Object behaviors
30.3. Using dot notation
Summary
Lesson 31. Creating a class for an object type
31.1. Implementing a new object type by using a class
31.2. Data attributes as object properties
31.2.1. Initializing an object with __init__
31.2.2. Creating an object property inside __init__
31.3. Methods as object operations and behaviors
31.4. Using an object type you defined
31.5. Creating a class with parameters in __init__
31.6. Dot notation on the class name, not on an object
Summary
Lesson 32. Working with your own object types
32.1. Defining a stack object
32.1.1. Choosing data attributes
32.1.2. Implementing methods
32.2. Using a Stack object
32.2.1. Make a stack of pancakes
32.2.2. Make a stack of circles
Summary
Lesson 33. Customizing classes
33.1. Overriding a special method
33.2. Overriding print() to work with your class
33.3. Behind the scenes
33.4. What can you do with classes?
33.4.1. Scheduling events
Summary
Lesson 34. Capstone project: card game
34.1. Using classes that already exist
34.2. Detailing the game rules
34.3. Defining the Player class
34.4. Defining the CardDeck class
34.5. Simulate the card game
34.5.1. Setting up the objects
34.5.2. Simulating rounds in the game
34.6. Modularity and abstraction with classes
Summary
Unit 8. Using libraries to enhance your programs
Lesson 35. Useful libraries
35.1. Importing libraries
35.2. Doing mathematical operations with the math library
35.3. Random numbers with the random library
35.3.1. Randomizing lists
35.3.2. Simulating games of chance
35.3.3. Replicating results by using a seed
35.4. Timing programs with the time library
35.4.1. Using the clock
35.4.2. Pausing your program
Summary
Lesson 36. Testing and debugging your programs
36.1. Working with the unittest library
36.2. Separating the program from the tests
36.2.1. Types of tests
36.3. Debugging your code
36.3.1. Using tools to help you step through code
Summary
Lesson 37. A library for graphical user interfaces
37.1. A library for graphical user interfaces
37.2. Setting up a program using the tkinter library
37.3. Adding widgets
37.4. Adding event handlers
Summary
Lesson 38. Capstone project: game of tag
38.1. Identifying the parts to the problem
38.2. Creating two shapes in a window
38.3. Moving shapes inside the canvas
38.4. Detecting a collision between shapes
38.5. Possible extensions
Summary
Appendix A. Answers to lesson exercises
Lesson 2
Answers to quick checks
Lesson 3
Answers to quick checks
Lesson 4
Answers to quick checks
Answers to summary questions
Lesson 5
Answers to quick checks
Lesson 6
Answers to quick checks
Answers to summary questions
Lesson 7
Answers to quick checks
Answers to summary questions
Lesson 8
Answers to quick checks
Answers to summary questions
Lesson 9
Answers to summary questions
Lesson 10
Answers to quick checks
Answers to summary questions
Lesson 11
Answers to quick checks
Answers to summary questions
Lesson 13
Answers to quick checks
Answers to summary questions
Lesson 14
Answers to quick checks
Answers to summary questions
Lesson 16
Answers to quick checks
Answers to summary questions
Lesson 17
Answers to quick checks
Answers to summary questions
Lesson 18
Answers to quick checks
Answers to summary questions
Lesson 20
Answers to quick checks
Answers to summary questions
Lesson 21
Answers to quick checks
Answers to summary questions
Lesson 22
Answers to quick checks
Answers to summary questions
Lesson 24
Answers to quick checks
Answers to summary questions
Lesson 25
Answers to quick checks
Answers to summary questions
Lesson 26
Answers to quick checks
Answers to summary questions
Lesson 27
Answers to quick checks
Answers to summary questions
Lesson 28
Answers to quick checks
Answers to summary questions
Lesson 30
Answers to quick checks
Lesson 31
Answers to quick checks
Answers to summary questions
Lesson 32
Answers to quick checks
Answers to summary questions
Lesson 33
Answers to quick checks
Answers to summary questions
Lesson 35
Answers to quick checks
Answers to summary questions
Lesson 36
Answers to quick checks
Answers to summary questions
Lesson 37
Answers to quick checks
Answer to summary questions
Appendix B. Python cheat sheet
Variable names
Mutable vs. immutable
Dictionaries
Appendix C. Interesting Python libraries
Thinking like a programmer: big ideas
Index
List of Figures
List of Tables
List of Listings
Preface
I wanted to write this book for two main reasons. I aimed to fill a need for a book that truly taught programming from scratch, and that presented programming as an activity that can help you with daily tasks.
A common misconception people have is that programing has to be a big endeavor every time you do it, where you’re trying to write a program that can solve a world problem. But that’s not so. Learning to program can improve your day-to-day life! I write short programs all the time, whether it’s to solve puzzles or to help me make decisions. I wanted to capture this sentiment in this book by making programming as accessible to everyone as I can, showing how with even a little bit of programming knowledge, you can write useful programs customized to your needs.
I teach an introductory Python computer science course for undergraduates. For the most part, many students taking the class have no prior programming experience, in any language. The course is fast-paced, and many students ask if there are any resources online for people who have never programmed before. Almost all the resources I point them to require prior knowledge of programming, which adds another level of indirection to their learning: they have to first grasp the idea of programming and then understand how to apply that to Python. I try not to forget what it’s like to start learning to program from scratch, no matter how many times I teach the course. I want this book to be a gentle introduction to programming in one of the most popular languages at this time, that also shows how approachable coding can be.
Acknowledgments
I’m so glad I had the opportunity to write this book, so I can help others who are just starting out in the wide world of programming.
First, I’d like to thank my husband, CJ. His support throughout the writing of this book was unwavering, from offering suggestions to watching our son while I wrote on weekends.
Next, I’d like to thank my parents and sister. My dad taught me programming when I was 12, and I’ll never forget how many times he had to explain object-oriented programming to me before it finally clicked. My sister and mom travelled across the country a few times a year to help watch my sons while I got more writing done. My mom, especially, was my secret weapon.
She has never programmed before and was the perfect target audience, working through the exercises and reviewing the chapters as I was writing them.
I’d also like to thank my development editors at Manning: Kristen Watterson, Dan Maharry, and Elesha Hyde. The book underwent many transformations to become what it is, and I thank them all for their patience while I wrote and rewrote lessons. Their suggestions were much appreciated and made the book that much stronger. A big thanks also goes to my technical development editor, Frances Buontempo, and technical proofreader, Ignacio Beltran Torres, who carefully read the lessons and pointed out corrections and had wonderful suggestions on how to improve the book. Also thanks to everyone else at Manning who helped produce and promote the book. Of course, thank you to all the reviewers who offered their time to read and comment on the book at all stages of development. They are Alexandria Webb, Ana Pop, Andru Estes, Angelo Costa, Ariana Duncan, Artiom Plugachev, Carlie Cornell, David Heller, David Moravec, Adnan Masood, Drew Leon, George Joseph, Gerald Mack, Grace Kacenjar, Ivo Stimac, James Gwaltney, Jeon-Young Kang, Jim Arthur, John Lehto, Joseph M. Morgan, Juston Lantrip, Keith Donaldson, Marci Kenneda, Matt Lemke, Mike Cuddy, Nestor Narvaez, Nicole E. Kogan, Nigel John, Pavol Kráľ, Potito Colluccelli, Prabhuti Prakash, Randy Coffland, R. Udendhran Mudaliyar, Rob Morrison, Rujiraporn Pitaksalee, Sam Johnson, Shawn Bolan, Sowmy Vajjala-Balakrishna, Steven Parr, Thomas Ballinger, Tom Northwood, Vester Thacker, Warren Rust, Yan Guo, and Yves Dorfsman.
About this Book
Who should read this book
Get Programming: Learn to Code with Python is intended for anyone who is curious about programming but doesn’t necessarily want to pursue a career in it. It doesn’t assume any programming experience. You should be familiar with the following ideas:
Variables—Readers who have taken a math course that deals with introductory algebra know what a variable is. This book explains how variables in a programming setting are different.
Assigning truth values (true/false) to statements—Statements are sentences that can be determined as true or false. For example, It is raining
is a statement that’s either true or false. You should know how to invert statements to take the opposite truth value by using the word not. For example, if It is raining
is true, then It is not raining
is false.
Connecting statements—When there’s more than one statement, they can be connected by using the words and or or. For example, It’s raining
and I’m happy
can become It’s raining and I’m happy.
Making decisions—With multiple statements, you can make a decision based on whether one statement is true by using if...then....
For example, If it is raining then the ground is wet
is made up of two statements: It is raining
and the ground is wet.
The statement the ground is wet
is a consequence of the statement it is raining.
Following instructions by doing any of the following activities or similar—Playing a game of 20 Questions, following a recipe, completing a read-your-own-adventure book or understanding an algorithm (following a set of instructions and making branching decisions).
How this book is organized: a roadmap
This book has eight units that cover 38 lessons. Every unit ends with a capstone project. Each unit is meant to teach you about one important concept in programming, through a series of short lessons:
Unit 0 provides a bit of motivation to nudge you into the world of computer programming. You’ll see how programming can be compared to other tasks that you might sometimes do.
Unit 1 introduces you to the basics behind programming and the building blocks of every computer program. You’ll download a programming environment and set it up so you can write programs.
Unit 2 gets you to start writing code that interacts with the user by getting input from them and showing them results.
Unit 3 shows you how to write programs that make decisions for you. You’ll write code that branches off into different directions. When run, programs will decide which branches to take, depending on values at decision points.
Unit 4 builds on the idea that computers are good at doing tasks quickly. You’ll write code that takes advantage of the power of computers by repeating certain commands many times by writing code that automatically repeats a set of commands many times.
Unit 5 introduces you to one way to write organized code: using functions as modules that can contain reusable code.
Unit 6 shows you advanced types of objects that you can program with. After this unit, you’ll be able to write some incredibly useful and versatile programs.
Unit 7 introduces you to making your own types of objects. This is a capability that not all programming languages have, but most of the ones being used today do have.
Unit 8 wraps up the book by showing you code libraries written by others that you can use in your own programs. This lesson brings together abstract ideas that show you how to organize your code and take advantage of previously written code.
About the code
The content and code in this book are presented using Python version 3.5, the most up-to-date version at the time of writing.
The code examples in this book show how to apply the concepts learned in each lesson to perform a task you may have to do in your day-to-day life. Toward the end of the book, the code becomes a bit longer, and the same task is revisited in a couple of different scenarios.
At the end of each unit, a capstone project summarizes key ideas learned in the lessons. A problem is described, and you’ll be walked through one possible solution. You’ll discover how to translate
the English description of the task outlined into code.
This book contains many examples of source code both in numbered listings and in line with normal text. In both cases, source code is formatted in a fixed-width font like this to separate it from ordinary text. Sometimes code is also set in bold to highlight code that has changed from previous steps in the chapter, such as when a new feature adds to an existing line of code.
In many cases, the original source code has been reformatted; we’ve added line breaks and reworked indentation to accommodate the available page space in the book. In rare cases, even this was not enough, and listings include line-continuation markers ( ). Additionally, comments in the source code have often been removed from the listings when the code is described in the text. Code annotations accompany many of the listings, highlighting important concepts.
Book forum
Purchase of Get Programming: Learn to Code with Python includes free access to a private web forum run by Manning Publications where you can make comments about the book, ask technical questions, and receive help from the author and from other users. To access the forum, go to https://forums.manning.com/forums/get-programming. You can also learn more about Manning’s forums and the rules of conduct at https://forums.manning.com/forums/about.
Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We suggest you try asking the author some challenging questions lest her interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print.
About the author
Dr. Ana Bell is a lecturer at the Massachusetts Institute of Technology in the Electrical Engineering and Computer Science department. She has co-lectured two introductory computer science courses in Python for the past five years: one aimed at students who have no prior programming experience, and one intended to expand on what students learn in the first course. She enjoys introducing others to programming and watching them gain confidence in themselves as they progress. It’s an extremely rewarding feeling to explain the same concept in different ways and watch it suddenly click with a student.
She was first introduced to Python in graduate school at Princeton University, where she started using it to parse and reformat large files in her research and found it to be an intuitive language to learn and use.
Unit 0. Learning how to program
This unit begins with a bit of motivation on why learning to program is beneficial no matter who you are; you can even use programming in your daily life to make certain tasks easier. You’ll briefly be introduced to ideas you should be familiar with before starting to program, and you’ll get an idea of the kinds of things you’ll be able to do by the end of this book.
The unit ends by drawing a parallel with baking so that you can see programming as a skill requiring practice and creativity. This unit also serves as an overview of what you should expect as you go through this journey: lots and lots of practice! Learning to program seems like a big undertaking, but it’s best to take small steps every day rather than giant occasional leaps. It’s a challenging but rewarding path.
Let’s begin!
Lesson 1. Why should you learn how to program?
After reading lesson 1, you’ll be able to
Understand why programming matters
Set up a plan for learning how to program
1.1. Why programming matters
Programming is universal. No matter who you are or what you do, you can learn to write programs that can help make your life easier.
1.1.1. Programming isn’t just for professionals
A misconception, both for veteran programmers and for people who have never programmed before, is that after you start to learn how to program, you’ll have to continue until you become a professional programmer. Likely, this misconception stems from associating programming with incredibly complex systems: your operating system, car/aviation software, artificial intelligence that learns, and many others.
I think of programming as a skill, like reading/writing, math, or cooking. You don’t have to become a best-selling author, a world-class mathematician, or a Michelin star chef. Your life significantly improves with a little bit of knowledge in each of those subjects: if you know how to read and write, you can communicate with others; if you know how to do basic calculations, you can tip appropriately at a restaurant; if you know how to follow a recipe, you can make a meal in a pinch. Knowing a little bit of programming will enable you to avoid having to rely on others to help you and will enable you to finish tasks you may want to do in a specific way more efficiently.
1.1.2. Improve your life
If you learn to program, your skill can be used as you effectively build your own personal toolbox of utilities. The more you try to integrate programming into your daily life, the more you’ll be able to solve personal tasks more efficiently.
To keep up with your skill, you can write custom programs that fit your daily needs. The benefit of writing your own programs instead of using ones that already exist is that you can customize them to your exact needs. For example:
Do you keep track of the checks that you write in the paper logbook that came with your checkbook? Consider typing them in a file and writing a program that reads the file and organizes the information. With programming, after the data is read, you can calculate sums, separate the checks by date ranges, or whatever else you want.
Have you taken pictures and downloaded them to your computer, but the names given by the camera software aren’t what you want? Instead of manually renaming everything by hand for a thousand pictures, you can write a short program that renames all files automatically.
Are you a student preparing for the SAT and want to make sure your solution for the quadratic equation is correct? You can write a program that takes in missing parameters and solves the equation for you, so that when you do it by hand, you can be sure that the calculations were done correctly.
Are you a teacher who would like to send a personalized email to each student with that student’s grade for a test? Instead of copying and pasting text and filling in the values manually, you can write a program that reads the student name, email address, and score from a file, and then effectively fills in the blank automatically for each student, and sends out the email.
These are just a few situations in which programming can help you to be more organized and self-reliant.
1.1.3. Challenge yourself
At first glance, programming feels technical. At the beginning, it is, especially as you’re learning all the basic concepts. Perhaps unintuitively, programming is also creative. After you become familiar with a few ways to do one task in programming, you get to make decisions about which way would be best to apply. For example, if you’re reading a file, do you want to read all the data at once, store it, and then do some analysis, or do you want to read the data one piece at a time and analyze as you go along?
By making these kinds of decisions with the knowledge you gain, you challenge yourself to think critically about what you want to achieve and how to do it most efficiently.
1.2. Where you are now and where you’ll be
This book doesn’t assume that you’ve programmed before. Having said that, you should be familiar with the following:
Understanding a variable—If you took a math course that covers introductory algebra, you should know what a variable is. In the next unit, you’ll see how variables in a programming setting are different.
Understanding true/false statements—You can think of statements as sentences that can be determined to be true or false. For example, it is raining
is a statement that’s either true or false. You can also invert statements to take the opposite truth value by using the word not. For example, if it is raining
is true, then it is not raining
is false.
Connecting statements—When you have more than one statement, you can connect them by using the words and or or. For example, if it is raining
is true and I am hungry
is false, then it is raining and I am hungry
is false because both parts need to be true. But it is raining or I am hungry
is true because at least one of the parts is true.
Making decisions—When you have multiple statements, you can make decisions based on whether one statement is true by using if...then. For example, if it is raining, then the ground is wet
is made up of two statements: it is raining
and the ground is wet.
The statement the ground is wet
is a consequence of the statement it is raining.
Following flowcharts—You won’t need to know flowcharts to understand this book, but understanding them requires the same skills as understanding basic programming. Other ideas that use the same skill set are playing the game of 20 Questions, following a recipe, reading a choose-your-own-adventure book, or understanding algorithms. You should be familiar with following a set of instructions and making branching decisions. Flowcharts show a list of instructions that flow from one to the next and allow you to make decisions, which lead to different paths. In a flowchart, you’re asked a series of questions, whose answer is one of two choices: yes or no. Depending on your answer, you follow certain paths through the flowchart and will eventually end up at a final answer. Figure 1.1 is an example of a flowchart.
Figure 1.1. Flowchart for deciding whether to take an umbrella today
Knowing the preceding skills is all you need to begin your programming journey. After reading this book, you’ll know the basics of programming. The basic concepts you’ll learn that can apply to any programming language are as follows:
Using variables, expressions, and statements in programming
Getting the program to make decisions based on conditions
Getting the program to automatically repeat tasks under some conditions
Reusing operations built into the language to help you be more efficient
Making your code more readable and easy to maintain by breaking a larger task into smaller ones
Knowing which data structure (a structure already created that can store information in a certain format) is appropriate to use in different situations
You’ll be learning how to program by using a language called Python (version 3.5). Any knowledge gained about programming concepts will be easily translatable to any other programming language; the basics are going to be the same between different languages. More specifically, at the end of this book, you’ll be familiar with the details of the Python programming language. You’ll know the following:
How to use the syntax of the language (in English, the equivalent is how to form valid sentences).
How to write more-complex programs with different blocks of code working together in harmony (in English, the equivalent is writing a short story).
How to use code that other programmers wrote (in English, the equivalent is referencing someone else’s work so you don’t have to rewrite it).
How to effectively check that your program works, including testing and debugging (in English, the equivalent is checking for spelling and grammar errors).
How to write programs that interact with the keyboard and mouse.
How to write more data-centric or mathematical programs.
1.3. Our plan for learning how to program
Individual motivation is one of the greatest make-or-break factors when learning a programming language. Taking things slow, getting a lot of practice, and allowing time to absorb the material will make the road to success less bumpy.
1.3.1. First steps
If you’ve never programmed before, this book is for you. This book is separated into units. A unit is a set of lessons that all deal with one particular concept in programming. The first lesson in the unit is usually a motivating lesson. The last lesson in a unit is a capstone project, which introduces a real-life problem or task. You can attempt the capstone on your own or you can read the walk-through of the solution; it’s intended to make sure that you’re on track with understanding the concepts.
You’ll have many opportunities to practice what you read. At the beginning of each lesson, you’ll see a simple exercise, called Consider this, that will get you thinking about the world around you and the way you interact with it; this exercise introduces you to the main idea of the lesson. It’s described without code jargon and hints at the kinds of programming ideas you’ll learn in the lesson. Throughout the lesson, you’ll discover how to translate
the English description of the outlined exercise into code. Each lesson contains many exercises to help you understand the concepts; doing all the exercises will help the concepts click. Answers to these exercises will be found in Appendix A so that you can check your work.
Being hands-on with the exercises is important in the first few lessons, as you’ll be learning the basics of programming using Python. In the last few lessons, you’ll see packages that other programmers wrote, and you’ll have an opportunity to learn how to use those packages to build more-complex programs. One of the packages will get you to build programs that you can interact with visually, by mouse click or keyboard input, and you’ll see your program update an image on the screen. Another package will show you how to deal with data as input. You’ll learn how to read files that have a certain structure, how to analyze the data gathered, and how to write