Chapter 2

Python Program Components

Let’s look at another Python program that creates short nonsense sentences:

Listing 2.1: Mad Lib

 1 # madlib.py
 2 # Your Name
 3
 4 adjective = input("Enter an adjective: ")
 5 noun = input("Enter a noun: ")
 6 verb = input("Enter a verb: ")
 7 adverb = input("Enter an adverb: ")
 8 print("A", adjective, noun, "should never", verb, adverb)

Type this program into your Python environment, save it as madlib.py, and run it a few times to play with it. Enter any responses you like when the interpreter asks for them. Then consider the following aspects of both this program and Listing 1.1.

Variables

Every program accomplishes its work by manipulating data. Variables are names that refer to data in memory. Variable names, also known as identifiers in Python, may consist of upper and lower alphabetic characters, the underscore (_), and, except for the first character, the digits 0–9. There is a small set of reserved Python keywords that may not be used as variable names; otherwise, you are free to choose any names you wish. You should already be able to see how meaningful identifiers can make a program easier to follow. The variables in Listing 2.1 are adjective, noun, verb, and adverb.

Program Statements and Syntax

A program is a sequence of statements, which are individual commands executed one after another by the Python interpreter. Every statement must have the correct syntax; the syntax of any language is the precise form that it is written in. Thus, if a statement does not have the correct form, the Python interpreter will respond with a syntax error. Three types of statements are used in Listings 1.1 and 2.1:

Assignment statements are used to give variables a value. The syntax of an assignment statement is:

<variable> = <expression>

Read assignment statements from right to left:

  1. Evaluate the expression on the right.
  2. Assign the variable on the left to refer to that value.

For example, the assignment

x = 10 − 17 + 5

computes the right side to be −2 and then assigns x to refer to −2.

⇒ Caution: An assignment statement “=” is not like a mathematical equals sign. Technically, it is a delimiter because it helps the interpreter delimit between the variable on the left and the expression on the right.

Print statements are used to produce program output. The syntax of a print() statement is:

print(<expression1>, <expression2>, ...)

Expressions inside quotation marks (either single or double) are printed literally, whereas expressions outside quotation marks have their value printed. Expressions are separated by single spaces in the output, and each print statement produces output on a separate line.

Technically, print() is a built-in function that we call in order to print, but it is generally called as its own separate statement.

Import statements are used to access library functions or data, as in the first line of Listing 1.1. The Python Standard Library consists of many modules, each of which adds a specific set of additional functionality. The statement:

from <module> import <name1>, <name2>, ...

allows the listed names to be used in your program.

The math module includes the constant pi and functions such as sin, cos, log and exp. Both import and from are reserved Python keywords and so may not be used as the names of variables. Keywords appear in bold in program listings.

Data Types

Listings 1.1 and 2.1 use three different types of data:

Strings are sequences of characters inside single or double quotation marks.

Integers are whole number values such as 847, −19, or 7.

Floats (short for “floating point”) are values that use a decimal point and therefore may have a fractional part. For example, 3.14159, −23.8, and even 7.0 (because it has a decimal point) are all considered floats.

A variable in Python may refer to any type of data.

Expressions

Recall that the right-hand side of every assignment statement must be an expression, which in Python is just something that can be evaluated to give a value.

Input expressions are used to ask the user of a program for information. They almost always appear on the right side of an assignment statement; using an input expression allows the variable on the left side to refer to different values each time the program is run.

input(prompt)

Display prompt and return user input as a string.

The prompt is printed to alert the user that the program is waiting for input.

Numeric expressions use the arithmetic operations +, −, *, /, //, and ** for addition, subtraction, multiplication, division, integer division, and raising to a power. These follow the normal rules of arithmetic and operator precedence: exponentiation is done first, then multiplication and division (left to right), and finally addition and subtraction (also left to right). Thus, 1 + 2 * 3 evaluates to 7 because multiplication is done before addition. Parentheses may be used to change the order of operations.

Integer division rounds down to the nearest integer, so 7//2 equals 3 and −1//3 equals −1. Integer division applied to floats rounds down to the nearest integer, but the result is still of type float.

Finally, variables must be assigned a value before being used in an expression.

Comments

Comments begin with a pound sign # and signify that whatever follows is to be completely ignored by the interpreter.

# Text that helps explain your program to others

Comments may appear anywhere in a Python program and are meant for human readers rather than the interpreter, in order to explain some aspect of the code.

Recap

There was a lot of terminology here, so let’s summarize what is most important:

  1. Variables refer to data. . .
  2. . . . via assignment statements. Remember to read them from right to left.
  3. Data can be of type string, integer, or float (so far). The data type of a variable determines what you can do with it.

Exercises

  1. 2.1 Give three names that are not legal Python identifiers.
  2. 2.2 Use Listing 1.1 to:
    1. (a) List each variable and give the type of data stored in it. Hint: pi is a variable.
    2. (b) Identify the assignment statements, and explain the effect of each.
  3. 2.3 Determine the output of Listing 1.1 if the print() statement is changed to:
     print("The area of a circle with radius r is area")

    Explain the result.

  4. 2.4 Use Listing 2.1 to:
    1. (a) List each assignment statement and identify the variable whose content changes in each.
    2. (b) Describe what happens if the final space in any of the input statements is deleted.
  5. 2.5 Determine the value of each of these Python expressions:
    1. (a) 1+2*34*5+6
    2. (b) 1+2**3*45
    3. (c) 1/23/4
    4. (d) 1//23//4+5//6
    5. (e) 1+42/2
    6. (f) (1+42)/2
  6. 2.6 Determine the output of each of these code fragments:
    1. (a) x = 10y = 15print(x, y)y = xprint(x, y)x = 5print(x, y)
    2. (b) x = 10y = 15print(x, y)y = xx = yprint(x, y)x = 5print(x, y)
    3. (c) x = 10y = 15z = 20x = zz = yy = xprint(x, y, z)
  7. 2.7 Modify Listing 2.1 to create your own Mad Lib program. You may want to look ahead to Chapter 8 to use the sep= or end= options of the print() statement to better control your output.
  8. 2.8 Explain the difficulty with using input() to get numeric values at this stage. (We will address it soon.)
  9. 2.9 Modify Listing 1.1 to write a program average.py that calculates and prints the average of two numbers.
  10. 2.10 Modify Listing 1.1 to write a program rect.py that calculates and prints the area and perimeter of a rectangle given its length and width. Run your program with several different values of the length and width to test it.
  11. 2.11 Modify Listing 1.1 to write a program cube.py that calculates and prints the volume and surface area of a cube given its width. Run your program with different values of the width to find the point at which volume equals surface area.
  12. 2.12 Modify Listing 1.1 to write a program sphere.py that calculates and prints the volume and surface area of a sphere given its radius. Look up the formulae if you do not remember them. Run your program with different values of the radius to find the point at which volume equals surface area.
..................Content has been hidden....................

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