Programming with Numbers and Strings 2
Total Page:16
File Type:pdf, Size:1020Kb
,,. 26 Chapter 1 Introduction CHAPTER I � 2 4. In secondary storage, typically a hard disk. 21. Is the number of minutes at most 300? I 5. The central processing unit. a. If so, the answer is $29.95 x 1.125 = $33.70. PROGRAMMING 6. (1) It would be very tedious to do so. b. If not, (2) Programs that are written for one CPU are 1. Compute the difference: (number of WITH NUMBERS not portable to a different CPU type. minutes)- 300. 7. Ease of use and portability. 2. Multiply that difference by 0.45. 8. The answer varies among systems. A typical 3. Add $29.95. AND STRINGS answer might be /home/dave/csl/hel lo/hello. py 4. Multiply the total by 1.125. That is the or c:\Users\Dave\Workspace\hello\hello. py answer. 9. You back up your files and folders. 22. No. The step If it is more attractive than the "best © samxmeg/iStockphoto. 1 O. Change World to your name (here, Dave): so far" is not executable because there is no objective way f deciding which of two photos print("Hello, Dave!") ? is more attractive. To define and use variables and constants 11. print("H") 23. Pick the first photo and call it "the most expensive so far". print("e") To understand the properties and limitations of integers and floating-point numbers print("l ") For each photo in the sequence print("l ") If it is more expensive than "the most expensive so far" To appreciate the importance of comments and good code layout print("o") Discard "the most expensive so far". Call this photo "the most expensive so far". To write arithmetic expressions and assignment statements I 12. No. The interpreter would look for an The photo called "the most expensive so far" is the most To create programs that read and process inputs, and display the results item whose name is He11 o. You need to expensive photo in the sequence. enclose He11 o in quotation marks: To learn how to use Python strings print("Hello") 24. The first black marble that is preceded by a white one is marked in blue: To create simple graphics programs using basic shapes and text 13. My lucky numbers are 17 29 oeo•• 14. Hello Switching the two yields f CHAPTER CONTENTS a blank line World 2.1 VARIABLES 28 eoo•• 2.4 STRINGS 46 1 5. This is a compile-time error at the point of the The next black marble to be switched is T: Syntax 2. Assignment 29 Special Topic 2.4: Character Values 51 ! symbol. eoo•• Common Error2. T: Using Undefined Special Topic 2.5: Escape Sequences 52 16. This is a compile-time error at the point of the yielding Variables 34 Computing & Society 2. T: International Alphabets { symbol. •o•o• Programming Tip2. T: Choose Descriptive and Unicode 52 17. This is a compile-time error. The interpreter Variable Names 34 The next steps are 2.5 INPUT AND OUTPUT 53 will either complain of an indentation error or Programming Tip2.2: Do Not Use Syntax 2.3: a syntax error because plain sentences cannot eeoo• Magic Numbers 35 String Format Operator 55 Programming Tip 2.4: Don't Wait to Convert 58 be used as instructions. ••o•o 2.2 ARITHMETIC 3 5 How To 2. T: Writing Simple Programs 58 18. It is a run-time error. After all, the program •••oo Syntax 2.2: had been compiled in order for you to run it. Calling Functions 38 Worked Example2.2: Computing the Cost Now the sequence is sorted. Common Error2.2: Roundoff Errors 41 of Stamps 61 19. When a program has compile-time errors, the 2 5. The sequence doesn't terminate. Consider the Common Error2.3: Unbalanced Parentheses 41 Computing & Society 2.2: The Pentium Floating· interpreter stops translating the instructions input oeoeo. The first two marbles keep Programming Tip2.3: and does not execute the program. Use Spaces in Point Bug 63 getting switched. Expressions 42 20. 4 years: 2.6 GRAPHICS: SIMPLE DRAWINGS 63 Special Topic 2. T: Other Ways to Import How To 2.2: 0 10,000 Modules 42 Graphics: Drawing Graphical 1 12,000 Special Topic 2.2: Combining Assignment and Shapes 70 Toolbox 2. T: Symbolic Processing with 2 14,400 Arithmetic 42 Special Topic 2.3: SymPy 73 3 17,280 Line Joining 43 4 20,736 2.3 PROBLEM SOLVING: FIRST DO IT BY HAND 43 Worked Example 2. T: Computing Travel Time 45 • Numbers and character strings (such as the ones on this 2.1 Variables 29 display board) are important data types in any Python program. In this chapter, you will learn how to work with Syntax 2. 1 Assignment numbers and text, and how to write simp le programs that perform useful tasks with them. Syntax variableName = value © samxmeg/iStockphoto. A variableis defined total = 0 ./1 Namesof previously the first timeit /" / definedvariables is assigneda value. t otal= bottles * BOTTLE_VOLUME Theexpression that replacesthe previousvalue When you r program carries out computations, you will want to store values so th at you can use them later. In a Python program, you use variables to store values. In this section, you will learn how to define and use variables. total = total+ cans* CAN_VOLUME To illustr ate the use of variables , we will develop a program that solves the Thesame name ~ following probl em. Soft drinks are sold canoccur on both sides. Namesof previously in cans and bottles. A store offers a six See Figure2. definedvariables pack of 12-ounce cans for the same price as a two-liter bottle. Which shou ld yo u buy? (Twelve fluid ounces equal approx imately 0.355 liters.) You use the assignment statement to place a value into a variable. Here 1s an In our program, we will define vari An assi gnment sta tem ent stores a example ables for the number of cans per pack value in a variable. and for the volume of each can. Then we cansPerPack = 6 C, ~ will compute the volume of a six-pack in What contains more soda? A six -pack of The left-hand side of an assignment statement consists of a variable. The right-hand liters and print out the answer. I 2-ounce cans or a t wo-liter bottle? side is an expression that has a value. That value is stored in the variable. The first tim e a variable is assigned a value, th e variable is created and initialized with that value. Aft er a variabl e has been defined, it can be used in other statements. For example, 2 .1 .1 Defining Variables A variab le is created the first time it is print(can s PerPa ck) ass igned a value . A variable is a storage location in a compute r program . Each variable has a name and cansPerPack . A va riable is a will print the value stored in the variable storage location holds a value. Assigning a va lue If an existing variable is assigned a new value, th at value repla ces th e previous con with a name. A variable is similar to a parking space in a parkin g garage. The parking space has to an existing tents of the variab le. For examp le, an identifier (such as "J 053"), and it can hold a vehicle. A variable has a name (such as variab le replaces the previo usly cansPerPack = 8 ~ cansPe rPack ), and it can hold a value (such as 6). sto red value. changes the value conta in ed in variable cansPerPack from 6 to 8. Figure 1 illustrates the two assignment statements used above . The assign ment Th e = sign does not mean that th e left-hand side is equal to th e right -h and side. ope rator= does not Instead, the valu e on the right-h and side is placed into the varia ble on the left. denot e mathematical Do not confus e this assignment operator with the = used in algebra to denot e equa lity. equalit y. Assignment is an instruction to do something-namely, place a value into a variable. 0 Because this is the first assignme nt, f) The variab le is initializ ed. The second assignment overwrites the variab le is created. the stored value. cansPerPack cansPerPack = 6 cansPerPack = 8 Like a variable in a comp uter program, a parking space has an identifie r and a contents. Figure 1 Executing Two Assignm ent s 28 30 Chapter 2 Programming with Numbers and Strings 2 . 1 Variable s 31 h1I iI Figure 2 0 Compute rhe value of rhe rigbr-band side I Executing the Assignment Table 1 Number Literals in Pytho n can s PerPack = cansPerPack + 2 ca nsPerPack = I Number Type Comment I ! can s PerP a ck + 2 6 int An integer bas no fractional part . I ~ -6 int 10 Integer s can be negative. 0 int Zero is an integer . f) Store the value in rhe variable ) 0.5 fl oat A number with a fractional part has type fl oat . ca ns Pe rPack = 1~ 1. 0 float An integer with a fractional part .0 has type float . l EG fl oat A numbe r in exponential notation: 1 x 106 or 1000000. Numbers in exponential notation always have type float. 2.96E-2 float Negative exponent: 2.96 x 10-2 = 2.96 I 100 = 0.0296 For exampl e, in Python, it is perf ectly legal to w rite (S)100,000 Error: Do no t use a comma as a decimal separator.