Summary

This document covers the fundamental concepts of Python programming, including designing a program, input processing and output. It details the program development cycle and different design techniques.

Full Transcript

Input, Processing, CHAPTER 2 and Output TOPICS 2.1 Designing a Program 2.6 Reading Input from the Keyboard 2.2 Input, Processing, and Output 2.7 Performing Calculations 2.3...

Input, Processing, CHAPTER 2 and Output TOPICS 2.1 Designing a Program 2.6 Reading Input from the Keyboard 2.2 Input, Processing, and Output 2.7 Performing Calculations 2.3 Displaying Output with the print 2.8 More About Data Output Function 2.9 Named Constants 2.4 Comments 2.10 Introduction to Turtle Graphics 2.5 Variables 2.1 Designing a Program CONCEPT: Programs must be carefully designed before they are written. During the design process, programmers use tools such as pseudocode and ­flowcharts to create models of programs. The Program Development Cycle In Chapter 1, you learned that programmers typically use high-level languages such as Python to create programs. There is much more to creating a program than writing code, however. The process of creating a program that works correctly typically requires the five phases shown in Figure 2-1. The entire process is known as the program development cycle. Figure 2-1 The program development cycle Design the Write the Correct Test the Correct program code syntax errors program logic errors Let’s take a closer look at each stage in the cycle. 1. Design the Program. All professional programmers will tell you that a program should be carefully designed before the code is actually written. When programmers begin a 53 54 Chapter 2   Input, Processing, and Output new project, they should never jump right in and start writing code as the first step. They start by creating a design of the program. There are several ways to design a program, and later in this section, we will discuss some techniques that you can use to design your Python programs. 2. Write the Code. After designing the program, the programmer begins writing code in a high-level language such as Python. Recall from Chapter 1 that each language has its own rules, known as syntax, that must be followed when writing a program. A language’s syntax rules dictate things such as how key words, operators, and punc- tuation characters can be used. A syntax error occurs if the programmer violates any of these rules. 3. Correct Syntax Errors. If the program contains a syntax error, or even a simple mis- take such as a misspelled key word, the compiler or interpreter will display an error message indicating what the error is. Virtually all code contains syntax errors when it is first written, so the programmer will typically spend some time correcting these. Once all of the syntax errors and simple typing mistakes have been corrected, the pro- gram can be compiled and translated into a machine language program (or executed by an interpreter, depending on the language being used). 4. Test the Program. Once the code is in an executable form, it is then tested to deter- mine whether any logic errors exist. A logic error is a mistake that does not prevent the program from running, but causes it to produce incorrect results. (Mathematical mistakes are common causes of logic errors.) 5. Correct Logic Errors. If the program produces incorrect results, the programmer debugs the code. This means that the programmer finds and corrects logic errors in the program. Sometimes during this process, the programmer discovers that the program’s original design must be changed. In this event, the program development cycle starts over and continues until no errors can be found. More About the Design Process The process of designing a program is arguably the most important part of the cycle. You can think of a program’s design as its foundation. If you build a house on a poorly con- structed foundation, eventually you will find yourself doing a lot of work to fix the house! A program’s design should be viewed no differently. If your program is designed poorly, eventually you will find yourself doing a lot of work to fix the program. The process of designing a program can be summarized in the following two steps: 1. Understand the task that the program is to perform. 2. Determine the steps that must be taken to perform the task. Let’s take a closer look at each of these steps. Understand the Task That the Program Is to Perform It is essential that you understand what a program is supposed to do before you can deter- mine the steps that the program will perform. Typically, a professional programmer gains this understanding by working directly with the customer. We use the term customer to describe the person, group, or organization that is asking you to write a program. This could be a customer in the traditional sense of the word, meaning someone who is paying you to write a program. It could also be your boss, or the manager of a department within your company. Regardless of whom it is, the customer will be relying on your program to perform an important task. 2.1 Designing a Program 55 To get a sense of what a program is supposed to do, the programmer usually interviews the customer. During the interview, the customer will describe the task that the program should perform, and the programmer will ask questions to uncover as many details as possible about the task. A follow-up interview is usually needed because customers rarely mention everything they want during the initial meeting, and programmers often think of additional questions. The programmer studies the information that was gathered from the customer during the inter- views and creates a list of different software requirements. A software requirement is simply a single task that the program must perform in order to satisfy the customer. Once the customer agrees that the list of requirements is complete, the programmer can move to the next phase. TIP: If you choose to become a professional software developer, your customer will be anyone who asks you to write programs as part of your job. As long as you are a student, however, your customer is your instructor! In every programming class that you will take, it’s practically guaranteed that your instructor will assign programming problems for you to complete. For your academic success, make sure that you understand your instructor’s requirements for those assignments and write your programs accordingly. Determine the Steps That Must Be Taken to Perform the Task Once you understand the task that the program will perform, you begin by breaking down the task into a series of steps. This is similar to the way you would break down a task into a series of steps that another person can follow. For example, suppose someone asks you how to boil water. You might break down that task into a series of steps as follows: 1. Pour the desired amount of water into a pot. 2. Put the pot on a stove burner. 3. Turn the burner to high. 4. Watch the water until you see large bubbles rapidly rising. When this happens, the water is boiling. This is an example of an algorithm, which is a set of well-defined logical steps that must be taken to perform a task. Notice the steps in this algorithm are sequentially ordered. Step 1 should be performed before step 2, and so on. If a person follows these steps exactly as they appear, and in the correct order, he or she should be able to boil water successfully. A programmer breaks down the task that a program must perform in a similar way. An algorithm is created, which lists all of the logical steps that must be taken. For example, suppose you have been asked to write a program to calculate and display the gross pay for an hourly paid employee. Here are the steps that you would take: 1. Get the number of hours worked. 2. Get the hourly pay rate. 3. Multiply the number of hours worked by the hourly pay rate. 4. Display the result of the calculation that was performed in step 3. Of course, this algorithm isn’t ready to be executed on the computer. The steps in this list have to be translated into code. Programmers commonly use two tools to help them accom- plish this: pseudocode and flowcharts. Let’s look at each of these in more detail. 56 Chapter 2   Input, Processing, and Output Pseudocode Because small mistakes like misspelled words and forgotten punctuation characters can cause syntax errors, programmers have to be mindful of such small details when writing code. For this reason, programmers find it helpful to write a program in pseudocode (pronounced “sue doe code”) before they write it in the actual code of a programming language such as Python. The word “pseudo” means fake, so pseudocode is fake code. It is an informal language that has no syntax rules and is not meant to be compiled or executed. Instead, program- mers use pseudocode to create models, or “mock-ups,” of programs. Because programmers don’t have to worry about syntax errors while writing pseudocode, they can focus all of their attention on the program’s design. Once a satisfactory design has been created with pseudocode, the pseudocode can be translated directly to actual code. Here is an example of how you might write pseudocode for the pay calculating program that we discussed earlier: Input the hours worked Input the hourly pay rate Calculate gross pay as hours worked multiplied by pay rate Display the gross pay Each statement in the pseudocode represents an operation that can be performed in Python. For example, Python can read input that is typed on the keyboard, perform mathematical calculations, and display messages on the screen. Flowcharts Flowcharting is another tool that programmers use to design programs. A flowchart is a diagram that graphically depicts the steps that take place in a program. Figure 2-2 shows how you might create a flowchart for the pay calculating program. Notice there are three types of symbols in the flowchart: ovals, parallelograms, and a rect- angle. Each of these symbols represents a step in the program, as described here: The ovals, which appear at the top and bottom of the flowchart, are called terminal symbols. The Start terminal symbol marks the program’s starting point, and the End terminal symbol marks the program’s ending point. Parallelograms are used as input symbols and output symbols. They represent steps in which the program reads input or displays output. Rectangles are used as processing symbols. They represent steps in which the program performs some process on data, such as a mathematical calculation. The symbols are connected by arrows that represent the “flow” of the program. To step through the symbols in the proper order, you begin at the Start terminal and follow the arrows until you reach the End terminal. Checkpoint 2.1 Who is a programmer’s customer? 2.2 What is a software requirement? 2.3 What is an algorithm? 2.4 What is pseudocode? 2.2 Input, Processing, and Output 57 Figure 2-2 Flowchart for the pay calculating program Start Input the hours worked Input the hourly pay rate Calculate gross pay as hours worked multiplied by pay rate Display the gross pay End 2.5 What is a flowchart? 2.6 What do each of the following symbols mean in a flowchart? Oval Parallelogram Rectangle 2.2 Input, Processing, and Output CONCEPT: Input is data that the program receives. When a program receives data, it usually processes it by performing some operation with it. The result of the operation is sent out of the program as output. Computer programs typically perform the following three-step process: 1. Input is received. 2. Some process is performed on the input. 3. Output is produced. Input is any data that the program receives while it is running. One common form of in­put is data that is typed on the keyboard. Once input is received, some process, such as a 58 Chapter 2   Input, Processing, and Output mathematical calculation, is usually performed on it. The results of the process are then sent out of the program as output. Figure 2-3 illustrates these three steps in the pay calculating program that we discussed earlier. The number of hours worked and the hourly pay rate are provided as input. The program processes this data by multiplying the hours worked by the hourly pay rate. The results of the calculation are then displayed on the screen as output. Figure 2-3 The input, processing, and output of the pay calculating program Input Process Output Hours worked Multiply hours worked Gross pay by hourly pay rate Hourly pay rate In this chapter, we will discuss basic ways that you can perform input, processing, and output using Python. 2.3 Displaying Output with the print Function CONCEPT: You use the print function to display output in a Python program. A function is a piece of prewritten code that performs an operation. Python has numerous built-in functions that perform various operations. Perhaps the most fundamental built-in VideoNote function is the print function, which displays output on the screen. Here is an example of The print Function a statement that executes the print function: print('Hello world') In interactive mode, if you type this statement and press the Enter key, the message Hello world is displayed. Here is an example: >>> print('Hello world') Enter Hello world >>> When programmers execute a function, they say that they are calling the function. When you call the print function, you type the word print, followed by a set of parentheses. Inside the parentheses, you type an argument, which is the data that you want displayed on the screen. In the previous example, the argument is 'Hello world'. Notice the quote marks are not displayed when the statement executes. The quote marks simply specify the beginning and the end of the text that you wish to display. Suppose your instructor tells you to write a program that displays your name and address on the computer screen. Program 2-1 shows an example of such a program, with the output that it will produce when it runs. (The line numbers that appear in a program listing in 2.3 Displaying Output with the print Function 59 this book are not part of the program. We use the line numbers in our discussion to refer to parts of the program.) Program 2-1 (output.py) 1 print('Kate Austen') 2 print('123 Full Circle Drive') 3 print('Asheville, NC 28899') Program Output Kate Austen 123 Full Circle Drive Asheville, NC 28899 It is important to understand that the statements in this program execute in the order that they appear, from the top of the program to the bottom. When you run this program, the first statement will execute, followed by the second statement, and followed by the third statement. Strings and String Literals Programs almost always work with data of some type. For example, Program 2-1 uses the following three pieces of data: 'Kate Austen' '123 Full Circle Drive 'Asheville, NC 28899' These pieces of data are sequences of characters. In programming terms, a sequence of char- acters that is used as data is called a string. When a string appears in the actual code of a pro- gram, it is called a string literal. In Python code, string literals must be enclosed in quote marks. As mentioned earlier, the quote marks simply mark where the string data begins and ends. In Python, you can enclose string literals in a set of single-quote marks (') or a set of ­double-quote marks ("). The string literals in Program 2-1 are enclosed in single-quote marks, but the program could also be written as shown in Program 2-2. Program 2-2 (double_quotes.py) 1 print("Kate Austen") 2 print("123 Full Circle Drive") 3 print("Asheville, NC 28899") Program Output Kate Austen 123 Full Circle Drive Asheville, NC 28899 60 Chapter 2   Input, Processing, and Output If you want a string literal to contain either a single-quote or an apostrophe as part of the string, you can enclose the string literal in double-quote marks. For example, Program 2-3 prints two strings that contain apostrophes. Program 2-3 (apostrophe.py) 1 print("Don't fear!") 2 print("I'm here!") Program Output Don't fear! I'm here! Likewise, you can use single-quote marks to enclose a string literal that contains double- quotes as part of the string. Program 2-4 shows an example. Program 2-4 (display_quote.py) 1 print('Your assignment is to read "Hamlet" by tomorrow.') Program Output Your assignment is to read "Hamlet" by tomorrow. Python also allows you to enclose string literals in triple quotes (either """ or '''). Triple- quoted strings can contain both single quotes and double quotes as part of the string. The following statement shows an example: print("""I'm reading "Hamlet" tonight.""") This statement will print I'm reading "Hamlet" tonight. Triple quotes can also be used to surround multiline strings, something for which single and double quotes cannot be used. Here is an example: print("""One Two Three""") This statement will print One Two Three 2.4 Comments 61 Checkpoint 2.7 Write a statement that displays your name. 2.8 Write a statement that displays the following text: Python's the best! 2.9 Write a statement that displays the following text: The cat said "meow." 2.4 Comments CONCEPT: Comments are notes of explanation that document lines or sections of a program. Comments are part of the program, but the Python interpreter ignores them. They are intended for people who may be reading the source code. Comments are short notes placed in different parts of a program, explaining how those parts of the program work. Although comments are a critical part of a program, they are ignored by the Python interpreter. Comments are intended for any person reading a pro- gram’s code, not the computer. In Python, you begin a comment with the # character. When the Python interpreter sees a # character, it ignores everything from that character to the end of the line. For example, look at Program 2-5. Lines 1 and 2 are comments that briefly explain the program’s purpose. Program 2-5 (comment1.py) 1 # This program displays a person's 2 # name and address. 3 print('Kate Austen') 4 print('123 Full Circle Drive') 5 print('Asheville, NC 28899') Program Output Kate Austen 123 Full Circle Drive Asheville, NC 28899 Programmers commonly write end-line comments in their code. An end-line comment is a comment that appears at the end of a line of code. It usually explains the statement that appears in that line. Program 2-6 shows an example. Each line ends with a comment that briefly explains what the line does. 62 Chapter 2   Input, Processing, and Output Program 2-6 (comment2.py) 1 print('Kate Austen') # Display the name. 2 print('123 Full Circle Drive') # Display the address. 3 print('Asheville, NC 28899') # Display the city, state, and ZIP. Program Output Kate Austen 123 Full Circle Drive Asheville, NC 28899 As a beginning programmer, you might be resistant to the idea of liberally writing com- ments in your programs. After all, it can seem more productive to write code that actually does something! It is crucial that you take the extra time to write comments, however. They will almost certainly save you and others time in the future when you have to modify or debug the program. Large and complex programs can be almost impossible to read and understand if they are not properly commented. 2.5 Variables CONCEPT: A variable is a name that represents a value stored in the computer’s memory. Programs usually store data in the computer’s memory and perform operations on that data. For example, consider the typical online shopping experience: you browse a website and add the items that you want to purchase to the shopping cart. As you add items to the shopping cart, data about those items is stored in memory. Then, when you click the checkout button, a program running on the website’s computer calculates the cost of all the items you have in your shopping cart, applicable sales taxes, shipping costs, and the total of all these charges. When the program performs these calculations, it stores the results in the computer’s memory. Programs use variables to access and manipulate data that is stored in memory. A vari- able is a name that represents a value in the computer’s memory. For example, a program that calculates the sales tax on a purchase might use the variable name tax to represent that value in memory. And a program that calculates the distance between two cities might use the variable name distance to represent that value in memory. When a vari- able represents a value in the computer’s memory, we say that the variable references the value. Creating Variables with Assignment Statements You use an assignment statement to create a variable and make it reference a piece of data. Here is an example of an assignment statement: age = 25 2.5 Variables 63 After this statement executes, a variable named age will be created, and it will reference the value 25. This concept is shown in Figure 2-4. In the figure, think of the value 25 as being stored somewhere in the computer’s memory. The arrow that points from age to the value 25 indicates that the name age references the value. Figure 2-4 The age variable references the value 25 age 25 An assignment statement is written in the following general format: variable = expression The equal sign (=) is known as the assignment operator. In the general format, variable is the name of a variable and expression is a value, or any piece of code that results in a value. After an assignment statement executes, the variable listed on the left side of the = operator will reference the value given on the right side of the = operator. To experiment with variables, you can type assignment statements in interactive mode, as shown here: >>> width = 10 Enter >>> length = 5 Enter >>> The first statement creates a variable named width and assigns it the value 10. The second statement creates a variable named length and assigns it the value 5. Next, you can use the print function to display the values referenced by these variables, as shown here: >>> print(width) Enter 10 >>> print(length) Enter 5 >>> When you pass a variable as an argument to the print function, you do not enclose the vari- able name in quote marks. To demonstrate why, look at the following interactive session: >>> print('width') Enter width >>> print(width) Enter 10 >>> In the first statement, you passed 'width' as an argument to the print function, and the function printed the string width. In the second statement, you passed width (with no quote marks) as an argument to the print function, and the function displayed the value referenced by the width variable. 64 Chapter 2   Input, Processing, and Output In an assignment statement, the variable that is receiving the assignment must appear on the left side of the = operator. As shown in the following interactive session, an error occurs if the item on the left side of the = operator is not a variable: >>> 25 = age Enter SyntaxError: can't assign to literal >>> The code in Program 2-7 demonstrates a variable. Line 2 creates a variable named room and assigns it the value 503. The statements in lines 3 and 4 display a message. Notice line 4 displays the value that is referenced by the room variable. Program 2-7 (variable_demo.py) 1 # This program demonstrates a variable. 2 room = 503 3 print('I am staying in room number') 4 print(room) Program Output I am staying in room number 503 Program 2-8 shows a sample program that uses two variables. Line 2 creates a variable named top_speed, assigning it the value 160. Line 3 creates a variable named distance, assigning it the value 300. This is illustrated in Figure 2-5. Program 2-8 (variable_demo2.py) 1 # Create two variables: top_speed and distance. 2 top_speed = 160 3 distance = 300 4 5 # Display the values referenced by the variables. 6 print('The top speed is') 7 print(top_speed) 8 print('The distance traveled is') 9 print(distance) Program Output The top speed is 160 The distance traveled is 300 2.5 Variables 65 Figure 2-5 Two variables top_speed 160 distance 300 WARNING! You cannot use a variable until you have assigned a value to it. An error will occur if you try to perform an operation on a variable, such as printing it, before it has been assigned a value. Sometimes a simple typing mistake will cause this error. One example is a misspelled variable name, as shown here: temperature = 74.5 # Create a variable print(tempereture) # Error! Misspelled variable name In this code, the variable temperature is created by the assignment statement. The variable name is spelled differently in the print statement, however, which will cause an error. Another example is the inconsistent use of uppercase and lowercase letters in a variable name. Here is an example: temperature = 74.5 # Create a variable print(Temperature) # Error! Inconsistent use of case In this code, the variable temperature (in all lowercase letters) is created by the assignment statement. In the print statement, the name Temperature is spelled with an uppercase T. This will cause an error because variable names are case sensitive in Python. Variable Naming Rules Although you are allowed to make up your own names for variables, you must follow these rules: You cannot use one of Python’s key words as a variable name. (See Table 1-2 for a list of the key words.) A variable name cannot contain spaces. The first character must be one of the letters a through z, A through Z, or an under- score character (_). After the first character you may use the letters a through z or A through Z, the digits 0 through 9, or underscores. Uppercase and lowercase characters are distinct. This means the variable name ItemsOrdered is not the same as itemsordered. In addition to following these rules, you should always choose names for your variables that give an indication of what they are used for. For example, a variable that holds the temperature might be named temperature, and a variable that holds a car’s speed might be named speed. You may be tempted to give variables names such as x and b2, but names like these give no clue as to what the variable’s purpose is. 66 Chapter 2   Input, Processing, and Output Because a variable’s name should reflect the variable’s purpose, programmers often find themselves creating names that are made of multiple words. For example, consider the fol- lowing variable names: grosspay payrate hotdogssoldtoday Unfortunately, these names are not easily read by the human eye because the words aren’t separated. Because we can’t have spaces in variable names, we need to find another way to separate the words in a multiword variable name and make it more readable to the human eye. One way to do this is to use the underscore character to represent a space. For example, the following variable names are easier to read than those previously shown: gross_pay pay_rate hot_dogs_sold_today This style of naming variables is popular among Python programmers, and is the style we will use in this book. There are other popular styles, however, such as the camelCase nam- ing convention. camelCase names are written in the following manner: The variable name begins with lowercase letters. The first character of the second and subsequent words is written in uppercase. For example, the following variable names are written in camelCase: grossPay payRate hotDogsSoldToday NOTE: This style of naming is called camelCase because the uppercase characters that appear in a name may suggest a camel’s humps. Table 2-1 lists several sample variable names and indicates whether each is legal or illegal in Python. Table 2-1 Sample variable names Variable Name Legal or Illegal? units_per_day Legal dayOfWeek Legal 3dGraph Illegal. Variable names cannot begin with a digit. June1997 Legal Mixture#3 Illegal. Variable names may only use letters, digits, or underscores. 2.5 Variables 67 Displaying Multiple Items with the print Function If you refer to Program 2-7, you will see that we used the following two statements in lines 3 and 4: print('I am staying in room number') print(room) We called the print function twice because we needed to display two pieces of data. Line 3 displays the string literal 'I am staying in room number', and line 4 displays the value referenced by the room variable. This program can be simplified, however, because Python allows us to display multiple items with one call to the print function. We simply have to separate the items with com- mas as shown in Program 2-9. Program 2-9 (variable_demo3.py) 1 # This program demonstrates a variable. 2 room = 503 3 print('I am staying in room number', room) Program Output I am staying in room number 503 In line 3, we passed two arguments to the print function. The first argument is the string literal 'I am staying in room number', and the second argument is the room variable. When the print function executed, it displayed the values of the two arguments in the order that we passed them to the function. Notice the print function automatically printed a space separating the two items. When multiple arguments are passed to the print func- tion, they are automatically separated by a space when they are displayed on the screen. Variable Reassignment Variables are called “variable” because they can reference different values while a program is running. When you assign a value to a variable, the variable will reference that value until you assign it a different value. For example, look at Program 2-10. The statement in line 3 creates a variable named dollars and assigns it the value 2.75. This is shown in the top part of Figure 2-6. Then, the statement in line 8 assigns a different value, 99.95, to the dollars variable. The bottom part of Figure 2-6 shows how this changes the dollars variable. The old value, 2.75, is still in the computer’s memory, but it can no longer be used because it isn’t referenced by a variable. When a value in memory is no longer referenced by a variable, the Python interpreter automatically removes it from memory through a process known as garbage collection. Program 2-10 (variable_demo4.py) 1 # This program demonstrates variable reassignment. 2 # Assign a value to the dollars variable. 3 dollars = 2.75 (program continues) 68 Chapter 2   Input, Processing, and Output Program 2-10 (continued) 4 print('I have', dollars, 'in my account.') 5 6 # Reassign dollars so it references 7 # a different value. 8 dollars = 99.95 9 print('But now I have', dollars, 'in my account!') Program Output I have 2.75 in my account. But now I have 99.95 in my account! Figure 2-6 Variable reassignment in Program 2-10 The dollars variable after line 3 executes. dollars 2.75 The dollars variable after line 8 executes. dollars 2.75 99.95 Numeric Data Types and Literals In Chapter 1, we discussed the way that computers store data in memory. (See Section 1.3) You might recall from that discussion that computers use a different technique for storing real numbers (numbers with a fractional part) than for storing integers. Not only are these types of numbers stored differently in memory, but similar operations on them are carried out in different ways. Because different types of numbers are stored and manipulated in different ways, Python uses data types to categorize values in memory. When an integer is stored in memory, it is classified as an int, and when a real number is stored in memory, it is classified as a float. Let’s look at how Python determines the data type of a number. Several of the programs that you have seen so far have numeric data written into their code. For example, the fol- lowing statement, which appears in Program 2-9, has the number 503 written into it: room = 503 This statement causes the value 503 to be stored in memory, and it makes the room vari- able reference it. The following statement, which appears in Program 2-10, has the number 2.75 written into it: dollars = 2.75 This statement causes the value 2.75 to be stored in memory, and it makes the dollars vari- able reference it. A number that is written into a program’s code is called a numeric literal. 2.5 Variables 69 When the Python interpreter reads a numeric literal in a program’s code, it determines its data type according to the following rules: A numeric literal that is written as a whole number with no decimal point is consid- ered an int. Examples are 7, 124, and −9. A numeric literal that is written with a decimal point is considered a float. Examples are 1.5, 3.14159, and 5.0. So, the following statement causes the number 503 to be stored in memory as an int: room = 503 And the following statement causes the number 2.75 to be stored in memory as a float: dollars = 2.75 When you store an item in memory, it is important for you to be aware of the item’s data type. As you will see, some operations behave differently depending on the type of data involved, and some operations can only be performed on values of a specific data type. As an experiment, you can use the built-in type function in interactive mode to determine the data type of a value. For example, look at the following session: >>> type(1) Enter >>> In this example, the value 1 is passed as an argument to the type function. The message that is displayed on the next line, , indicates that the value is an int. Here is another example: >>> type(1.0) Enter >>> In this example, the value 1.0 is passed as an argument to the type function. The message that is displayed on the next line, , indicates that the value is a float. WARNING! You cannot write currency symbols, spaces, or commas in numeric literals. For example, the following statement will cause an error: value = $4,567.99 # Error! This statement must be written as: value = 4567.99 # Correct Storing Strings with the str Data Type In addition to the int and float data types, Python also has a data type named str, which is used for storing strings in memory. The code in Program 2-11 shows how strings can be assigned to variables. 70 Chapter 2   Input, Processing, and Output Program 2-11 (string_variable.py) 1 # Create variables to reference two strings. 2 first_name = 'Kathryn' 3 last_name = 'Marino' 4 5 # Display the values referenced by the variables. 6 print(first_name, last_name) Program Output Kathryn Marino Reassigning a Variable to a Different Type Keep in mind that in Python, a variable is just a name that refers to a piece of data in memory. It is a mechanism that makes it easy for you, the programmer, to store and retrieve data. Internally, the Python interpreter keeps track of the variable names that you create and the pieces of data to which those variable names refer. Any time you need to retrieve one of those pieces of data, you simply use the variable name that refers to it. A variable in Python can refer to items of any type. After a variable has been assigned an item of one type, it can be reassigned an item of a different type. To demonstrate, look at the following interactive session. (We have added line numbers for easier reference.) 1 >>> x = 99 Enter 2 >>> print(x) Enter 3 99 4 >>> x = 'Take me to your leader' Enter 5 >>> print(x) Enter 6 Take me to your leader. 7 >>> The statement in line 1 creates a variable named x and assigns it the int value 99. Figure 2-7 shows how the variable x references the value 99 in memory. The statement in line 2 calls the print function, passing x as an argument. The output of the print function is shown in line 3. Then, the statement in line 4 assigns a string to the x variable. After this statement executes, the x variable no longer refers to an int, but to the string 'Take me to your leader'. This is shown in Figure 2-8. Line 5 calls the print function again, passing x as an argument. Line 6 shows the print function’s output. Figure 2-7 The variable x references an integer x 99 Figure 2-8 The variable x references a string x 99 Take me to your leader 2.6 Reading Input from the Keyboard 71 Checkpoint 2.10 What is a variable? 2.11 Which of the following are illegal variable names in Python, and why? x 99bottles july2009 theSalesFigureForFiscalYear r&d grade_report 2.12 Is the variable name Sales the same as sales? Why or why not? 2.13 Is the following assignment statement valid or invalid? If it is invalid, why? 72 = amount 2.14 What will the following code display? val = 99 print('The value is', 'val') 2.15 Look at the following assignment statements: value1 = 99 value2 = 45.9 value3 = 7.0 value4 = 7 value5 = 'abc' After these statements execute, what is the Python data type of the values referenced by each variable? 2.16 What will be displayed by the following program? my_value = 99 my_value = 0 print(my_value) 2.6 Reading Input from the Keyboard CONCEPT: Programs commonly need to read input typed by the user on the key- board. We will use the Python functions to do this. Most of the programs that you will write will need to read input and then perform an operation on that input. In this section, we will discuss a basic input operation: reading VideoNote Reading Input data that has been typed on the keyboard. When a program reads data from the keyboard, from the usually it stores that data in a variable so it can be used later by the program. Keyboard In this book, we use Python’s built-in input function to read input from the keyboard. The input function reads a piece of data that has been entered at the keyboard and returns that piece of data, as a string, back to the program. You normally use the input function in an assignment statement that follows this general format: variable = input(prompt)

Use Quizgecko on...
Browser
Browser