• No results found

Elements of Programs

In document Python Programming for Starters (Page 33-36)

Writing Simple Programs

2.3 Elements of Programs

Now that you know something about the programming process, you are almost ready to start writing programs on your own. Before doing that, though, you need a more complete grounding in the fundamentals of Python. The next few sections will discuss technical details that are essential to writing correct programs. This material can seem a bit tedious, but you will have to master these basics before plunging into more interesting waters.

2.3.1 Names

You have already seen that names are an important part of programming. We give names to modules (e.g., convert) and to the functions within modules (e.g., main). Variables are used to give names to values (e.g., celsius and fahrenheit). Technically, all these names are called identifiers. Python has some rules about how identifiers are formed. Every identifier must begin with a letter or underscore (the “_” character) which may be followed by any sequence of letters, digits, or underscores. This implies that a single identifier cannot contain any spaces.

According to these rules, all of the following are legal names in Python:

x

celsius spam spam2

SpamAndEggs Spam_and_Eggs

Identifiers are case-sensitive, so spam, Spam, sPam, and SPAM are all different names to Python.

For the most part, programmers are free to choose any name that conforms to these rules. Good programmers always try to choose names that describe the thing being named.

One other important thing to be aware of is that some identifiers are part of Python itself.

These names are called reserved words or keywords and cannot be used as ordinary identifiers. The complete list of Python keywords is shown in Table 2.1.

2.3. Elements of Programs 25

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except in raise

Table 2.1: Python Keywords

2.3.2 Expressions

Programs manipulate data. So far, we have seen two different kinds of data in our example pro-grams: numbers and text. We’ll examine these different data types in great detail in later chapters.

For now, you just need to keep in mind that all data has to be stored on the computer in some digital format, and different types of data are stored in different ways.

The fragments of program code that produce or calculate new data values are called expressions.

The simplest kind of expression is a literal. A literal is used to indicate a specific value. In chaos.py you can find the numbers 3.9 and 1. The convert.py program contains 9, 5, and 32. These are all examples of numeric literals, and their meaning is obvious: 32 represents, well,32 (the number 32).

Our programs also manipulated textual data in some simple ways. Computer scientists refer to textual data as strings. You can think of a string as just a sequence of printable characters. A string literal is indicated in Python by enclosing the characters in quotation marks (""). If you go back and look at our example programs, you will find a number of string literals such as: "Hello" and

"Enter a number between 0 and 1: ". These literals produce strings containing the quoted characters. Note that the quotes themselves are not part of the string. They are just the mechanism to tell Python to create a string.

The process of turning an expression into an underlying data type is called evaluation. When you type an expression into a Python shell, the shell evaluates the expression and prints out a textual representation of the result. Consider this small interaction:

>>> 32 32

>>> "Hello"

’Hello’

>>> "32"

’32’

Notice that when the shell shows the value of a string, it puts the sequence of characters in single quotes. This is a way of letting us know that the value is actually text, not a number (or other data type). In the last interaction, we see that the expression "32" produces a string, not a number. In this case, Python is actually storing the characters “3” and “2,” not a representation of the number

26 Chapter 2. Writing Simple Programs 32. If that’s confusing right now, don’t worry too much about it; it will become clearer when we discuss these data types in later chapters.

A simple identifier can also be an expression. We use identifiers as variables to give names to values. When an identifier appears as an expression, its value is retrieved to provide a result for the expression. Here is an interaction with the Python interpreter that illustrates the use of variables as expressions:

>>> x = 5

>>> x 5

>>> print(x) 5

>>> print(spam)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name ’spam’ is not

First the variable x is assigned the value 5 (using the numeric literal 5). In the second line of interaction, we are asking Python to evaluate the expression x. In response, the Python shell prints out 5, which is the value that was just assigned to x. Of course, we get the same result when we explicitly ask Python to print x using a print statement. The last interaction shows what happens when we try to use a variable that has not been assigned a value. Python cannot find a value, so it reports a NameError. This says that there is no value with that name. The important lesson here is that a variable must always be assigned a value before it can be used in an expression.

More complex and interesting expressions can be constructed by combining simpler expressions with operators. For numbers, Python provides the normal set of mathematical operations: addition, subtraction, multiplication, division, and exponentiation. The corresponding Python operators are:

+, -, *, /, and **. Here are some examples of complex expressions from chaos.py and convert.py 3.9 * x * (1 - x)

9/5 * celsius + 32

Spaces are irrelevant within an expression. The last expression could have been written 9/5*celsius+32 and the result would be exactly the same. Usually it’s a good idea to place some spaces in expres-sions to make them easier to read.

Python’s mathematical operators obey the same rules of precedence and associativity that you learned in your math classes, including using parentheses to modify the order of evaluation. You should have little trouble constructing complex expressions in your own programs. Do keep in mind that only the round parentheses are allowed in numeric expressions, but you can nest them if necessary to create expressions like this.

((x1 - x2) / 2*n) + (spam / k**3)

By the way, Python also provides operators for strings. For example, you can “add” strings.

In document Python Programming for Starters (Page 33-36)