Learn to Program using Python: Let's Do Numbers
Something for everyone
There is something for just about everyone here. Beginners start at the beginning, and experienced programmers jump in further along. Learn to Program using Python: Lesson 1, Getting Started provides an overall description of this online programming course.
Because this course is designed for beginning programmers, I am going to take it slow and easy for the first few lessons. My discussion will be informal, and will be designed to get you familiar and comfortable with the Python interactive programming environment. Later on, I will get a little more formal.
A programmable calculator
I am going to start out by showing you how to use Python as a programmable calculator. In the process, I will introduce you to some programming concepts, such as operators that I will explain in a more formal way in subsequent lessons.
Start the interactive Python environment
The first thing that you need to do is to start the interactive programming environment. If you have forgotten how to do that, see Lesson 1.
There are two ways to start the interactive Python environment from the Windows Start menu. You can either:
- Select IDLE (Python GUI), or
- Select Python (command line).
The >>> that you see on the last line is the Python interactive prompt, which I will refer to simply as the prompt.
Before we go any further, I need to introduce you to the concept of program comments.
In programming jargon, a comment is text that you insert into the program that is intended for human consumption only. Comments provide a quick and easy form of documentation. They are ignored by the computer and are intended to explain what you are doing.
How useful are comments?
Comments aren't terribly useful when doing interactive programming. Presumably you already know what you and doing and don't need to explain it to yourself using comments.
However, comments are very useful when you are writing scripts that you will store in files and use again later after you have forgotten how you did what you did.
In these lessons, I will use comments occasionally to explain what I am doing for your benefit, even in interactive mode.
What is the comment syntax?
According to The Python Reference Manual "A comment starts with a hash character (#) ... and ends at the end of the physical line.
Figure 2 shows a Python comment along with a new kind of prompt.
What is that ... thing?
The interactive mode actually uses two different kinds of prompts.
- One is >>>
- The other is ...
How much is 2+5
Enter 2+5 at the prompt and press the Enter key. You should see something like Figure 3 on your screen:
Input and output
To begin with, we need to differentiate between input and output. Everything that appears on a line with one of the prompts is input to the Python interpreter. (You typed it, so you know that it is input.)
Everything that appears on a line without a prompt is output from the interpreter. (You didn't type it. The interpreter produced it, so it was output.)
What was the input in this case?
Your input was the expression 2+5.
What was the output?
Python evaluated that expression and produced an output, which was the sum of 2 and 5, or 7.
Then Python presented you with a new prompt to allow you to provide more input.
Mixing comments and expressions
Now try entering the comment, followed by the expression that you see in Figure 4, and note the difference in the prompts.
My only reason for showing you this at this time is to give you some experience in mixing comments and expressions.
Command line versus GUI
The text in Figure 4 was produced using the Python (command line) window. I don't get exactly the same behavior (with respect to prompts) when I use the Python GUI Shell under Windows NT. Rather, what I get is shown in Figure 5. (Note the missing ... prompt.)
I believe that the command-line version is the more correct of the two.
Let's get technical
But not too technical. Computer programs are made up of statements.
Statements are composed of expressions.
(Later we will learn that large Python programs are made up of smaller programs called modules, which are made up of statements, which are composed of expressions.)
Statement ends at the end of the line
In Python, a statement normally end at the end of the line that contains it (although there are exceptions to this rule).
For the time being, suffice it to say that expressions are made up of
- literal values,
- operators, and
What are operators?
If you have ever used a hand calculator, you already know what operators are. The plus sign is an operator in the expression shown in Figure 6.
In programming jargon, operators are said to operate on operands.
What are operands?
In Figure 6, the 2 is the left operand and the 5 is the right operand of the plus operator.
Unary and binary operators
Normally, operators are said to be either unary or binary.
A unary operator has only one operand while a binary operator has two operands.
Some can be either
Some operators, such as the minus sign, can be either unary or binary operators.
In its unary mode with a single operand, a minus sign is usually a sign changing operator, while in its binary mode with two operands, a minus sign is usually a subtraction operator.
All of the operators discussed in this lesson are being used as binary operators.
Some arithmetic operators
Python has numerous operators. You can find a complete list of operators in the Python Reference Manual.
For the time being, we will concentrate on the follow arithmetic operators:
- The addition operator, +
- The subtraction operator, -
- The multiplication operator, *
- The division operator, /
- The modulus operator, %
If you add 2 and 5, you get 7. If you subtract 5 from 2, the answer is 3. If you multiply 2 by 5, you get 10
The next result, shown in Figure 8, may surprise you until I explain it. In this case, we are dividing the integer (whole number) 2 by the integer 5 producing an integer result.
Normally, a hand calculator would tell you that the answer is 0.4, but that is not an integer result. Rather, it is a decimal fraction.
As you can see in Figure 8, Python tells you that the result of dividing the integer 2 by the integer 5 is 0.
Remember long division?
Think back to when your second grade teacher taught you how to do long division with whole numbers. She told you that if you divide 2 by 5, you get a quotient of 0 and a remainder of 5. Or, if you divide 23 by 4, you get a quotient of 5 and a remainder of 3. That is what we are talking about here.
The modulus operator
And that brings us to the modulus operator (%).
Try entering the expressions shown in Figure 9. (You don't need to enter the comments. They are there to explain what is going on. But it wouldn't hurt for you to enter a few, just for practice.)
What does the modulus do?
The purpose of the modulus operator is to produce the remainder resulting from an integer division.
As you can see from this example in Figure 9, the division operator produced the integer quotient of 5, and the modulus operator produced the remainder of 3 (just like your second-grade teacher told you it should).
What if you don't want to produce an integer quotient and a remainder? What if you really want to produce a decimal quotient the way hand calculators do.
This is easy to do. Just represent either the numerator or the denominator or both as a decimal value and Python will automatically convert to decimal arithmetic mode as shown in Figure 10.
Note that in the first expression, I changed the numerator from 2 to 2.0 (I could have left off the zero, but adding the zero makes the decimal point easier to spot). This caused Python to perform decimal arithmetic instead of integer arithmetic, producing the decimal quotient value of 0.4.
I did essentially the same thing to the denominator in the second expression, producing the same result.
Grouping terms with parentheses
What is the result of evaluating the expression shown in Figure 11?
Try it on your hand calculator. (You will probably need to use an X instead of an * to indicate multiplication.) My hand calculator gives an answer of 32.
Now try it with Python and you should get the result shown in Figure 12.
This answer doesn't match the answer given by my hand calculator, and I'll bet that it doesn't match your calculator either unless you are using a fancy scientific calculator.
The answer depends on the order in which you perform the various arithmetic operations. Ordinary hand calculators usually do the arithmetic in the order that the terms are fed into the keyboard.
However, most computer programming systems, including Python, use a precedence system to decide which operations to perform first, which operations to perform second, etc.
I'm not going to go into the Python precedence system in detail. (If you are interested in the order of precedence of all the operators, you can find a precedence table in the Python Reference Manual.)
Rather, I am going to show you how to group terms using parentheses so that you can control the order of operations without worrying about the precedence system.
A sample grouping
The Python code fragment in Figure 13 shows how I can produce both results simply by grouping terms using parentheses.
The first expression produces 32 as produced by the hand calculator. The second expression produces 23 as produced by the earlier Python expression.
A Python expression is evaluated by first evaluating each of the sub-expressions inside the parentheses and then using those values to complete the evaluation.
Forcing addition to be performed first
In the first expression, I forced Python to perform the addition first by placing the addition inside the parentheses. This produced an intermediate value of 8 when the sub-expression inside the parentheses was evaluated. The remaining part of the overall expression was then evaluated by multiplying the intermediate value by 4, producing a result of 32.
Forcing multiplication to be performed first
In the second expression, I forced Python to perform the multiplication first (which it always does first anyway, but the parentheses make that more obvious). This produced an intermediate value of 20. The remaining part of the overall expression was then evaluated by adding the intermediate value to 3 producing an output of 23.
Hopefully, you get the picture. By using parentheses to group the terms in an expression, you have total control over the order in which the arithmetic operations are performed, without having to memorize a precedence table.
Parentheses can be, and often are nested to provide greater control over the order of the operations as shown in Figure 14.
In this case, Python evaluates the expressions inside the innermost parentheses first, and then works from the inside out evaluating each pair of parentheses along the way.
Negative integer division
When I learned to do long division in the second grade, I didn't know about positive and negative numbers yet, so I didn't learn about remainders when one of the operands is negative and the other is positive. I suspect that you didn't either.
Figure 15 shows how negative integer division and modulus works in Python.
The remainder may be surprising
The quotient shouldn't be a surprise, but the remainder may be surprising when the numerator and denominator have different algebraic signs.
An exercise for the student...
I'm not going to try to explain it. I just want to make you aware that the behavior of integer division and integer modulus is different when the operands have different signs. I will leave it as an exercise for the student to think about this and come to a mental reconciliation with the facts as presented here.
Sometimes, you may make an error and enter an expression that can't be evaluated. In this case, you will get an error message. A typical error message is shown in Figure 16.
Briefly, this error message means that the Python interpreter doesn't know how to add the value 3 to the value 5a. I will discuss error messages in more detail in a subsequent lesson. I just wanted to show you a programming error here at the beginning.
Mono spaced font
You may have noticed that the font that I used in Figure 16 is different from the font that I have been using in previous examples.
In the previous examples, I have used a font that allows me to put more information on each line in order to accommodate a narrow page format. However, that font does not allocate the same amount of space to each character. Narrow characters consume less space than wider characters. (That explains why I am able to get more text on each line.)
Note the pointer
In this case, I needed a font that allocates the same amount of space for each character so that the little pointer (^) below the a will be in the correct spot. This pointer is Python's way of giving you a hint as to where the error occurred.
1. Python programming comments are ignored by the computer, True or False?
Ans: True. Programming comments are used for program documentation and are intended for human consumption.
2. Just like in C, C++, and Java, a Python comment begins with two slash characters (//) and continues to the end of the line, True or False?
Ans: False. In Python, a comment starts with the hash character (#) and ends at the end of the line.
3. The only prompt used by the Python interactive system is the one consisting of three right-angle brackets (>>>), True or False?
Ans: False. The Python interactive system also uses a secondary prompt consisting of three periods (...).
4. The output produced by the Python interactive system appears on a line without either of the prompts mentioned above, True or False?
5. If you enter an expression at the prompt and press the Enter key, the result of evaluating the expression will be displayed on the next line without a prompt, True or False?
Ans: True, unless the expression can't be evaluated, in which case an error message will appear.
6. Computer programs are composed of expressions, which are made up of statements, True or False?
Ans: False. Just the reverse is true. Programs are made up of statements, which are composed of expressions.
7. In the following expression, 2+5, what is the common jargon for the plus sign, and what is the common jargon for the 2 and the 5?
Ans: The plus sign is commonly called the operator. The 2 and the 5 are commonly called operands. More specifically, the 2 is the left operand and the 5 is the right operand.
8. List the operators discussed in this lesson, and describe the purpose of each.
- The addition operator, +
- The subtraction operator, -
- The multiplication operator, *
- The division operator, /
- The modulus operator, %
Ans: False. Integer division produces an integer result.
10. Describe how to force Python division to produce a decimal result.
Ans: Represent either the numerator, the denominator, or both as a decimal value, appending a decimal point and a 0 if necessary to cause it to be represented as a decimal value (actually, the decimal point alone is sufficient, but the zero makes the decimal point easier to detect visually).
11. The modulus operator is used to produce the quotient in division, True or False?
Ans: False, the modulus operator is used to produce the remainder.
12. Describe the use of parentheses in expressions.
Ans: Parentheses can be used to group terms in an expression in order to provide control over the order in which the operations are performed.
13. Describe how Python evaluates an expression containing parentheses.
Ans: A Python expression is evaluated by first evaluating each of the sub-expressions in the parentheses, and then using those values to complete the evaluation. If the expression contains nested parentheses, the evaluation is performed by evaluating the innermost parentheses first and working outwards from there.
Copyright 2000, Richard G. Baldwin. Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.
About the authorRichard Baldwin is a college professor and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.
Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two. He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas. He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.
Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.
This article was originally published on Developer.com in April of 2000.