Chapter 1. Starting to Code: Finding your way

image with no caption

Writing programs gives you the power to control your PC.

Almost everyone knows how to use a computer, but few people take the next step and learn how to control it. If you use other people’s software, you will always be limited by what other people think you want to do. Write your own programs and the only limit will be your own imagination. Programming will make you more creative, it will make you think more precisely, and it will teach you to analyze and solve problems logically.

Do you want to be programmed or be the programmer?

Programming lets you do more

You’ve got problems to solve and work to do, but your existing software doesn’t quite cut it. Even with all those programs on your computer, you still need to do something different, something specific to you.

image with no caption
image with no caption
image with no caption
image with no caption

You want to do more with your computer. You want to take control.

Learning to program gives you the power to create and solve.Learning to program puts you in charge.

But, how does programming work?

Let’s look at a simple game written in Python.

But what are g and guess?

You might be wondering what g and guess are in the code. They are called variables and they’re used to keep track of data in the computer’s memory.

image with no caption

Watch it!

Be careful with = signs in code.

Programming languages use = signs for different purposes. In most languages (including Python), a double equals (==) is a test for equality. It means, “are these two things equal?” In contrast, a single equal (=) is an instruction (known as assignment) that means “set the value to.”

A variable is really just a label for data. So if the user inputs “3” at the keyboard, then guess will be set to the number 3, and whenever the computer reads guess, it will read it as the value 3.

So how do you run your code?

There are two things that you will need to run the guessing-game program: an editor and an interpreter.

The editor saves the code you write into a file on your hard disk. The code (sometimes called the source code) is just text, and it can be written and read by humans.

image with no caption

But computers can’t process text meant for humans, at least not very well. That’s why we need a tool to translate the human-friendly source code into the binary 1s and 0s that computers do understand. That’s what an interpreter does. In this book, an interpreter called Python is used.

image with no caption

So we need an editor and a Python interpreter. Fortunately, Python 3 comes with a built-in application called IDLE, which does both jobs and more. IDLE enables you to write and edit Python code, it translates this code into binary form, and finally, it runs the Python 3 program. Because of this, IDLE is known as an Integrated Development Environment.

Let’s see these steps in action.

Create a new program file

When you first start IDLE, it displays a window called the Python Shell. Select the New Window option from the Python Shell File menu, which creates a new edit window for you. Input your program code as text into this edit window and you’ll be on your way.

image with no caption

Do this!

Go ahead and open a new IDLE edit window and type in the code from Sharpen your pencil.

Prepare and run your code

The next step is to prepare your program code for execution. To do this, select FileSave from the menu to save your program code to a file. Choose an appropriate name for your program.

image with no caption

Python programs are usually saved in files that end with .py, so let’s call this program game.py.

It doesn’t really matter to IDLE which directory you save the file in. Some coders like to create special directories for each new programming project. But for now, just save the code in some directory that’s easy to remember.

Now, let’s see what happens when we run the program.

image with no caption
image with no caption

The program needs to do more.

At the moment, the guessing game tells the user whether his guess is right or wrong, but nothing more than that. It might be more helpful if the program displayed more informative messages, such as whether the guess is higher or lower than the correct answer. That would help the user to hone in on the right answer the next time the program is run.

We can do this by changing the code. But in what way?

image with no caption

Brain Power

Think about the original code. You will need to use more than just print() commands to provide more informative feedback. What else will you need?

A program is more than a list of commands

You could create a program that was simply a list of commands. But you almost never will. This is because a simple list of commands can only be run in one direction. It’s just like driving down a straight piece of road: there’s really only one way of doing it.

image with no caption

But programs need to be much smarter than that.

Codeville: Your program is like a network of roads

Programs need to do different things under different circumstances. In the game, the code displays “You win!” if the user guesses the number correctly, and “You lose!” if not. This means that all programs, even really simple programs, typically have multiple paths through them.

image with no caption

A path refers to the set of instructions that the computer will actually follow (or execute). Your code is like a street network, with lots of sections of code connected together just like the streets in a city. When you drive through a city, you make decisions as to which streets you drive down by turning left or right at different intersections. It’s the same for a program. It also needs to make decisions from time to time as to which path to take, but for your code, it is not like driving along a road, it’s executing a particular path.

Let’s look in more detail at how a program decides which path to take.

Branches are code intersections

Driving down a street is easy. You need to make a decision only when you get to an intersection. It’s the same for your program. When a program has a list of commands, it can blindly execute them one after another. But sometimes, your program needs to make a decision. Does it run this piece of code or that piece of code?

These decision points are called branches, and they are the road intersections in your code.

image with no caption

Your program makes a decision using a branch condition. A branch condition has the value true or false. If the branch condition is true, it runs the code on the true branch. And if the branch condition is false, it runs the code on the false branch.

image with no caption

if/else branches

image with no caption

You need to amend the game program to give more informative messages to the user.

But what will the paths in the program look like?

The Python code needs interconnecting paths

The solution’s mapped out, and now we know that the program code will need to have paths that match this:

image with no caption

But isn’t there a problem here? In the design there are many interconnecting paths, but so far, we have only written code that contains just one branch:

if guess == 5:
    print("You win!")
else:
    print("You lose!")

In the new code, we will need to connect two branches together. We need the second branch to appear on the false path of the first.

image with no caption

So how do you connect branches together in Python?

Python uses indents to connect paths

The code inside the if and else statements is indented. This isn’t just to make the code pretty. In Python, indents matter. Let’s consider a different piece of example code: something that will decide if you can drive downtown. Python uses indents to connect a sequence of commands together to form paths.

image with no caption

So how do you connect branches together? You simply indent the second branch in by one more level.

image with no caption

Watch it!

Indents matter in Python.

Be careful how you indent code in Python; if you don’t indent your code correctly, your code might do something wildly different from what you expect.

You should now have enough information to go fix the code, but before we do that, let’s take a look at how IDLE helps you indent code.

image with no caption

The users still don’t like it.

The program works, and now generates extra feedback, but there’s a problem. If the users want to have another guess, they have to run the program again. They really want the program to keep asking them for another guess until they finally get the correct answer.

Can you see what the problem is?

How do we get the computer to do something repeatedly? Should we just make a copy of the code and paste it at the end of the file? That would make sure the user is asked twice. But what if they need to make 3 guesses? Or 4 guesses? Or 10,000 guesses? What about the case where the guess is correct?

The guessing game program needs to be able to run some code repeatedly.

image with no caption

Loops let you run the same piece of code over and over again

Programs often need to keep running the same piece of code many times. In addition to branches, programming languages also provide loops.

Loops are a little like branches. Just like branches, loops have a condition (the loop condition) that is either true or false. Also, like the if part of branches, if the loop condition is true, then a loop will run a given piece of code. For a branch, this code is called the body. For a loop, it’s called the loop body.

image with no caption

The big difference between a loop and a branch is how many times it runs the code associated with it. A branch will run its code only once. But a loop will run the loop body, then check the loop condition again and, if it’s still true, it will run the loop body again. And again. And again. In fact, it will keep running the loop body until the loop condition becomes false.

Python’s while loop

Programming languages have lots of different ways of creating loops, but one of the simplest ways in Python is to use a while loop. Here’s an example:

image with no caption

This is what the loop looks like when you write it as a Python while loop. The code keeps asking the question “Are we there?” until the user types something other than no. This is what it looks like when it runs:

image with no caption

Did you notice that you had to set the value of the answer variable to something sensible before you started the loop? This is important, because if the answer variable doesn’t already have the value no, the loop condition would have been false and the code in the loop body would never have run at all.

Bear that in mind. It might be useful in this next exercise...

Your Programming Toolbox

You’ve got Chapter 1 under your belt. Let’s look back at what you’ve learned so far.

Programming Tools

* Programs are created from code statements:

  • commands do things.

  • branches decide things.

  • loops repeat things.

* Conditionals help you decide if

  • something is True or False.

* Assignment sets a name to a value.

* A named value is stored in a “variable”.

Python Tools

* if/else branches

* while loops

* = assignment operator

* == equality operator

* != inequality operator

* > greater than operator

* print() displays a message on screen

* input() gets and returns user input

* int() converts characters to numbers

* randint() produces a random number

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.66.206