Chapter 4. Making Decisions – Python Control Flows

Congratulations! In Chapter 3, Calculate This!, you wrote a calculator program. If you followed the instructions and corrected your errors, then you have a program that runs all of the mathematical functions with two numbers. While this is great for a first program, that sort of a limited calculator doesn't give a user much choice. When the user runs the calculator, the program will not end until all five functions have run or until the program ends due to an error.

What if, instead of doing the entire math, we could program our calculator to perform certain operations based on the way the users answer our questions? As programmers, we can use Python to interpret user data and change the way the program operates. In this chapter, you will learn how to use control flows so that our calculator program can make choices and only run the code that the user chooses.

At the end of this chapter, you will have a calculator program that can choose which mathematical operations to perform based on what the user wants to do. You will be able to customize this program on the basis of how you use the control flows.

Is it equal, not equal, or something else?

Before you learn about conditional statements, you need to realize that computers make decisions based on comparison operators. These help us compare two things so that the computer can make a decision about what to do next. Here is a list of operators:

Comparison Operators

Less than

<

Less than or equal to

<=

Greater than

>

Greater than or equal to

>=

Equal to

==

Not equal to

!=

Each of these operators allows us to compare two values. The most confusing operator is the equal to operator because it uses two equals signs. The reason for this is that when we set a variable, we use one equal sign. We do not want the computer to get confused when we are comparing two values, so we use two equals signs. When we use the comparison operators with if, elif, and else, our program can be written to make better decisions.

To take a look at how these operators work in real life, open up your Python shell and type the following lines of code:

1 < 1
1 <= 1
1 > 1
1 >= 1
1 == 1
1 != 1

After each line of code, the words True or False will print. Take a look at the following screenshot for answers to how the statements evaluate using the number 1. Experiment with other numbers to take a look at what happens and to learn about the operators and what they do:

Is it equal, not equal, or something else?
..................Content has been hidden....................

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