Discover millions of audiobooks, ebooks, and so much more with a free trial

From $11.99/month after trial. Cancel anytime.

Learn to Code by Solving Problems: A Python Programming Primer
Learn to Code by Solving Problems: A Python Programming Primer
Learn to Code by Solving Problems: A Python Programming Primer
Ebook612 pages5 hours

Learn to Code by Solving Problems: A Python Programming Primer

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Learn to Code by Solving Problems is a practical introduction to programming using Python. It uses coding-competition challenges to teach you the mechanics of coding and how to think like a savvy programmer.

Computers are capable of solving almost any problem when given the right instructions. That’s where programming comes in. This beginner’s book will have you writing Python programs right away. You’ll solve interesting problems drawn from real coding competitions and build your programming skills as you go.
 
Every chapter presents problems from coding challenge websites, where online judges test your solutions and provide targeted feedback. As you practice using core Python features, functions, and techniques, you’ll develop a clear understanding of data structures, algorithms, and other programming basics. Bonus exercises invite you to explore new concepts on your own, and multiple-choice questions encourage you to think about how each piece of code works.
 
You’ll learn how to:
  • Run Python code, work with strings, and use variables
  • Write programs that make decisions
  • Make code more efficient with while and for loops
  • Use Python sets, lists, and dictionaries to organize, sort, and search data
  • Design programs using functions and top-down design
  • Create complete-search algorithms and use Big O notation to design more efficient code
  •  
    By the end of the book, you’ll not only be proficient in Python, but you’ll also understand how to think through problems and tackle them with code. Programming languages come and go, but this book gives you the lasting foundation you need to start thinking like a programmer.
     
    LanguageEnglish
    PublisherNo Starch Press
    Release dateJun 29, 2021
    ISBN9781718501331
    Learn to Code by Solving Problems: A Python Programming Primer
    Author

    Daniel Zingaro

    Dr. Daniel Zingaro is an Associate Teaching Professor of computer science and award-winning teacher at the University of Toronto. His main area of research is computer science education research, where he studies how students learn computer science material.

    Related authors

    Related to Learn to Code by Solving Problems

    Related ebooks

    Programming For You

    View More

    Reviews for Learn to Code by Solving Problems

    Rating: 0 out of 5 stars
    0 ratings

    0 ratings0 reviews

    What did you think?

    Tap to rate

    Review must be at least 10 words

      Book preview

      Learn to Code by Solving Problems - Daniel Zingaro

      INTRODUCTION

      We use computers to accomplish tasks and to solve problems. For example, perhaps you’ve used a word processor to write an essay or letter. Perhaps you’ve used a spreadsheet program to organize your finances. Perhaps you’ve used an image editor to touch up a picture. It’s hard to imagine doing these things these days without a computer. We get a lot of mileage out of our word processors and spreadsheet programs and image editors.

      Those programs are written as general-purpose tools to accomplish a wide variety of tasks. Ultimately, though, they’re programs written by others, not by us. What do we do when an off-the-shelf program doesn’t quite do what we need?

      In this book, our goal is to learn how to take control of our computer by going beyond what can be done by an end user using preexisting programs. We’re going to write our own programs. We won’t write a word processor or a spreadsheet or an image editor. Those are huge tasks that, fortunately, people have already done. Rather, we’re going to learn how to write small programs to solve problems that we otherwise wouldn’t be able to solve. I want to help you learn to communicate instructions to a computer; these instructions will tell the computer how to carry out your plan for solving a problem.

      To give instructions to a computer, we write code in a programming language. A programming language specifies the rules for the code we write and dictates what the computer does in response to that code.

      We’re going to learn to program in the Python programming language. That’s a concrete skill that you’ll take away from this book, one that you can put on your résumé. More than Python, though, you’ll learn the type of thinking required to solve problems using a computer. Programming languages come and go. The way that we solve problems does not. I hope that this book helps you on your way from end user to programmer and that you have fun exploring what’s possible.

      Online Resources

      Supplementary resources for the book, including downloadable code and additional exercises, are available at https://nostarch.com/learn-code-solving-problems/.

      Who This Book Is For

      This book is for anyone who wants to learn how to write computer programs to solve problems. I have three particular types of people in mind.

      First, you may have heard about the Python programming language and want to learn how to write code in Python. I’ll explain in the next section why Python is a great choice as a first programming language to learn. You’ll learn a lot about Python in this book, and you’ll be in a position to read more advanced books on Python if that’s your next step.

      Second, if you haven’t heard of Python or just want to learn what programming is all about, don’t worry: this book is for you, too! This book will teach you how to think about programming. Programmers have particular ways of breaking down problems into manageable pieces and expressing solutions to those pieces in code. At this level, it doesn’t matter what programming language is being used, because the way that programmers think is not tied to a particular language.

      Finally, you may be interested in learning some other programming language such as C++, Java, Go, or Rust. Much of what you learn as a byproduct of learning Python will be useful when you study those other programming languages. Plus, Python is certainly worth learning in its own right. Let’s turn to why next.

      Why Learn Python?

      Years of teaching introductory programming have demonstrated to me that Python is a great choice for a first programming language. Compared to other languages, Python code is often more structured and readable. Once you get used to it, you might agree that parts of it almost read like English! Python also comes with many features that are not available in other languages, including powerful tools to manipulate and store data. We’ll use many of these features throughout the book.

      Not only is Python an excellent teaching language, but it’s also one of the most in-demand programming languages in the world. Programmers use it to write web applications, games, visualizations, machine learning software, and more.

      There we have it: a language well-suited for teaching that also carries a professional advantage for you. I can’t ask for any more than that!

      Installing Python

      Before we can program in Python, we need to install it. Let’s do that now.

      There are two major versions of Python: Python 2 and Python 3. Python 2 is an older version of Python and is no longer supported. In this book, we use Python 3, so you’ll need to install Python 3 on your computer.

      Python 3 was a major evolution from Python 2, but Python continues to change even within version 3. The first version of Python 3 was Python 3.0. Then Python 3.1 was released, then Python 3.2, and so on. At the time of writing, the latest version of Python 3 is Python 3.9. Versions as old as Python 3.6 will suffice for this book, but I encourage you to install and work with the latest version of Python.

      Follow these steps for your operating system to install Python.

      Windows

      Windows doesn’t come with Python by default. To install it, go to https://www.python.org/ and click Downloads. This should offer you the option of downloading the latest version of Python for Windows. Click the link to download Python and then run the installer. On one of the first screens in the installation process, click either Add Python 3.9 to PATH or Add Python to environment variables; this makes running Python much easier. (If upgrading Python, you may need to click Customize installation to find this option.)

      macOS

      macOS doesn’t come with Python 3 by default. To install it, go to https://www.python.org/ and click Downloads. This should offer you the option of downloading the latest version of Python for macOS. Click the link to download Python and then run the installer.

      Linux

      Linux comes with Python 3, but it may be an older version of Python 3. Installation instructions will vary depending on which Linux distribution you’re using, but you should be able to install the newest version of Python using your favorite package manager.

      How to Read This Book

      Reading this book from cover to cover in one sitting is likely to teach you very little. It would be like trying to learn piano by inviting someone into your house to play piano for a few hours and then kicking them out, lowering the lights, and serenading. That’s not how a practice-based skill is learned.

      Here is my advice for making your way through the book:

      Space out your work. Massing your practice into a small number of sessions is far less effective than spacing your practice out. When you feel tired, take a break. No one can tell you how much time to work before taking a break. No one can tell you how long it should take you to finish the book. It’s up to your own mind and body.

      Pause to test your understanding. Reading about something can give us the illusion that we understand it better than we do. Applying the material forces what we know and what we think we know into alignment. For that reason, at key points in each chapter, I’ve included multiple-choice concept check questions that ask you to make a prediction. Take these seriously! Read each question and commit to a response without checking anything using your computer. Then, read my answer and explanation. This is an opportunity to confirm that you’re on the right track. If you answer incorrectly or answer correctly but for the wrong reason, take time to remedy your understanding before continuing. This could involve playing around a little more with the relevant Python feature being discussed, rereading material from the book, or searching for additional explanations and examples online.

      Practice programming. Making predictions while you read will help solidify your understanding of key concepts. But you need more than that to become an adept problem-solver and programmer. You need to practice using Python to solve new problems, whose solutions you haven’t read about in the book. Each chapter concludes with a list of practice exercises. Please work through as many of these exercises as you can.

      Learning how to program takes time. Don’t be discouraged if you progress slowly or make a lot of mistakes. Don’t be intimidated by any blustering peacocks that you might encounter online. Surround yourself with people and resources that can help you learn.

      Using Programming Judges

      I’ve decided to structure this book around problems from programming judge websites. A programming judge website offers a repository of programming problems that can be solved by programmers around the world. You submit your solution—your Python code—and the site runs tests on your code. If your code produces the correct answer for each test case, then it’s likely that your solution is correct. If instead your code produces the wrong answer for one or more test cases, then your code is incorrect, and revisions are required.

      There are several reasons why I think programming judges are particularly suitable sites for learning programming:

      Rapid feedback Rapid, targeted feedback is crucial in the early stages of learning to program. Programming judges provide feedback as soon as you submit your code.

      High-quality problems I find the problems on programming judges to be high quality. Many problems are originally from competitive programming contests. Other problems are written by individuals who are associated with a programming judge or simply want to help others learn. See the Problem Credits appendix for the source of each problem that we’ll study.

      Quantity of problems The programming judges contain hundreds of problems. I’ve selected only a small number for this book. If you need more practice, trust me: the programming judges can provide it.

      Community features The programming judges enable users to read and respond to comments. If you’re stuck on a problem, browse the comments for hints dropped there by others. If you’re still stuck, consider posting a comment of your own asking for help. Once you’ve successfully solved a problem, your learning is not done! Many programming judges allow you to view the code that others have submitted. Dig through a few such submissions to see how they compare to yours. There are always multiple ways to solve a problem. Perhaps your way is most intuitive to you right now, but opening yourself to other possibilities is an important step toward programming mastery.

      Making Your Programming Judge Accounts

      We’ll use several programming judge websites throughout the book. That’s because each programming judge hosts some problems that are not found on other programming judges; we need multiple programming judges to cover all of the problems that I’ve chosen.

      Here are the programming judges that we’ll use:

      Each programming judge requires that you create an account before you can submit code. Let’s go through the process of creating your accounts now and learn a little about the judges while we’re at it.

      The DMOJ Judge

      The DMOJ judge is the judge we’ll use most often in the book. More than for any other judge, it’s worth your time exploring the DMOJ website and learning about what the judge offers.

      To create an account on the DMOJ judge, go to https://dmoj.ca/ and click Sign up. On the registration page that comes up, enter your username, password, and email address. This page also allows you to set your default programming language. We’ll exclusively be using the Python programming language in this book, so I suggest clicking Python 3 here. Click Register! to create your account. Once registered, you can use your username and password to log in to DMOJ.

      Each problem in the book begins by indicating the judge website where the problem can be found and the problem code that you should use to access it. For example, the first problem that we’ll work on in Chapter 1 is found on DMOJ and is problem dmopc15c7p2. To find this problem on DMOJ, click Problems, type dmopc15c7p2 in the search box, and click Go. You should see the problem as the only result. If you click the problem title, you should see the problem itself.

      When you’re ready to submit Python code for a problem, find the problem and click Submit solution. On the resulting page, paste your Python code into the text box and click Submit!. Your code will then be judged and the results shown.

      The Timus Judge

      To create an account on the Timus judge, go to https://acm.timus.ru/ and click Register. On the registration page that comes up, enter your name, password, email address, and other requested information. Click Register to create your account. Then, check your email for a message from Timus containing your judge ID. You’ll need your judge ID whenever you submit Python code.

      There’s currently no way to set your default programming language, so be sure to choose the available version of Python 3 whenever you submit Python code.

      We use the Timus judge only once, in Chapter 6, so I won’t say any more about it here.

      The USACO Judge

      To create an account on the USACO judge, go to http://usaco.org/ and click Register for New Account. On the registration page that comes up, enter your username, email address, and other requested information. Click Submit to create your account. Then, check your email for a message from USACO containing your password. Once you have your password, you can use your username and password to log in to USACO.

      There’s currently no way to set your default programming language, so be sure to choose the available version of Python 3 whenever you submit Python code. You’ll also need to choose the file containing your Python code rather than paste your code into a text box.

      We won’t be using the USACO judge until Chapter 7, so I won’t say any more about it here.

      About This Book

      Each chapter in the book is driven by two or three problems from a programming judge website. In fact, I start each chapter by posing our first problem, before teaching any new Python at all! My goal in doing this is to motivate you to want to learn the Python features that we need to solve the problem. Don’t worry if you’re not sure how to solve a problem after reading its description. (If you can’t solve the problem yet, then you’re reading the right book!) If you understand what the problem is asking you to do, then you’re all set. We’re going to learn Python and solve the problem together. Subsequent problems in the chapter may introduce further Python features or ask us to extend what we learned in the first problem. Each chapter concludes with exercises that you should solve on your own to practice what you just learned.

      Here’s a rundown of what we’ll learn in each chapter:

      Chapter 1: Getting Started There are quite a few introductory concepts that we’ll need to learn before we can solve any problems with Python. In this chapter, we’ll learn these concepts, including entering Python code, working with strings and numbers, using variables, reading input, and writing output.

      Chapter 2: Making Decisions In this chapter, we’ll learn about if statements, which allow our programs to decide what to do based on whether specific conditions are true or false.

      Chapter 3: Repeating Code: Definite Loops Many programs continue running as long as there is work to do. In this chapter, we’ll learn about the for loop, which lets our programs process each piece of input until the job is done.

      Chapter 4: Repeating Code: Indefinite Loops Sometimes we don’t know in advance how many times our program should repeat some specified behavior. for loops are not appropriate for these kinds of problems. In this chapter, we’ll learn about the while loop, which repeats code as long as a specific condition is true.

      Chapter 5: Organizing Values Using Lists A Python list allows us to use a single name to refer to a whole sequence of data. Using a list helps us organize our data and leverage the powerful list operations (such as sorting and searching) that Python provides. In this chapter, we’ll learn all about lists.

      Chapter 6: Designing Programs with Functions A large program, with lots of code, can become unwieldy if we don’t organize it well. In this chapter, we’ll learn about functions, which help us design programs composed of small, self-contained chunks of code. Using functions leads to programs that are much easier to understand and modify. We’ll also learn about top-down design, an approach to designing programs with functions.

      Chapter 7: Reading and Writing Files Files are convenient for providing data to our programs or obtaining data from our programs. In this chapter, we’ll learn how to read data from and write data to files.

      Chapter 8: Organizing Values Using Sets and Dictionaries As we begin to solve increasingly challenging problems, it’s important that we think about how our data is stored. In this chapter, we’ll learn about two new ways to store data using Python: using a set and using a dictionary.

      Chapter 9: Designing Algorithms with Complete Search Programmers don’t start from scratch for each problem they solve. Instead, they think about whether a general solution pattern—a type of algorithm—can be used to solve it. In this chapter, we’ll learn about complete-search algorithms, which can be used to solve a wide range of problems.

      Chapter 10: Big O and Program Efficiency Sometimes we’ll manage to write a program that does the right thing but does so too slowly to be useful in practice. In this chapter, we’ll learn how to communicate about the efficiency of programs, and we’ll learn about tools we can use to write more efficient code.

      1

      GETTING STARTED

      Programming involves writing code to solve a problem. As such, I want to solve problems with you from the outset. That is, rather than learning Python concept by concept and then solving a problem, we’re going to use a problem to dictate the concepts we need to learn.

      In this chapter, we’ll solve two problems: determining the number of words in a line (like the word-count feature in a word processor) and calculating the volume of a cone. Solving these problems requires a tour of quite a few Python concepts. You may feel that you need more details to fully understand some of what I introduce here and how it all fits together in the design of a Python program. Don’t worry: we’ll revisit and elaborate on the most important concepts in later chapters.

      What We’ll Be Doing

      As described in the introduction, we’ll be solving competitive programming problems using the Python programming language. The competitive programming problems can each be found on an online judge website. I assume that you’ve followed the instructions in the introduction to install Python and make your judge accounts.

      For each problem, we’ll write a program to solve it. Each problem specifies the kind of input that our program will be provided, and the kind of output (or result) that is expected. Our program correctly solves the problem if it can take any valid input and produce the correct output.

      In general, there will be millions or billions of possible inputs. Each such input is referred to as a problem instance. For example, in the first problem that we’ll solve, the input is a line of text, like hello there or bbaabbb aa abab. Our task will be to output the number of words in the line. One of the most powerful ideas in programming is that often a small amount of general-purpose code can solve a seemingly endless number of problem instances. Whether the line has 2 words or 3 or 50, it won’t matter. Our program will get it right every time.

      Our programs will perform three tasks:

      Read input We need to determine the specific instance of the problem that we’re solving, so we first read the provided input.

      Process We process the input to determine the correct output.

      Write output Having solved the problem, we produce the desired output.

      The boundaries between these steps may not always be crisp—we might have to interleave some processing with producing some output, for example—but it will be helpful to keep these three broad steps in mind.

      You likely use programs on a daily basis that follow this input-process-output model. Consider a calculator program: you type in a formula (the input), the program crunches your numbers (process), and the program displays the answer (output). Or consider a web search engine: you type in a search query (input), the search engine determines the most relevant results (process), and it displays them (output).

      Contrast these kinds of programs with interactive programs, which fuse input, processing, and output. For example, I’m typing this book using a text editor. When I type a character, the editor responds by adding that character to my document. It doesn’t wait for me to type the entire document before displaying it to me; it interactively displays it as I build it. We won’t be writing interactive programs in this book. If you’re interested in writing such programs after studying this book, you’ll be happy to hear that Python is certainly up for the task.

      The text for each problem is found both here and on the online judge. However, the text won’t match, because I’ve rewritten it for purposes of consistency throughout the book. Don’t worry: what I’ve written conveys the same information as the official problem statement.

      The Python Shell

      For each problem in the book, we want to write a program and save it in a file. But that assumes we know what program to write! For many of the problems in the book, we’ll need to learn some new Python features before we can solve the problem.

      The best way to experiment with Python features is by using the Python shell. It’s an interactive environment where you type some Python code and press ENTER, and Python shows you the result. Once we learn enough to solve the current problem, we’ll stop using the shell and start typing our solution in a text file instead.

      To begin, create a new folder on your desktop called programming. We’ll use that folder to store all of the work that we do for this book.

      Now, we’ll navigate to this programming folder and launch the Python shell. Follow these steps for your operating system whenever you’d like to start the Python shell.

      Windows

      On Windows, do the following:

      Hold down SHIFT and right-click your programming folder.

      From the resulting menu, click Open PowerShell window here. If that choice isn’t there, click Open command window here.

      At the bottom of the resulting window, you’ll see a line that ends with a greater-than sign (>). This is your operating system prompt, and it’s waiting for you to type a command. You type operating system commands here, not Python code. Be sure to press ENTER after each command.

      You’re now in your programming folder. You can type dir (for directory) if you’d like to see what’s there. You shouldn’t see any files yet, because we haven’t created any.

      Now, enter python to start the Python shell.

      When you start the Python shell, you should see something like this:

      Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:30:23)

      [MSC v.1928 32 bit (Intel)] on win32

      Type help, copyright, credits or license for more information.

      >>>

      What’s important here is that you see a Python version of at least 3.6 in the first line. If you have an older version, especially 2.x, or if Python doesn’t load at all, please install a recent version of Python following the instructions in the introduction.

      At the bottom of this window, you’ll see a >>> Python prompt. This is where you type Python code. Never type the >>> symbols yourself. Once you’re done programming, you can press CTRL-Z and then press ENTER to quit.

      macOS

      On macOS, do the following:

      Open Terminal. You can do that by pressing COMMAND-spacebar, typing terminal, and then double-clicking the result.

      In the resulting window, you’ll see a line that ends with a dollar symbol ($). This is your operating system prompt, and it’s waiting for you to type a command. You type operating system commands here, not Python code. Be sure to press ENTER after each command.

      You can enter the ls command to obtain a list of what’s in the current folder. Your Desktop should be listed there.

      Enter cd Desktop to navigate to your Desktop folder. The cd command stands for change directory; directory is another name for folder.

      Enter cd programming to navigate to your programming folder.

      Now, enter python3 to start the Python shell. (You could also try entering python, without the 3, but that might start up an older version of Python 2. Python 2 is not suitable for working through this book.)

      When you start the Python shell, you should see something like this:

      Python 3.9.2 (default, Mar 15 2021, 17:23:44)

      [Clang 11.0.0 (clang-1100.0.33.17)] on darwin

      Type help, copyright, credits or license for more information.

      >>>

      What’s important here is that you see a Python version of at least 3.6 in the first line. If you have an older version, especially 2.x, or if Python doesn’t load at all, please install a recent version of Python following the instructions in the introduction.

      At the bottom of this window, you’ll see a >>> Python prompt. This is where you type Python code. Never type the >>> symbols yourself. Once you’re done programming, you can press CTRL-D to quit.

      Linux

      On Linux, do the following:

      Right-click your programming folder.

      In the resulting menu, click Open in Terminal. (You can also open the terminal and navigate to your programming folder if you’re more comfortable with that.)

      At the bottom of the resulting window, you’ll see a line that ends with a dollar sign ($). This is your operating system prompt, and it’s waiting for you to type a command. You type operating system commands here, not Python code. Be sure to press ENTER after each command.

      You’re now in your programming folder. You can type ls if you’d like to see what’s there. You shouldn’t see any files yet, because we haven’t created any.

      Now, enter python3 to start the Python shell. (You could also try entering python, without the 3, but that might start up an older version of Python 2. Python 2 is not suitable for working through this book.)

      When you start the Python shell, you should see something like this:

      Python 3.9.2 (default, Feb 20 2021, 20:57:50)

      [GCC 7.5.0] on linux

      Type help, copyright, credits or license for more information.

      >>>

      What’s important here is that you see a Python version of at least 3.6 in the first line. If you have an older version, especially 2.x, or if Python doesn’t load at all, please install a recent version of Python following the instructions in the introduction.

      At the bottom of this window, you’ll see a >>> Python prompt. This is where you type Python code. Never type the >>> symbols yourself. Once you’re done programming, you can press CTRL-D to quit.

      Problem #1: Word Count

      Now it’s time for our first problem! We’re going to use Python to write a little word-count program. We’ll learn how to read input from the user, process the input to solve the problem, and output the result. We’ll also learn how to manipulate text and numbers in our programs, make use of built-in Python operations, and store intermediate results on our way to the solution.

      This is DMOJ problem dmopc15c7p2.

      The Challenge

      Count the number of words provided. For this problem, a word is any sequence of lowercase letters. For example, hello is a word, but so are non-English words like bbaabbb.

      Input

      The input is one line of text, consisting of lowercase letters and spaces. There is exactly one space between each pair of words, and there are no spaces before the first word or after the last word.

      The maximum length of the line is 80 characters.

      Output

      Output the number of words in the input line.

      Strings

      Values are a fundamental building block of Python programs. Each value has a type, and the type determines the operations that can be performed on the value. In the Word Count problem, we’re working with a line of text. Text is stored as a string value in Python, so we’ll need to learn about strings. To solve the problem, we output the number of words in the text, so we also need to learn about numeric values. Let’s begin with

      Enjoying the preview?
      Page 1 of 1