Previous Next

Python Practice Lab Learn How to Code Through Interactive Examples (Angelica Lim, Victor Cheung)(Z-Library)

Author: Angelica Lim, Victor Cheung

Python

A guide to learning basic programming by writing fun, working programs that gradually become more complex This classroom-tested, workbook-style text teaches basic programming by guiding readers to write Python programs that mimic interactive chatbots. Unlike textbooks with opaque examples explained in dry, monotonous code, Python Practice Lab engages readers immediately, with more than thirty motivating and hands-on examples. Readers learn by writing fun, working programs that gradually become more difficult as new concepts are introduced. Most exercises are open ended, promoting creativity in the process of learning. Along with coding practice, the book offers brief introductions to a range of other topics in computer science, including recommendation systems, computer vision, and big data, and relates these subjects to the programming concepts covered in the book. Python Practice Lab will be an essential resource for anyone who wants to learn to program, instructors teaching Python to beginners, and students who want to supplement their coursework by building complete and functional programs.

📄 File Format: PDF
💾 File Size: 11.5 MB
10
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
(This page has no text content)
📄 Page 2
Python Practice Lab
📄 Page 3
(This page has no text content)
📄 Page 4
Python Practice Lab Learn How to Code through Interactive Examples Angelica Lim • Victor Cheung Princeton University Press Princeton and Oxford
📄 Page 5
Copyright © 2026 by Princeton University Press Princeton University Press is committed to the protection of copyright and the intellectual property our authors entrust to us. Copyright promotes the progress and integrity of knowledge created by humans. By engaging with an authorized copy of this work, you are supporting creators and the global exchange of ideas. As this work is protected by copyright, any reproduction or distribution of it in any form for any purpose requires permission; permission requests should be sent to permissions@press.princeton.edu. Ingestion of any IP for any AI purposes is strictly prohibited. Published by Princeton University Press 41 William Street, Princeton, New Jersey 08540 99 Banbury Road, Oxford OX2 6JX press.princeton.edu GPSR Authorized Representative: Easy Access System Europe - Mustamäe tee 50, 10621 Tallinn, Estonia, gpsr.requests@easproject.com All Rights Reserved ISBN (pbk.) 978-0-691-24360-3 ISBN (epub) 978-0-691-28262-6 ISBN (PDF) 978-0-691-24363-4 Library of Congress Control Number: 2025948509 British Library Cataloging-in-Publication Data is available Editorial: Hallie Stebbins and Chloe Coy Production Editorial: Karen Carter Text and Cover Design: Wanda España Production: Erin Suydam Publicity: William Pagdatoon Cover Credit: Danil Cetvericov / Alamy Stock Vector This book has been composed in Times New Roman and Halyard Display Printed in the United States of America 10 9 8 7 6 5 4 3 2 1
📄 Page 6
Contents Preface ix Guiding Principles xiii 1 INTRODUCTION TOCOMPUTER SCIENCE 1 1.1 Welcome to CS! 1 1.1.1 Learning Outcomes 3 1.1.2 Alien Explanations 3 1.1.3 Writing and Running Your Programs 4 1.1.4 Motivational Quote Generator 5 1.1.5 Review Questions 6 1.1.6 Practice Exercises 7 1.1.7 Glossary 7 2 CHATBOTS 9 2.1 Chatbots with Personality 10 2.1.1 Learning Outcomes 11 2.1.2 Greetings Chatbot 12 2.1.3 How’s It Going Bot 18 2.1.4 Horoscope Bot 22 2.1.5 Review Questions 26 2.1.6 Practice Exercises 27 2.1.7 Glossary 28 2.2 Chatbots with Loops 29 2.2.1 Learning Outcomes 29 v
📄 Page 7
vi CONTENTS 2.2.2 A Robust Bot 30 2.2.3 Food Bot 32 2.2.4 Measuring Things in Canada 34 2.2.5 Bubble Tea Menu 36 2.2.6 Mind Reader Game 38 2.2.7 Review Questions 42 2.2.8 Practice Exercises 43 2.2.9 Glossary 44 3 RECOMMENDATION SYSTEMS 45 3.1 Popularity Contest 46 3.1.1 Learning Outcomes 46 3.1.2 Popular Cafe Finder 46 3.1.3 Chip Rater 50 3.1.4 Movie Rater 52 3.1.5 Review Questions 54 3.1.6 Practice Exercises 56 3.1.7 Glossary 57 3.2 Finding Your Match 57 3.2.1 Learning Outcomes 57 3.2.2 Data Files 58 3.2.3 Favourite Pets 59 3.2.4 Similarity Score 65 3.2.5 Who Is Most Similar to You? 66 3.2.6 Review Questions 68 3.2.7 Practice Exercises 70 3.2.8 Glossary 71 4 GRAPHICS ANDCOMPUTER VISION 72 4.1 Interactive Drawings 73 4.1.1 Learning Outcomes 73 4.1.2 Basic Turtle Commands 73 4.1.3 Interactive Drawing with Turtle 74 4.1.4 Cookie Drawer 76 4.1.5 Review Questions 79 4.2 Image Processing 81 4.2.1 Learning Outcomes 81 4.2.2 Green or Not? 82 4.2.3 Image Magic 91 4.2.4 Cool Colours Module 96 4.2.5 Review Questions 100 4.2.6 Practice Exercises 101
📄 Page 8
CONTENTS vii 4.3 Drawing Trees 101 4.3.1 Learning Outcomes 101 4.3.2 Intro to Recursion 102 4.3.3 Recursion Revisited 106 4.3.4 Review Questions 110 4.3.5 Practice Exercises 110 5 INTERNET AND BIG DATA 112 5.1 Searching 112 5.1.1 Learning Outcomes 113 5.1.2 Linear Search 113 5.1.3 Binary Search 115 5.1.4 Review Questions 117 5.1.5 Practice Exercises 117 5.2 Sorting 118 5.2.1 Learning Outcomes 118 5.2.2 Selection Sort 118 5.2.3 Merge Sort 122 5.2.4 Review Questions 124 5.2.5 Practice Exercises 124 5.3 Map, Filter, Reduce 125 5.3.1 Learning Outcomes 128 5.3.2 Review Questions 128 5.3.3 Practice Exercises 129 6 EXPERT PROJECTS 130 6.1 Audio-Visual Language Learning Chatbot 130 6.2 Interactive Image Processor 135 Index 139
📄 Page 9
(This page has no text content)
📄 Page 10
Preface Interactive chatbots are taking the world by storm! Are you interested in creating interactive programs but don’t know where to start? Do you have no coding background and want a fun introduction to computer science (CS)? Or, perhaps you are a teacher looking for a structured program to cover the areas in CS, while keeping examples interesting and fresh for your students? In this book, you will learn basic programming by writing Python programs that mimic interactive chatbots.While this introductory book is not about how to code an advanced arti- ficial intelligence, youwill gain skills necessary for basic coding while learning about artifi- cial intelligence concepts such as recommendation systems, computer vision, and big data. The curriculum presented in this workbook has been taught as an introduction to CS and programming course at Simon Fraser University in British Columbia, Canada, to over a thousand students, and to both majors and nonmajors in Computing Science. The course is designed to teach through real-life situations, and to give students the opportunity for creative thinking. Reflecting on the course, a student shared: Although I have been interested in programming since high school, I was always too intimidated to try it. I am really glad to have finally taken this course because I found that I enjoyed programming and problem solving more than I expected to. I had somuch fun throughout the entire semester, andwill be takingmore computing science courses this summer—hopefully I can pursue a minor! We hope this book will inspire the same enthusiasm in you to pursue a deeper understanding and appreciation of CS! WHATARE CHATBOTS? In this book, we use the term “chatbots” to describe interactive programs that use text as input and output. In particular, these programs converse with the user and have a text- based interface, similar to that of a messaging app. You will be developing these interactive programs, which your friends and you can try! ix
📄 Page 11
x PREFACE HOW IS THIS BOOKDIFFERENT? This workbook is meant to be engaging, hands-on, and example-driven to help you become a confident coder. In line with our theme, interactive chatbots, natural language and text strings are used early on as the main building blocks for learning about program structures, rather than math. This approach demonstrates the use of CS in many diverse areas and fields. Additionally, code comprehension exercises, traditionally containing terse, single- letter variables, are rewritten in equivalent code with inclusive and approachable variable names. In each chapter, the reader is challenged to write a full program based on the topics and the provided examples. Finally, a selection of projects is presented at the end of the book, to integrate the concepts learned through all the chapters. By the end of this book, you will become well-versed in traditional introductory algo- rithms and become fluent in programming in Python 3. The learning outcomes for this toolkit are roughly equivalent to those of How to Think Like a Computer Scientist (Ch. 1–12, 15) (https://runestone.academy/ns/books/published/thinkcspy/index.html). IS THIS BOOK RIGHT FORME? The audience for this workbook includes: • anyone who wants to learn how to program by coding fun, working programs that gradually become more complex; • instructors teaching Python to beginners who need motivating examples and exercises for their classes; and • students wishing to have a reference to examples taught by their instructors andwishing to build complete and functional programs. WHAT IS THIS BOOKNOT? This book is not a stand-alone CS textbook. It is a hands-on workbook that provides basic coverage of all the necessary concepts needed for introductory CS through examples and exercises, without overburdening the reader with details behind individual topics (e.g., how are variables represented in memory? what are modules?). Additional explanations and exercises to practice specific skills are linked to from this workbook as additional resources from this workbook. ROADMAP Here is a short guide to the contents of this book. Chapters 1 to 4.2 focus on learning the basics of programming in Python 3, while Chapters 4.3 to 6 introduce classic algorithms and hands-on projects to deepen your knowledge of CS. Chapter 1, “Getting Started,” explains the concept of an algorithm and gets you up and running with your first, “Hello, World,” program. Chapter 2, “Chatbots,” introduces a broad range of concepts by progressively building more and more advanced programs that we call “bots.” Chapter 2.1 focuses on the string data type and the many things you can do with it: assign it to a variable, concatenate it,
📄 Page 12
PREFACE xi compare it with other strings in conditionals (if/else), assign user input to it, create a list of them, and even choose one randomly from a list. Chapter 2.2 introduces the for-loop and integers, while building upon previous knowledge, such as that of string methods and nested conditionals. Chapter 3, “Recommendation Systems,” continues to build upon Chapter 2, expanding more on data types, manipulation of numbers (including floating-point numbers), division operators, accumulators, and lists using indexing. It also ventures deeper into loops by introducing nested loops and using them to access files. Finally, this chapter introduces dictionaries. Chapter 4, “Graphics and Computer Vision,” introduces the while-loop, expanding your understanding of functions through defining your own functions and modules. This chapter explains 2D arrays and color representation using RGB images. A simple Python course could end here, but we end the chapter with an introduction to recursion, an important concept in the field of CS. Chapter 5, “Internet and Big Data,” assumes that you now have the basics of Python programming under your belt. It provides a basic introduction to classic CS algorithms of sorting and searching, and to modern list processing algorithms such as map, filter and reduce. Finally, Chapter 6, “Expert Projects,” provides some sample applications you can build with the knowledge you’ve gained from this book. DEEPEN YOUR UNDERSTANDING Your learning doesn’t stop here! Deepen your understanding of the topics by reviewing and trying activities linked from our companion website https://press.princeton.edu/books /paperback/9780691243603/python-practice-lab. The activities are also listed here for your reference: Chapter 1 (from How to Think Like a Computer Scientist): • Chapter 1: General Introduction Chapter 2.1 (from How to Think Like a Computer Scientist): • Chapter 2: Simple Python Data • Chapter 5: Python Modules • Chapter 7: Selection • Chapter 9.3: Operations on Strings • Chapter 10.2: List Values Chapter 2.2 (from How to Think Like a Computer Scientist): • Chapters 1.7 to 1.9: Different Types of Errors • Chapter 9.5 - String Methods • Chapter 9.13 - The in and not in Operators • Chapter 10.5 - List Membership • Chapters 4.4 and 4.5 – The for-Loop Chapter 3.1 (from How to Think Like a Computer Scientist): • Chapter 2 - Simple Python Data (Review) • Chapters 4.4 to 4.7 - for-Loop and for-Loop with range Function (except turtle Examples)
📄 Page 13
xii PREFACE • Chapter 6.5.1 - The Accumulation Pattern • Chapter 9.5 - String Methods • Chapter 9.13 - The in and not in Operators • Chapters 10.3 to 10.5 - List Length to List Membership • Chapter 10.18 - Accumulator Pattern Chapter 3.2 (from How to Think Like a Computer Scientist): • Chapters 10.1 to 10.8 - Lists • Chapters 11.1 to 11.6 - Files Chapter 4.1 (from How to Think Like a Computer Scientist): • Chapters 4.1 to 4.3 and Chapter 4.6 to 4.9 - Python Turtle and the Range Function • Chapters 6.1, 6.4 and 6.11 - Files Chapter 4.2 (from How to Think Like a Computer Scientist): • Chapters 6.2, 6.5, 6.6 and 6.7 - Files • Chapters 8.3 to 8.8 and 8.11 - 2D Iteration: Image Processing. Note: This online refer- ence on image processing is helpful for theory, but is slightly different from what we use in this book (provided as the csimage module). Chapter 4.3 (from How to Think Like a Computer Scientist): • Chapter 6.1 - What Is Recursion? • Chapter 6.3 - Three Laws of Recursion • Chapter 6.5 - Visualizing Recursion • Chapter 6.6 - Sierpinski Triangle Chapter 5.1 (from Problem Solving with Algorithms and Data Structures Using Python): • Chapter 6.2 - Searching • Chapter 6.3 - Linear Search • Chapter 6.4 - Binary Search Chapter 5.2 (from Problem Solving with Algorithms and Data Structures using Python): • Chapter 6.6 - Sorting • Chapter 6.8 - Selection Sort • Chapter 6.11 - Merge Sort Chapter 5.3 (fromMIT’s Software Construction course (focus on the Python notes and disregard the lambda examples): • Map • Functions as Values • Filter • Reduce
📄 Page 14
Guiding Principles This book is a little different from those that employ traditional methods for learning computer science (CS). It uses the following philosophy to teach CS and programming. • Make parallels with foreign language learning. We acknowledge that CS can feel difficult at first because learning any new language, like Chinese or French, takes time and practice. But once you become fluent, you can translate from English in your head, and communicate with a new friend—the computer! • Write useful code from day 1. Our approach takes concepts and explores them in useful, end-to-end programs in each lesson. You don’t have to know everything to write a program—we’ll start from simple ones that you can write from day 1 and build on that to create more sophisticated ones. • Introduce one or two concepts at a time, in context. Sample programs are carefully crafted so that you are not overloadedwithmultiple concepts at a time. And just aswhen learning a natural language, new concepts are introduced embedded in real programs and situations, not in isolation. • Design algorithms in English. Thinking of a solution and putting it into code are two different processes, especially at first. We suggest that you design the algorithm flow in English first, then translate it into Python. • Handle strings first. We reduce cognitive overload by exploring strings (sequences of characters that form words and sentences), and all their possibilities (conditionals, loops, etc.), first. This allows you to write useful and practical programs early, adding the complexity of multiple data types later. • Construct with creativity. Exercises are open-ended rather than looking for a right answer. We reinforce from the beginning the idea that programming is a creative endeavor. • Share code with others.We make it a delight to build programs and share them with friends and family. We use an online coding space like online-python.com or trinket.io so that you can take pride in your work and have others try it out! • Focus on fluency. Our ultimate goal is to help you become a fluent coder. We deliver practice questions that ask you to write full programs from scratch. xiii
📄 Page 15
xiv GUIDING PRINCIPLES • Write beautiful, understandable code. Obscure, tricky code is often used for tests of understanding, but we emphasize that real code written by professionals is highly readable, and uses descriptive variable names. No longer are variables limited to i, j, and k! • Showcase fields in CS. You will learn coding through exploration units in con- temporary fields in CS, such as computer vision, natural language processing, and recommendation systems. HOWTOUSE THIS BOOK This workbook is designed to be used as an example-driven book to guide your learning of concepts in CS and Python programming. Each chapter unit begins with a scenario and a sample interactive program, followed by a list of relevant topics necessary to implement the program. As the chapter progresses, details and an explanation of each topic are provided. At the end of each chapter, additional practice exercises are included to reinforce these topics. We recommend using this workbook in a way that depends on who you are. IF YOU ARE A SELF-DIRECTED LEARNEROR STUDENT . . . If you have never coded before and want to use this book as a guide for your learning, you have come to the right place! Read through each chapter and program listing, and try to run the example programs in your Python interpreter. Retyping the code from this book will help you learn and practice, so don’t skip this step! You’ll also be able to run the interactive programs and modify them, which we’ll sometimes ask you to do. Next, after each subsec- tion, check the list of external resources in Preface—Deepen Your Understanding, which links to online resources and practice questions to solidify your learning. Finally, test your mastery of the topics by completing the practice coding exercises, which each results in creating a small chatbot. Focus on writing the requested programs from scratch, then share them with your family and friends to test and play with! IF YOU ARE AN INSTRUCTOR . . . Use the scenarios as motivating examples to intrigue your students and drive the topics. Download the slides and code from our companion website (and feel free to tailor them to your class), and use in-class time to challenge your students with the practice exercises. Point your students to the additional readings for further explanations and practice exercises related to each chapter.
📄 Page 16
Python Practice Lab
📄 Page 17
(This page has no text content)
📄 Page 18
1 Introduction to Computer Science Congratulations on taking your first step into CS! In this first unit, you’ll learn what computer science (CS) is and where it came from, and start to learn about how it works. You’ll get set up with the tools that we’ll be using in the following chapters to help you become a proficient computer scientist by the end of the book. CS topics in this chapter: • Algorithms • Comments • Output 1.1 WELCOME TOCS! CS IS PROBLEM SOLVING If you like solving problems, you have come to the right place! In CS, we solve problems by designing and developing two components: • Algorithms, which are a way of thinking • Code, which is a way of communicating In this book, we will be designing our algorithms in English, and translating them into the Python programming language. This will allow us to communicate with computers to solve our problems. WHATARE ALGORITHMS? An algorithm is simply a list of steps to follow in order to complete a task. For example, cookie recipes are algorithms. They have ingredients as input, and a list of steps to produce a very tasty output: cookies! Another example is IKEA furniture instructions. If you can write clear, step-by-step instructions (e.g., how to build a chair), you’ve got great potential as a computer scientist! 1
📄 Page 19
2 CHAPTER 1 Introduction to Computer Science Algorithms can also be optimized for different things. Youmaywant to design instruc- tions for how to do the task as fast as possible, or in a simple way, or to minimize the space needed. For instance, in our cookie recipe example, some recipe titles might be “Chocolate chip cookies in 15 minutes” (fast) or “Easy chocolate chip cookies” (simple) or “One-bowl chocolate chip cookies” (minimizing space), optimizing for different needs. There are often multiple recipes, or algorithms, to achieve a similar result. WHATARE PROGRAMMING LANGUAGES? The computer is our fast, number crunching tool to solve problems for us. In order to communicate with the computer, we need to speak a language it understands. Program- ming languages have been developed to be a common language that both humans and the computer can interpret and understand. Python, Java, and C++ are names of some programming languages. Just like English, Japanese, French, and other natural languages, they are used to communicate meaning, and each has different grammar, syntax, and vocabulary. We say that some programming languages, such as Python and JavaScript, are inter- preted languages, while C, C++, and Java are compiled languages. What does compiled mean? When you run a program, your instructions to the computer are translated from the human-readable language such as Python or C++ into 0s and 1s, which are digital signals that the computer can understand. Translation can in happen two ways: line-by-line or in a batch. To understand this better, imagine being at the United Nations. There are professional translators who sit next to each diplomat and translate everything being said in real time. These translators are called interpreters. At the same meeting, there may be thick piles of documents on each desk that have been compiled into big translated reports before the meeting. In the same way, Python is an interpreted language because the Python interpreter on your computer translates each line of code into machine code in real time, on the fly, as the program runs on your computer. With C++, the entire program is completely compiled into machine code before anything runs. Now that you know the difference between interpreted and compiled programming languages, can you list two examples of programming languages for each type? WHAT IS PROGRAMMING? Once we have a general algorithm design in mind, and have selected a programming lan- guage, we can begin to program! Programming itself is the process where you break a large, complex task down into smaller subtasks and constructs that are recognizable to a computer. Common programming constructs include: • Input • Output • Conditions • Repetition • Math or logic We will explore all of these in the coming chapters!
📄 Page 20
CHAPTER 1 Introduction to Computer Science 3 DID YOU KNOW? The first programmer was an English mathematician named Lady Ada Lovelace. In 1842, she wrote the first computer program for Charles Babbage’s Analytical Engine (1837). Her first program calculated Bernoulli num- bers, but she also envisioned a future where the numbers she worked with could represent more than numbers. She believed that any data represented by numbers could be processed by a machine like the Analytical Engine, to compose music, create images, or do science. Today, with our modern computers, we know that she was right! 1.1.1 Learning Outcomes At the end of this unit, you will be able to… • write Python comments • explain what pseudocode is • describe the main characteristics of an algorithm • give an example of problem solving by subdividing tasks in to subtasks • write a program header block (i.e., initial comments with information about the author, date, and purpose of the code) • output Hello World using print() 1.1.2 Alien Explanations Do you like science fiction? In this section, we’ll deepen our understanding of algorithms by inventing an example that may seem strange, even alien, at first. All will be clear, soon! Imagine that one day the Earth is visited by aliens from another planet. You have been chosen to communicate with the alien, which knows nothing about the human race. You meet the alien, which comically looks exactly like a pea-green octopus with a space helmet. Luckily, the alien happens to speak English. The first thing it says is, “I would like to learn about the human species. Please, tell me something about your daily life as a human.” You reply, “Well, we do this thing every day. We brush our teeth!” The alien replies, “Please, human, explain ‘brush our teeth.’” EXERCISE Explain to the alien the procedure to “brush one’s teeth.” You can either explain to another person nearby who takes the role of the alien (be as curious as possible!), or write out the explanation. DEBRIEF First off, it’s not easy to explain something that comes so simply to us! You may have included the tools or input involved: a hand, a toothbrush…what else? Toothpaste?Mouth? Many components are involved. For an alien that does not have teeth or even hands, this requires patience and explanation in detail. Secondly, what did your explanation look like? Was it a list of numbered steps? How detailed was it? Did you include aspects such as how long the brushing should last, or how much toothpaste you need? The clearer your steps were, the closer to algorithmic thinking they will be.
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now

Recommended for You

Loading recommended books...
Failed to load, please try again later
Back to List