Introduction to Python Programming

Size: px
Start display at page:

Download "Introduction to Python Programming"

Transcription

1 2 Introduction to Python Programming Objectives To understand a typical Python program-development environment. To write simple computer programs in Python. To use simple input and output statements. To become familiar with fundamental data types. To use arithmetic operators. To understand the precedence of arithmetic operators. To write simple decision-making statements. High thoughts must have high language. Aristophanes Our life is frittered away by detail Simplify, simplify. Henry Thoreau My object all sublime I shall achieve in time. W.S. Gilbert

2 74 Introduction to Python Programming Chapter 2 Outline 2.1 Introduction 2.2 Simple Program: Printing a Line of Text 2.3 Another Simple Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic 2.6 String Formatting 2.7 Decision Making: Equality and Relational Operators 2.8 Indentation 2.9 Thinking About Objects: Introduction to Object Technology Summary Terminology Self-Review Exercises Answers to Self-Review Exercises Exercises 2.1 Introduction Learning the Python language using Python How to Program facilitates a structured and disciplined approach to computer-program design. In this first programming chapter, we introduce Python programming and present several examples that illustrate important features of the language. To understand each example, we analyze the code one statement at a time. After presenting basic concepts in Chapters 2 3, we examine the structured programming approach in Chapters 4 6. At the same time we explore introductory Python topics, we also begin our discussion of object-oriented programming because of the central importance object-oriented programming takes throughout this text. For this reason, we conclude this chapter with Section 2.9, Thinking About Objects. 2.2 Simple Program: Printing a Line of Text 1 Python uses notations that may appear strange to non-programmers. To familiarize readers with these notations, we consider a simple program that prints a line of text. Figure 2.1 illustrates the program and its screen output. 1 # Fig. 2.1: fig02_01.py 2 # A first program in Python 3 4 print "Welcome to Python!" Welcome to Python! Fig. 2.1 Text-printing program. 1. The resources for this book, including step-by-step instructions on installing Python on Windows and Unix/Linux platforms are posted at

3 Chapter 2 Introduction to Python Programming 75 This first program illustrates several important features of the Python language. Let us consider each line of the program. Both lines 1 and 2 begin with the pound symbol (#), which indicates a comment. Programmers insert comments to document programs and to improve program readability. Comments also help other programmers read and understand your program. A comment that begins with # is called a single-line comment, because the comment terminates at the end of the current line. The comment text A first program in Python describes the purpose of the program (line 2). Good Programming Practice 2.1 Place comments throughout a program. Comments help other programmers understand the program, assist in debugging a program (i.e., discovering and removing errors in a program) and list useful information. Comments also help you understand your own coding when you revisit a document for modifications or updates. 2.1 The Python print command instructs the computer to display the string of characters contained between the quotation marks (line 4). A string is a Python data type that contains a sequence of characters. The entire line is called a statement. In other programming languages, like C++ and Java, statements must end with a semicolon. In Python, most statements end when the lines end. Output (displays information) and input (receives information) in Python are accomplished with streams of characters (continuous rows of characters). Thus, when the preceding statement is executed, it sends the stream of characters Welcome to Python! to the standard output stream. Standard output stream is the information presented to the user by an application which is typically displayed on the screen by may be printed on a printer, written to a file, etc. Python statements can be executed in two ways. The first is by typing statements into a file (as in Fig. 2.1) to create a program and saving the file with a.py extension. Python files typically end with.py, although other extensions (e.g.,.pyw on Windows) can be used. The Python interpreter, which executes (runs) the program, is then invoked (called) on the file by typing python file.py at the DOS or Unix shell command line, in which file is the name of the Python file. The shell command line is a text terminal in which the user can type commands that cause the computer system to respond. [Note: To invoke Python, the system path variable must be set properly to include the python executable, a file containing a program that can be run. The resources for this book posted at our Web site include instructions on how to set the appropriate variable.] When the Python interpreter runs a program stored in the file, the interpreter starts at the first line of the file and executes statements until the end of the file. The output box in Fig. 2.1 contains the results of the Python interpreter running fig02_01.py. The second way to execute Python statements is interactively. Typing python at the shell command line runs the Python interpreter in interactive mode. With this mode, the programmer types statements directly to the interpreter, which executes these statements one at a time.

4 76 Introduction to Python Programming Chapter 2 Testing and Debugging Tip 2.1 In interactive mode, Python statements are entered and interpreted one at a time. This mode often is useful when debugging a program. 2.1 Testing and Debugging Tip 2.2 When Python is invoked on a file, the interpreter exits after the last statement in the file has been executed. However, invoking Python on a file using the -i flag (e.g., python -i file.py) causes the interpreter to enter interactive mode after running the file. This is useful when debugging a program (e.g., for checking variable values). 2.2 Figure 2.2 shows Python 2.2 running in interactive mode on Windows. The first two lines display information about the version of Python being used. The third line contains the Python prompt (>>>). A Python statement is interpreted when a developer types a statement at the Python prompt and presses the Enter key (sometimes called the Return key). Python 2.2b1 (#25, Oct , 11:44:52) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> print "Welcome to Python!" Welcome to Python! >>> ^Z Fig. 2.2 Python in interactive mode. (Copyright 2001 Python Software Foundation.) The print statement on the third line prints the text Welcome to Python! to the screen. After printing the text to the screen, the interpreter waits for the user to enter the next statement. We exit Python by typing the Ctrl-Z end-of-file character (on Microsoft Windows systems) and pressing the Enter key. Figure 2.3 lists the keyboard combinations for the end-of-file character for various computer systems. Computer system UNIX/Linux systems DOS/Windows Macintosh VAX (VMS) Keyboard combination Ctrl-D (on a line by itself) Ctrl-Z (sometimes followed by pressing Enter) Ctrl-D Ctrl-Z Fig. 2.3 End-of-file key combinations for various popular computer systems. The string "Welcome to Python!" can be printed several ways. For example, Fig. 2.4 uses two print statements (lines 4 5), yet produces identical output to the program in Fig Line 4 prints the string "Welcome" to the screen. Normally, a string following a print statement begins on a new line, below the previous string. The comma (,) at the end of line 4, however, tells Python not to begin a new line but instead to add a space

5 Chapter 2 Introduction to Python Programming 77 after the string, and the next string printed to the screen (line 5) appears on the same line as the string "Welcome" 1 # Fig. 2.4: fig02_04.py 2 # Printing a line with multiple statements 3 4 print "Welcome", 5 print "to Python!" Welcome to Python! Fig. 2.4 Printing on one line with separate statements using print. Python offers special characters that perform certain tasks, such as backspace and carriage return. A special character is formed by combining the backslash (\) character, also called the escape character, with any letter. When a backslash exists in a string of characters, the backslash and the character immediately following the backslash form an escape sequence. An example of an escape sequence is \n, or newline. Each occurrence of the \n escape sequence causes the screen cursor to move to the beginning of the next line. To print a blank line, simply place two newline characters back-to-back. Figure 2.5 illustrates the use of the \n escape sequence; notice that the escape sequence is not printed to the screen. Figure 2.6 lists other common escape sequences. 1 # Fig. 2.5: fig02_05.py 2 # Printing multiple lines with a single statement 3 4 print "Welcome\nto\n\nPython!\n" Welcome to Python! Fig. 2.5 Printing on multiple lines with a single statement using print. Escape Sequence Description \n Newline. Move the screen cursor to the beginning of the next line. \t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Move the screen cursor to the beginning of the current line; do not advance to the next line. Fig. 2.6 Some common escape sequences (part 1 of 2).

6 78 Introduction to Python Programming Chapter 2 Escape Sequence Description \b Backspace. Move the screen cursor back one space. \a Alert. Sound the system bell. \\ Backslash. Print a backslash character. \" Double quote. Print a double quote character. \' Single quote. Print a single quote character. Fig. 2.6 Some common escape sequences (part 2 of 2). 2.3 Another Simple Program: Adding Two Integers Our next program invokes Python functions raw_input and int to obtain two integers entered by a user at a keyboard. The program then computes the sum of these values and outputs the result using print. Figure 2.7 contains the program and its output. 1 # Fig. 2.7: fig02_07.py 2 # Simple addition program 3 4 # prompt user for input 5 integer1 = raw_input( "Enter first integer:\n" ) # read string 6 integer1 = int( integer1 ) # convert string to integer 7 8 integer2 = raw_input( "Enter second integer:\n" ) # read string 9 integer2 = int( integer2 ) # convert string to integer sum = integer1 + integer2 # compute and assign sum print "Sum is", sum # print sum Enter first integer: 5 Enter second integer: 27 Sum is 32 Fig. 2.7 Addition program. The comments in lines 1 2 state the name of the file and the purpose of the program. Line 5 calls Python s built-in function raw_input to request user input. A built-in function is a piece of code provided by Python that performs a task. The task is performed by calling the function writing the function name, followed by parentheses (()). After performing its task, a function may return a value that represents the result of the task. Python function raw_input takes the argument, "Enter first integer:\n" that requests user input. An argument is a value that a function accepts and uses to perform its task. In this case, function raw_input accepts the prompt argument (that requests user input) and prints that prompt to the screen. The user enters a number and presses the

7 Chapter 2 Introduction to Python Programming 79 Enter key. After the user presses the Enter key, the number is sent to function raw_input in the form of a string. The result of raw_input (a string containing the characters typed by the user) is given to variable (or, identifier) integer1 using the assignment statement, =. In Python, variables are simply names that identify objects (containers that store given values). A variable name (e.g., integer1) consists of letters, digits and underscores (_) that does not begin with a digit. Python is case sensitive uppercase and lowercase letters are different, so a1 and A1 are different variables. An object can have multiple variable names. The statement (line 5) is read as integer1 references the value returned by raw_input( "Enter first integer:\n" ). Good Programming Practice 2.2 Choosing meaningful variable names helps a program to be self-documenting, i.e., it is easier to understand the program simply by reading it rather than having to read manuals or use excessive comments. 2.2 Good Programming Practice 2.3 Avoid identifiers that begin with underscores and double underscores because the Python interpreter or other Python code may reserve those characters for internal use. This prevents names you choose from being confused with names the interpreter chooses. This avoids confusion between user-defined identifiers and interpreter-defined identifiers. 2.3 In addition to a name and value, each object has a type. An object s type describes the object s format (e.g., integer, string, etc.) which identifies the kind of information stored in the object. Integers are whole numbers that encompass negative numbers (-14), zero (0) and positive numbers (6). In languages like C++ and Java, the programmer must declare (state) the object type before using the object in the program. However, Python uses dynamic typing, which determines an object s type during program execution. For example, if object a is initialized to 2, then the object is of type integer (because the number 2 is an integer). Similarly, if object b is initialized to "Python", then the object is of type string. Function raw_input returns values of type string, so the object referenced by integer1 (line 5) is of type string. To perform integer addition on the value referenced by integer1, the program must convert the string value to an integer value. Python function int (line 6) converts a noninteger value to an integer value and returns the new value. If we do not obtain an integer value for variable integer1, we will not achieve the desired results the program would concatenate (merge) two strings instead of adding two integers (Fig. 2.8).

8 80 Introduction to Python Programming Chapter 2 Python 2.2b1 (#25, Oct , 11:44:52) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> value1 = raw_input( "Enter an integer: " ) Enter an integer: 2 >>> value2 = raw_input( "Enter an integer: " ) Enter an integer: 4 >>> print value1 + value2 24 Fig. 2.8 Adding values from raw_input without converting to integers. (Copyright 2001 Python Software Foundation.) The assignment statement (line 11 of Fig. 2.7) calculates the sum of the variables integer1 and integer2 and assigns the result to variable sum using the assignment symbol =. The statement is read as, sum gets the value of integer1 + integer2. Most calculations are performed through assignment statements. The + symbol is an operator a special symbol that performs a specific operation. In this case, the + operator performs addition. The + operator is called a binary operator, because it receives two operands (values) on which it performs its operation. In this example, the operands are integer1 and integer2. Good Programming Practice 2.4 Place spaces on either side of a binary operator or symbol. This makes the operator or symbol stand out and create a more easily readable program. 2.4 Line 14 displays the string "Sum is" followed by the numerical value of variable sum. Items we want to output are separated by commas (,). Note that the print statement outputs multiple values of different types. Python knows how to convert each piece of data to a string before outputting it. Calculations also can be performed in output statements. We could have combined the statements in lines 11 and 13 into the statement print "Sum is", integer1 + integer2 thus eliminating the need for variable sum. A powerful feature of Python is that users can create their own data types. (We explore this capability in Chapter 7, Classes and Data Abstraction.) Users can then teach Python how to output values of these new data types using the print statement. (This is accomplished through method overriding a topic we explore in Chapter 8, Customizing Classes.) 2.4 Memory Concepts Variable names such as integer1, integer2 and sum actually correspond to Python objects. Every object has a type, a size, a value and a location in the computer s memory.

9 Chapter 2 Introduction to Python Programming 81 A program cannot change an object s type or location. Some object types permit programmers to change the object s value. We discuss these types beginning in Chapter 5, Tuples, Lists and Dictionaries. When the addition program in Fig. 2.7, executes the statement integer1 = raw_input( "Enter first integer:\n" ) Python first creates an object to hold the user-entered string and places the object into a memory location. The = assignment symbol then binds the name integer1 to the newly created object. Suppose the user enters 45 at the raw_input prompt. Python places "45" into a memory location to which the name integer1 is bound, as shown in Fig integer1 "45" Fig. 2.9 Memory location showing value of a variable and the name bound to the value. When the statement integer1 = int( integer1 ) is executed, function int creates a new object to store the integer value 45. This integer object is contained in a new memory location, and Python binds the name integer1 to this new memory location (Fig. 2.10). Variable integer1 no longer refers to the memory location that contains the string value "45". We demonstrate this at the end of this section. "45" integer1 45 Fig Memory location showing the name and value of a variable. Returning to our addition program, when the statements integer2 = raw_input( "Enter second integer:\n" ) integer2 = int( integer2 ) are executed, suppose the user enters the value "72". This value is converted to the integer value 72 by the second line, placed into a memory location to which integer2 is bound, and memory appears as in Fig Note that these locations are not necessarily adjacent locations in memory.

10 82 Introduction to Python Programming Chapter 2 integer1 45 integer2 72 Fig Memory locations after values for two variables have been input. Once the program has obtained values for integer1 and integer2, it adds these values and assigns the sum to variable sum. The statement sum = integer1 + integer2 that performs the addition causes memory to appear as in Fig Note that the values of integer1 and integer2 appear exactly as they did before they were used in the calculation of sum. These values were used, but not destroyed, as the computer performed the calculation. Thus, when a value is read out of a memory location, the process is nondestructive. integer1 45 integer2 72 sum 117 Fig Memory locations after a calculation. In Fig. 2.13, the program demonstrates that each Python object has a location, a type and a value and that these properties are accessed through an object s name. This program is identical to the program in Fig. 2.7, except that we have added statements that display the memory location, type and value for each object at various points in the program. 1 # Fig. 2.13: fig02_13.py 2 # Displaying location, type and value 3 4 # prompt the user for input 5 integer1 = raw_input( "Enter first integer:\n" ) # read a string 6 print "integer1: ", id( integer1 ), type( integer1 ), integer1 7 integer1 = int( integer1 ) # convert the string to an integer 8 print "integer1: ", id( integer1 ), type( integer1 ), integer integer2 = raw_input( "Enter second integer:\n" ) # read a string Fig Displaying an object s location and type (part 1 of 2).

11 Chapter 2 Introduction to Python Programming print "integer2: ", id( integer2 ), type( integer2 ), integer2 12 integer2 = int( integer2 ) # convert the string to an integer 13 print "integer2: ", id( integer2 ), type( integer2 ), integer sum = integer1 + integer2 # assignment of sum 16 print "sum: ", id( sum ), type( sum ), sum Enter first integer: 5 integer1: <type 'string'> 5 integer1: <type 'int'> 5 Enter second integer: 27 integer2: <type 'string'> 27 integer2: <type 'int'> 27 sum: <type 'int'> 32 Fig Displaying an object s location and type (part 2 of 2). Line 6 prints integer1 s location, type and value after the call to raw_input. Python function id returns the interpreter s representation of the variable s location. Function type returns the type of the variable. We print these values again (line 8), after converting the string value in integer1 to an integer value. Notice that both the type and the location of variable integer1 change as a result of the statement integer1 = int( integer1 ) The change underscores the fact that a program cannot change a variable s type. Instead, the statement causes Python to create a new integer value in a new location and assigns the name integer1 to this location. The location to which integer1 previously referred is no longer accessible. The remainder of the program prints the location type and value for variables integer2 and sum in a similar manner. Functions id and type are examples of Python s introspective capabilities Python s ability to provide information about itself. An advanced program might use these functions to perform the program s task. In our example, however, we use these functions only to reenforce basic facts about Python variables. 2.5 Arithmetic Many programs perform arithmetic calculations. The arithmetic operators are summarized in Fig Note the use of various special symbols not used in algebra. The asterisk (*) indicates multiplication, and the percent sign (%) is the modulus operator that we discuss shortly. The arithmetic operators in Fig are all binary operators, (i.e., operators that take two operands). For example, the expression integer1 + integer2 contains the binary operator + and the two operands integer1 and integer2.

12 84 Introduction to Python Programming Chapter 2 Python operation Arithmetic operator Algebraic expression Python expression Addition + f + 7 f + 7 Subtraction - p c p - c Multiplication * bm b * m Exponentiation ** x^y or x y x ** y Division / // (new in Python 2.2) x / y or or x y x / y x // y Modulus % r mod s r % s x - y Fig Arithmetic operators. Python is a growing language, and as such, some language features change over time. Starting with Python 2.2, the behavior of the / division operator will begin to change from floor division to true division. Floor division (sometimes called integer division), divides the numerator by the denominator and returns the highest integer value that is no more than the result. For example, dividing 7 by 4 with floor division yields 1, and dividing 17 by 5 with floor division yields 3. Note that any fractional part in floor division is simply discarded (i.e., truncated) no rounding occurs. True division yields the precise floatingpoint result of dividing the numerator by the denominator. For example, dividing 7 by 4 with true division yields In prior versions, Python contained only one operator for division the / operator. The behavior (i.e., floor or true division) of the operator is determined by the type of the operands. If the operands are both integers, the operator performs floor division. If one or both of the operands are floating-point numbers, the operator perform true division. The language designers and many programmers disliked the ambiguity of the / operator and decided to create two operators for version 2.2 one for each type of division. The / operator performs true division, and the // operator performs floor division. However, this decision could introduce errors into programs that use older versions of Python. Therefore, the designers came up with a compromise: Starting with Python 2.2 all future 2.x versions will include two operators, but if a program author wants to use the new behavior, the programmer must state their intention explicitly with the statement from future import division After Python sees this statement, the / operator performs true division and the // operator performs floor division. Figure 2.15 contains an example.

13 Chapter 2 Introduction to Python Programming 85 Python 2.2b1 (#25, Oct , 11:44:52) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> 3 / 4 # floor division (default behavior) 0 >>> 3.0 / 4.0 # true division (floating-point operands) 0.75 >>> 3 // 4 # floor division (only behavior) 0 >>> 3.0 // 4.0 # floating-point floor division 0.0 >>> from future import division >>> 3 / 4 # true division (new behavior) 0.75 >>> 3.0 / 4.0 # true division (same as before) 0.75 Fig Difference in behavior of the / operator. (Copyright 2001 Python Software Foundation.) We first evaluate the expression 3 / 4. This expression evaluates to the value 0, because the default behavior of the / operator with integer operands is floor division. The expression 3.0 / 4.0 evaluates to In this case, we use floating-point operands, so the / operator performs true division. The expressions 3 // 4 and 3.0 // 4.0 evaluate to 0 and 0.0, respectively, because the // operator always performs floor division, regardless of the types of the operands. Then, we change the behavior of the / operator with the special import statement. In effect, this statement turns on the true division behavior for operator /. Now the expression 3 / 4 evaluates to In this text, we use only the default 2.2 behavior for the / operator, namely floor division for integers and true division for floating-point numbers. In Python version 3.0 (due to be released no sooner than 2003), the / operator can perform only true division. After the release of version 3.0, programmers need to update applications to compensate for the new behavior. For more information on the change, see Python provides the modulus operator (%), which yields the remainder after integer division. The modulus operator usually is used only with integer operands. The expression x % y yields the remainder after x is divided by y. Thus, 7 % 4 yields 3 and 17 % 5 yields 2. In later chapters, we discuss many interesting applications of the modulus operator, such as determining whether one number is a multiple of another. (A special case of this is determining whether a number is odd or even.) Arithmetic expressions in Python must be entered into the computer in straight-line form. Thus, expressions such as a divided by b must be written as a / b, so that all constants, variables and operators appear in a straight line. The algebraic notation

14 86 Introduction to Python Programming Chapter 2 a -- b is generally not acceptable to compilers or interpreters, although some special-purpose software packages do exist that support more natural notation for complex mathematical expressions. Parentheses are used in Python expressions in much the same manner as in algebraic expressions. For example, to multiply a times the quantity b + c, we write a * (b + c) Python applies the operators in arithmetic expressions in a precise sequence determined by the following rules of operator precedence, which are generally the same as those followed in algebra: 1. Expressions contained within pairs of parentheses are evaluated first. Thus, parentheses may force the order of evaluation to occur in any sequence desired by the programmer. Parentheses are said to be at the highest level of precedence. In cases of nested, or embedded, parentheses, the operators in the innermost pair of parentheses are applied first. 2. Exponentiation operations are applied next. If an expression contains several exponentiation operations, operators are applied from right to left. 3. Multiplication, division and modulus operations are applied next. If an expression contains several multiplication, division and modulus operations, operators are applied from left to right. Multiplication, division and modulus are said to be on the same level of precedence. 4. Addition and subtraction operations are applied last. If an expression contains several addition and subtraction operations, operators are applied from left to right. Addition and subtraction also have the same level of precedence. Not all expressions with several pairs of parentheses contain nested parentheses. For example, the expression a * (b + c) + c * (d + e) does not contain nested parentheses. Rather, the parentheses are said to be on the same level. The rules of operator precedence enable Python to apply operators in the correct order. When we say that certain operators are applied from left to right, we are referring to the associativity of the operators. For example, in the expression a + b + c the addition operators (+) associate from left to right. We will see that some operators associate from right to left. Figure 2.16 summarizes these rules of operator precedence. This table will be expanded as additional Python operators are introduced. A complete precedence chart is included in the appendices.

15 Chapter 2 Introduction to Python Programming 87 Operator(s) Operation(s) Order of Evaluation (Precedence) ( ) Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses on the same level (i.e., not nested), they are evaluated left to right. ** Exponentiation Evaluated second. If there are several, they are evaluated right to left. * / // % Multiplication Division Modulus + - Addition Subtraction Evaluated third. If there are several, they are evaluated left to right. [Note: The // operator is new in version 2.2] Evaluated last. If there are several, they are evaluated left to right. Fig Precedence of arithmetic operators. Now let us consider several expressions in light of the rules of operator precedence. Each example lists an algebraic expression and its Python equivalent. The following is an example of an arithmetic mean (average) of five terms: Algebra: m = a + b + c + d + e Python: m = ( a + b + c + d + e ) / 5 The parentheses are required because division has higher precedence than addition. The entire quantity ( a + b + c + d + e ) is to be divided by 5. If the parentheses are erroneously omitted, we obtain a + b + c + d + e / 5, which evaluates incorrectly as e a + b + c + d The following is an example of the equation of a straight line: Algebra: y = mx + b Python: y = m * x + b No parentheses are required. The multiplication is applied first, because multiplication has a higher precedence than addition. The following example contains modulus (%), multiplication, division, addition and subtraction operations:

16 88 Introduction to Python Programming Chapter 2 Algebra: z = pr%q + w/x y Python: z = p * r % q + w / x - y The circled numbers under the statement indicate the order in which Python applies the operators. The multiplication, modulus and division are evaluated first, in left-to-right order (i.e., they associate from left to right) because they have higher precedence than addition and subtraction. The addition and subtraction are applied next. These are also applied left to right. Once the expression has been evaluated, Python assigns the result to variable z. To develop a better understanding of the rules of operator precedence, consider how a second-degree polynomial is evaluated: y = a * x ** 2 + b * x + c The circled numbers under the statement indicate the order in which Python applies the operators. Suppose variables a, b, c and x are initialized as follows: a = 2, b = 3, c = 7 and x = 5. Figure 2.17 illustrates the order in which the operators are applied in the preceding second-degree polynomial.

17 Chapter 2 Introduction to Python Programming 89 Step 1. y = 2 * 5 ** * ** 2 is 25 (Exponentiation) Step 2. y = 2 * * * 25 is 50 (Leftmost multiplication) Step 3. y = * * 5 is 15 (Multiplication before addition) Step 4. y = is 65 (Leftmost addition) Step 5. y = is 72 (Last addition) Step 6. y = 72 (Python assigns 72 to y) Fig Order in which a second-degree polynomial is evaluated. The preceding assignment statement can be parenthesized with unnecessary parentheses for clarity as y = ( a * ( x ** 2 ) ) + ( b * x ) + c Good Programming Practice 2.5 As in algebra, it is acceptable to place unnecessary parentheses in an expression to make the expression clearer. These parentheses are called redundant parentheses. Redundant parentheses are commonly used to group subexpressions in a large expression to make that expression clearer. Breaking a large statement into a sequence of shorter, simpler statements also promotes clarity String Formatting Now that we have investigated Python numeric values, let us turn our attention to Python strings. Unlike some other popular programming languages, Python provides strings as a

18 90 Introduction to Python Programming Chapter 2 basic data type, thereby enabling Python programs to perform powerful text-based operations simply. We have already learned how to create a string by placing text inside double quotes ("). Python strings can be created in a variety of other ways, as Fig demonstrates. 1 # Fig. 2.18: fig02_18.py 2 # Creating strings and using quote characters in strings 3 4 print "This is a string with \"double quotes.\"" 5 print 'This is another string with "double quotes."' 6 print 'This is a string with \'single quotes.\'' 7 print "This is another string with 'single quotes.'" 8 print """This string has "double quotes" and 'single quotes'. 9 You can even do multiple lines.""" 10 print '''This string also has "double" and 'single' quotes.''' This is a string with "double quotes." This is another string with "double quotes." This is a string with 'single quotes.' This is another string with 'single quotes.' This string has "double quotes" and 'single quotes'. You can even do multiple lines. This string also has "double" and 'single' quotes. Fig Creating Python strings. Line 4 creates a string with the familiar double-quote character ("). If we want such a string to print double quotes to the screen, we must use the escape sequence for the doublequote character, rather than the double-quote character itself. Recall from Fig. 2.6 that the escape sequence for the double-quote character is \". Strings can be created using the single-quote character ('), too (line 5). If we want to use the double-quote character inside a string created with single quotes, we do not need to use the escape character. Similarly, if we want to use a single-quote character inside a string created with double quotes, we do not need to use the escape sequence (line 7). However, if we want to use the single-quote character inside a string created with single quotes, we must use the escape sequence (line 6). Python also supports triple-quoted strings (lines 8 10). Triple-quoted strings are useful for programs that output strings with special characters such as quote characters. Single- or double-quote characters inside a triple-quoted string do not need to use the escape sequence. Triple-quoted strings also are used for large blocks of text because triplequoted strings can span multiple lines. In this book, we use triple-quoted strings when we write programs that output large blocks of text for the Web. Python strings support simple, but powerful, output formatting, not available to basic data types in some other languages. We can create strings that format output in several ways: 1. Rounding floating-point values to an indicated number of decimal places. 2. Representing floating-point numbers in exponential format.

19 Chapter 2 Introduction to Python Programming Aligning a column of numbers with decimal points appearing one above the other. 4. Using right-justification and left-justification of outputs. 5. Inserting literal characters at precise locations in a line of output. 6. Displaying all types of data with fixed-size field widths and precision. The program in Fig demonstrates basic string-formatting capabilities. 1 # Fig. 2.19: fig02_19.py 2 # String formatting. 3 4 integervalue = print "Integer ", integervalue 6 print "Decimal integer %d" % integervalue 7 print "Hexadecimal integer %x\n" % integervalue 8 9 floatvalue = print "Float", floatvalue 11 print "Default float %f" % floatvalue 12 print "Default exponential %e\n" % floatvalue print "Right justify integer (%8d)" % integervalue 15 print "Left justify integer (%-8d)\n" % integervalue stringvalue = "String formatting" 18 print "Force eight digits in integer %.8d" % integervalue 19 print "Five digits after decimal in float %.5f" % floatvalue 20 print "Fifteen and five characters allowed in string:" 21 print "(%.15s) (%.5s)" % ( stringvalue, stringvalue ) Integer 4237 Decimal integer 4237 Hexadecimal integer 108d Float Default float Default exponential e+005 Right justify integer ( 4237) Left justify integer (4237 ) Force eight digits in integer Five digits after decimal in float Fifteen and five characters allowed in string: (String formatti) (Strin) Fig Demonstrating the string-formatting operator %. Lines 4 7 demonstrate how to represent integers in a string. Line 5 simply prints the value of variable integervalue, without string formatting. The % formatting operator inserts the value of a variable in a string (line 6). The value to the left of the operator is a string that contains one or more conversion specifiers place holders for values in the

20 92 Introduction to Python Programming Chapter 2 string. Each conversion specifier begins with a percent sign (%) and ends with a conversionspecifier symbol. Conversion-specifier symbol d indicates that we want to place an integer within the current string at the specified point. Figure 2.20 lists several conversion-specifier symbols for use in string formatting. [Note: See Appendix C, Number Systems, for a discussion of numeric terminology in Fig ] Conversion Specifier Symbol Meaning c s d u o x X f Single character (i.e., a string of length one) or the integer representation of an ASCII character. String or a value to be converted to a string. Signed decimal integer. Unsigned decimal integer. Unsigned octal integer. Unsigned hexadecimal integer (using format abcdef). Unsigned hexadecimal integer (using format ABCDEF). Floating-point number. e, E Floating-point number (using scientific notation). g, G Floating-point number (using least-significant digits). Fig String-formatting characters. The value to the right of the % formatting operator specifies what replaces the placeholders in the strings. In line 6, we specify the value integervalue to replace the %d placeholder in the string. Line 7 inserts the hexadecimal value assigned to variable integervalue into the string. Lines 9 12 demonstrate how to insert floating-point values in a string. The f conversion specifier acts as a place holder for a floating-point value (line 11). To the right of the % formatting operator, we use variable floatvalue as the value to be displayed. The e conversion specifier acts as a place holder for a floating-point value in scientific notation. Lines demonstrate string formatting with field widths. A field width is the exact size of a field in which a value is printed. If the field width is larger than the value being printed, the data are normally right-justified within the field. To use field widths, place an integer representing the field width between the percent sign and the conversion-specifier symbol. Line 14 right-justifies the value of variable integervalue in a field width of size eight. To left-justify a value, specify a negative integer as the field width (line 15). Lines demonstrate string formatting with precision. Precision has different meaning for different data types. When used with integer conversion specifiers, precision indicates the minimum number of digits to be printed. If the printed value contains fewer digits than the specified precision, zeros are prefixed to the printed value until the total number of digits is equivalent to the precision. To use precision, place a decimal point (.) followed by an integer representing the precision between the percent sign and the conver-

21 Chapter 2 Introduction to Python Programming 93 sion specifier. Line 18 prints the value of variable integervalue with a precision of eight. When precision is used with a floating-point conversion specifier, the precision is the number of digits to appear after the decimal point. Line 19 prints the value of variable floatvalue with a precision of five. When used with a string-conversion specifier, the precision is the maximum number of characters to be written from the string. Line 21 prints the value of variable stringvalue twice once with a precision of fifteen and once with a precision of five. Notice that the conversion specifications are contained within parentheses. When the string to the left of the % formatting operator contains more than one conversion specifier, the value to the right of the operator must be a comma-separated sequence of conversion specifications. This sequence is contained within parentheses and must have the same number of conversion specifications as the string has conversion specifiers. Python constructs the string from left to right by matching a placeholder with the next value specified between parentheses and replacing the formatting character with that value. Python strings support even more powerful string-formatting capabilities through string methods. We discuss string methods in detail in Chapter 13, String Manipulation and Regular Expressions. 2.7 Decision Making: Equality and Relational Operators This section introduces a simple version of Python s if structure that allows a program to make a decision based on the truth or falsity of some condition. If the condition is true, (i.e., the condition is met), the statement in the body of the if structure is executed. If the condition is not met, the body statement is not executed. We will see an example shortly. Conditions in if structures can be formed using the equality operators and relational operators summarized in Fig The relational operators all have the same level of precedence and associate from left to right. All equality operators have the same level of precedence, which is lower than the precedence of the relational operators. The equality operators also associate from left to right. Common Programming Error 2.1 A syntax error occurs if any of the operators ==,!=, >= and <= appear with spaces between its pair of symbols. 2.1 Common Programming Error 2.2 Reversing the order of the pair of operators in any of the operators!=, <>, >= and <= (by writing them as =!, ><, => and =<, respectively) is a syntax error. 2.2 Standard algebraic equality operator or relational operator Python equality or relational operator Example of Python condition Meaning of Python condition Relational operators > > x > y x is greater than y Fig Equality and relational operators (part 1 of 2).

22 94 Introduction to Python Programming Chapter 2 Standard algebraic equality operator or relational operator Python equality or relational operator Example of Python condition Meaning of Python condition < < x < y x is less than y >= x >= y x is greater than or equal to y <= x <= y x is less than or equal to y Equality operators = == x == y x is equal to y!=, <> x!= y, x is not equal to y x <> y Fig Equality and relational operators (part 2 of 2). Common Programming Error 2.3 Confusing the equality operator == with the assignment symbol = is a common error. The equality operator should be read is equal to and the assignment symbol should be read gets, gets the value of or is assigned the value of. Some people prefer to read the equality operator as double equals. In Python, the assignment symbol causes a syntax error when used in a conditional statement. 2.3 The following example uses six if statements to compare two user-entered numbers. If the condition in any of these if statements is satisfied, the output statement associated with that if is executed. The program and three sample executions are shown in Fig # Fig. 2.22: fig02_22.py 2 # Using if statements, relational operators and 3 # equality operators 4 5 print "Enter two integers, and I will tell you" 6 print "the relationships they satisfy." 7 8 # read first string and convert to integer 9 number1 = raw_input( "Please enter first integer: " ) 10 number1 = int( number1 ) # read second string and convert to integer 13 number2 = raw_input( "Please enter second integer: " ) 14 number2 = int( number2 ) if number1 == number2: 17 print "%d is equal to %d" % ( number1, number2 ) if number1!= number2: 20 print "%d is not equal to %d" % ( number1, number2 ) 21 Fig Equality and relational operators used to determine mathematical relationships (part 1 of 2).

23 Chapter 2 Introduction to Python Programming if number1 < number2: 23 print "%d is less than %d" % ( number1, number2 ) if number1 > number2: 26 print "%d is greater than %d" % ( number1, number2 ) if number1 <= number2: 29 print "%d is less than or equal to %d" % ( number1, number2 ) if number1 >= number2: 32 print "%d is greater than or equal to %d" % ( number1, number2 ) Enter two integers, and I will tell you the relationships they satisfy. Please enter first integer: 37 Please enter second integer: is not equal to is less than is less than or equal to 42 Enter two integers, and I will tell you the relationships they satisfy. Please enter first integer: 7 Please enter second integer: 7 7 is equal to 7 7 is less than or equal to 7 7 is greater than or equal to 7 Fig Equality and relational operators used to determine mathematical relationships (part 2 of 2). The program uses Python functions raw_input and int to input two integers (lines 8 14). First a value is obtained for variable number1, then a value is obtained for variable number2. The if structure in lines compares the values of variables number1 and number2 to test for equality. If the values are equal, the statement displays a line of text indicating that the numbers are equal (line 17). If the conditions are met in one or more of the if structures starting at lines 19, 22, 25, 28 and 31, the corresponding print statement displays a line of text. Each if structure consists of the word if, the condition to be tested and a colon (:). An if structure also contains a body. Notice that each if structure in Fig has a single statement in its body and that each body is indented. Some languages, like C++ and Java, use braces ( { } ) to denote the body of if structures; Python requires indentation. We discuss indentation in the next section. Common Programming Error 2.4 Forgetting the colon (:) in an if structure causes a syntax error. 2.4

24 96 Introduction to Python Programming Chapter 2 Common Programming Error 2.5 Forgetting to indent the body of an if structure causes a syntax error. 2.5 Good Programming Practice 2.6 Set a convention for the size of indent you prefer, then apply that convention uniformly. The tab key may create indents, but tab stops may vary. We recommend using three spaces to form a level of indent. However, the Python style guide recommends using four spaces. 2.6 In Python, syntax evaluation is dependent on white space, thus, the inconsistent use of white space can cause syntax errors. For instance, splitting a statement over multiple lines can result in a syntax error. If a statement is long, the statement can be spread over multiple lines using the \ line-continuation character (Fig. 2.23). Some interpreters use "..." to denote a continuing line. Python 2.2b1 (#25, Oct , 11:44:52) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> print 1 + File "<stdin>", line 1 print 1 + ^ SyntaxError: invalid syntax >>> print 1 + \ >>> Fig Demonstrating the \ line-continuation character. (Copyright 2001 Python Software Foundation.) Good Programming Practice 2.7 A lengthy statement may be spread over several lines with the \ continuation character. If a single statement must be split across lines, choose breaking points that make sense, such as after a comma in a print statement or after an operator in a lengthy expression. 2.7 Figure 2.24 shows the precedence of the operators introduced in this chapter. The operators are shown from top to bottom in decreasing order of precedence. Notice that all these operators, except exponentiation, associate from left to right. Operators Associativity Type () left to right parentheses ** right to left exponential * / // % left to right multiplicative + - left to right additive Fig Precedence and associativity of the operators discussed so far.

25 Chapter 2 Introduction to Python Programming 97 Operators Associativity Type < <= > >= left to right relational ==!= <> left to right equality Fig Precedence and associativity of the operators discussed so far. Good Programming Practice 2.8 Refer to the operator precedence chart when writing expressions containing many operators. Confirm that the operators in the expression are performed in the order you expect. If you are uncertain about the order of evaluation in a complex expression, break the expression into smaller statements or use parentheses to force the order, exactly as you would do in an algebraic expression. Be sure to observe that some operators, such as exponentiation (**), associate from right to left rather than from left to right Indentation Python uses indentation to delimit (distinguish) blocks of code, called suites. This is in contrast to many other programming languages, which normally use braces to delimit blocks of code. The Python programmer chooses the number of spaces to indent a suite, and the number of spaces must remain consistent within a suite. Python recognizes new suites when there is a change in the number of indented spaces. If a single suite contains lines of code which are not uniformly indented, the Python interpreter reads those lines as belonging to other suites, normally resulting in syntax errors. Figure 2.25 contains a modified version of the code in Fig to illustrate improper indentation. 1 # Fig. 2.25: fig02_25.py 2 # Using if statements, relational operators and equality 3 # operators to show improper indentation 4 5 print "Enter two integers, and I will tell you" 6 print "the relationships they satisfy." 7 8 # read first string and convert to integer 9 number1 = raw_input( "Please enter first integer: " ) 10 number1 = int( number1 ) # read second string and convert to integer 13 number2 = raw_input( "Please enter second integer: " ) 14 number2 = int( number2 ) if number1 == number2: 17 print "%d is equal to %d" % ( number1, number2 ) # improper indentation causes this if statement to execute only Fig if statements used to show improper indentation (part 1 of 2).

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

Introduction to C++ Programming Pearson Education, Inc. All rights reserved. 1 2 Introduction to C++ Programming 2 What s in a name? that which we call a rose By any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would be the

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

Programming for Engineers Introduction to C

Programming for Engineers Introduction to C Programming for Engineers Introduction to C ICEN 200 Spring 2018 Prof. Dola Saha 1 Simple Program 2 Comments // Fig. 2.1: fig02_01.c // A first program in C begin with //, indicating that these two lines

More information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator 1 A Closer Look at the / Operator Used for performing numeric calculations C++ has unary, binary, and ternary s: unary (1 operand) - binary ( operands) 13-7 ternary (3 operands) exp1? exp : exp3 / (division)

More information

Chapter 2 - Introduction to C Programming

Chapter 2 - Introduction to C Programming Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.1: Introduction to C# App Programming Xianrong (Shawn) Zheng Spring 2017 1 Outline Introduction Creating a Simple App String Interpolation

More information

2.5 Another Application: Adding Integers

2.5 Another Application: Adding Integers 2.5 Another Application: Adding Integers 47 Lines 9 10 represent only one statement. Java allows large statements to be split over many lines. We indent line 10 to indicate that it s a continuation of

More information

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 6/e 1992-2010 by Pearson Education, Inc. An important part of the solution to any problem is the presentation of the results. In this chapter, we discuss in depth the formatting features

More information

Chapter 1 Introduction to Computers and C++ Programming

Chapter 1 Introduction to Computers and C++ Programming Chapter 1 Introduction to Computers and C++ Programming 1 Outline 1.1 Introduction 1.2 What is a Computer? 1.3 Computer Organization 1.7 History of C and C++ 1.14 Basics of a Typical C++ Environment 1.20

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 1992-2010 by Pearson Education, Inc. All Rights Reserved. 2 1992-2010 by Pearson Education, Inc. All Rights Reserved. 3 1992-2010 by Pearson Education, Inc. All Rights Reserved. 4 1992-2010 by Pearson

More information

Chapter 2 Author Notes

Chapter 2 Author Notes Chapter 2 Author Notes Good Programming Practice 2.1 Every program should begin with a comment that explains the purpose of the program, the author and the date and time the program was last modified.

More information

Full file at C How to Program, 6/e Multiple Choice Test Bank

Full file at   C How to Program, 6/e Multiple Choice Test Bank 2.1 Introduction 2.2 A Simple Program: Printing a Line of Text 2.1 Lines beginning with let the computer know that the rest of the line is a comment. (a) /* (b) ** (c) REM (d)

More information

Chapter 2, Part III Arithmetic Operators and Decision Making

Chapter 2, Part III Arithmetic Operators and Decision Making Chapter 2, Part III Arithmetic Operators and Decision Making C How to Program, 8/e, GE 2016 Pearson Education, Ltd. All rights reserved. 1 2016 Pearson Education, Ltd. All rights reserved. 2 2016 Pearson

More information

Introduction to Java Applications; Input/Output and Operators

Introduction to Java Applications; Input/Output and Operators www.thestudycampus.com Introduction to Java Applications; Input/Output and Operators 2.1 Introduction 2.2 Your First Program in Java: Printing a Line of Text 2.3 Modifying Your First Java Program 2.4 Displaying

More information

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance. 2.1 Introduction (No questions.) 2.2 A Simple Program: Printing a Line of Text 2.1 Which of the following must every C program have? (a) main (b) #include (c) /* (d) 2.2 Every statement in C

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

JavaScript: Introduction to Scripting

JavaScript: Introduction to Scripting iw3htp2.book Page 194 Wednesday, July 18, 2001 9:01 AM 7 JavaScript: Introduction to Scripting Objectives To be able to write simple JavaScript programs. To be able to use input and output statements.

More information

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Introduction to C Programming Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline Printing texts Adding 2 integers Comparing 2 integers C.E.,

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 5 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel s slides Sahrif University of Technology Outlines

More information

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

Introduction to C++ Programming. Adhi Harmoko S, M.Komp Introduction to C++ Programming Adhi Harmoko S, M.Komp Machine Languages, Assembly Languages, and High-level Languages Three types of programming languages Machine languages Strings of numbers giving machine

More information

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

Fundamentals of Programming. Lecture 3: Introduction to C Programming

Fundamentals of Programming. Lecture 3: Introduction to C Programming Fundamentals of Programming Lecture 3: Introduction to C Programming Instructor: Fatemeh Zamani f_zamani@ce.sharif.edu Sharif University of Technology Computer Engineering Department Outline A Simple C

More information

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */ Overview Language Basics This chapter describes the basic elements of Rexx. It discusses the simple components that make up the language. These include script structure, elements of the language, operators,

More information

Fundamentals of Programming Session 4

Fundamentals of Programming Session 4 Fundamentals of Programming Session 4 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2011 These slides are created using Deitel s slides, ( 1992-2010 by Pearson Education, Inc).

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

2.8. Decision Making: Equality and Relational Operators

2.8. Decision Making: Equality and Relational Operators Page 1 of 6 [Page 56] 2.8. Decision Making: Equality and Relational Operators A condition is an expression that can be either true or false. This section introduces a simple version of Java's if statement

More information

Full file at

Full file at Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional

More information

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional

More information

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Bits, Words, and Integers

Bits, Words, and Integers Computer Science 52 Bits, Words, and Integers Spring Semester, 2017 In this document, we look at how bits are organized into meaningful data. In particular, we will see the details of how integers are

More information

Program Elements -- Introduction

Program Elements -- Introduction Program Elements -- Introduction We can now examine the core elements of programming Chapter 3 focuses on: data types variable declaration and use operators and expressions decisions and loops input and

More information

Variables and Literals

Variables and Literals C++ By 4 EXAMPLE Variables and Literals Garbage in, garbage out! To understand data processing with C++, you must understand how C++ creates, stores, and manipulates data. This chapter teaches you how

More information

Chapter 1 & 2 Introduction to C Language

Chapter 1 & 2 Introduction to C Language 1 Chapter 1 & 2 Introduction to C Language Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 1 & 2 - Introduction to C Language 2 Outline 1.1 The History

More information

Introduction to C# Applications

Introduction to C# Applications 1 2 3 Introduction to C# Applications OBJECTIVES To write simple C# applications To write statements that input and output data to the screen. To declare and use data of various types. To write decision-making

More information

Introduction to C# Applications Pearson Education, Inc. All rights reserved.

Introduction to C# Applications Pearson Education, Inc. All rights reserved. 1 3 Introduction to C# Applications 2 What s in a name? That which we call a rose by any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would be the

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

Reserved Words and Identifiers

Reserved Words and Identifiers 1 Programming in C Reserved Words and Identifiers Reserved word Word that has a specific meaning in C Ex: int, return Identifier Word used to name and refer to a data element or object manipulated by the

More information

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on: Data and Expressions Data and Expressions Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration And Use Of Variables Expressions

More information

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators 1 Professor: Sana Odeh odeh@courant.nyu.edu Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators Review What s wrong with this line of code? print( He said Hello ) What s wrong with

More information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

Maciej Sobieraj. Lecture 1

Maciej Sobieraj. Lecture 1 Maciej Sobieraj Lecture 1 Outline 1. Introduction to computer programming 2. Advanced flow control and data aggregates Your first program First we need to define our expectations for the program. They

More information

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M tutor Isam M. Al Jawarneh, PhD student isam.aljawarneh3@unibo.it Mobile Middleware

More information

CMPT 125: Lecture 3 Data and Expressions

CMPT 125: Lecture 3 Data and Expressions CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,

More information

Chapter 2, Part I Introduction to C Programming

Chapter 2, Part I Introduction to C Programming Chapter 2, Part I Introduction to C Programming C How to Program, 8/e, GE 2016 Pearson Education, Ltd. All rights reserved. 1 2016 Pearson Education, Ltd. All rights reserved. 2 2016 Pearson Education,

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

Visual C# Instructor s Manual Table of Contents

Visual C# Instructor s Manual Table of Contents Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms

More information

JavaScript: Introductionto Scripting

JavaScript: Introductionto Scripting 6 Comment is free, but facts are sacred. C. P. Scott The creditor hath a better memory than the debtor. James Howell When faced with a decision, I always ask, What would be the most fun? Peggy Walker Equality,

More information

Chapter 17. Fundamental Concepts Expressed in JavaScript

Chapter 17. Fundamental Concepts Expressed in JavaScript Chapter 17 Fundamental Concepts Expressed in JavaScript Learning Objectives Tell the difference between name, value, and variable List three basic data types and the rules for specifying them in a program

More information

ANSI C Programming Simple Programs

ANSI C Programming Simple Programs ANSI C Programming Simple Programs /* This program computes the distance between two points */ #include #include #include main() { /* Declare and initialize variables */ double

More information

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language Chapter 1 Getting Started Introduction To Java Most people are familiar with Java as a language for Internet applications We will study Java as a general purpose programming language The syntax of expressions

More information

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh C++ PROGRAMMING For Industrial And Electrical Engineering Instructor: Ruba A. Salamh CHAPTER TWO: Fundamental Data Types Chapter Goals In this chapter, you will learn how to work with numbers and text,

More information

9. Elementary Algebraic and Transcendental Scalar Functions

9. Elementary Algebraic and Transcendental Scalar Functions Scalar Functions Summary. Introduction 2. Constants 2a. Numeric Constants 2b. Character Constants 2c. Symbol Constants 2d. Nested Constants 3. Scalar Functions 4. Arithmetic Scalar Functions 5. Operators

More information

Work relative to other classes

Work relative to other classes Work relative to other classes 1 Hours/week on projects 2 C BOOTCAMP DAY 1 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Overview C: A language

More information

Introduction to Java Applications

Introduction to Java Applications 2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

More information

4. Inputting data or messages to a function is called passing data to the function.

4. Inputting data or messages to a function is called passing data to the function. Test Bank for A First Book of ANSI C 4th Edition by Bronson Link full download test bank: http://testbankcollection.com/download/test-bank-for-a-first-book-of-ansi-c-4th-edition -by-bronson/ Link full

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

Unit 3. Operators. School of Science and Technology INTRODUCTION

Unit 3. Operators. School of Science and Technology INTRODUCTION INTRODUCTION Operators Unit 3 In the previous units (unit 1 and 2) you have learned about the basics of computer programming, different data types, constants, keywords and basic structure of a C program.

More information

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program Overview - General Data Types - Categories of Words - The Three S s - Define Before Use - End of Statement - My First Program a description of data, defining a set of valid values and operations List of

More information

4 Programming Fundamentals. Introduction to Programming 1 1

4 Programming Fundamentals. Introduction to Programming 1 1 4 Programming Fundamentals Introduction to Programming 1 1 Objectives At the end of the lesson, the student should be able to: Identify the basic parts of a Java program Differentiate among Java literals,

More information

CS112 Lecture: Working with Numbers

CS112 Lecture: Working with Numbers CS112 Lecture: Working with Numbers Last revised January 30, 2008 Objectives: 1. To introduce arithmetic operators and expressions 2. To expand on accessor methods 3. To expand on variables, declarations

More information

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output Last revised January 12, 2006 Objectives: 1. To introduce arithmetic operators and expressions 2. To introduce variables

More information

Chapter 2: Introduction to C++

Chapter 2: Introduction to C++ Chapter 2: Introduction to C++ Copyright 2010 Pearson Education, Inc. Copyright Publishing as 2010 Pearson Pearson Addison-Wesley Education, Inc. Publishing as Pearson Addison-Wesley 2.1 Parts of a C++

More information

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Copyright 2009 Publishing Pearson as Pearson Education, Addison-Wesley Inc. Publishing as Pearson Addison-Wesley

More information

Data Types and Variables in C language

Data Types and Variables in C language Data Types and Variables in C language Basic structure of C programming To write a C program, we first create functions and then put them together. A C program may contain one or more sections. They are

More information

2.2 Syntax Definition

2.2 Syntax Definition 42 CHAPTER 2. A SIMPLE SYNTAX-DIRECTED TRANSLATOR sequence of "three-address" instructions; a more complete example appears in Fig. 2.2. This form of intermediate code takes its name from instructions

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure C Overview Basic C Program Structure C OVERVIEW BASIC C PROGRAM STRUCTURE Goals The function main( )is found in every C program and is where every C program begins speed execution portability C uses braces

More information

CPS122 Lecture: From Python to Java

CPS122 Lecture: From Python to Java Objectives: CPS122 Lecture: From Python to Java last revised January 7, 2013 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Chapter 2 Working with Data Types and Operators

Chapter 2 Working with Data Types and Operators JavaScript, Fourth Edition 2-1 Chapter 2 Working with Data Types and Operators At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics

More information

CS102: Variables and Expressions

CS102: Variables and Expressions CS102: Variables and Expressions The topic of variables is one of the most important in C or any other high-level programming language. We will start with a simple example: int x; printf("the value of

More information

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O Overview of C Basic Data Types Constants Variables Identifiers Keywords Basic I/O NOTE: There are six classes of tokens: identifiers, keywords, constants, string literals, operators, and other separators.

More information

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual: Java Programming, Eighth Edition 2-1 Chapter 2 Using Data A Guide to this Instructor s Manual: We have designed this Instructor s Manual to supplement and enhance your teaching experience through classroom

More information

Chapter Two PROGRAMMING WITH NUMBERS AND STRINGS

Chapter Two PROGRAMMING WITH NUMBERS AND STRINGS Chapter Two PROGRAMMING WITH NUMBERS AND STRINGS Introduction Numbers and character strings are important data types in any Python program These are the fundamental building blocks we use to build more

More information

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

CPS122 Lecture: From Python to Java last revised January 4, Objectives: Objectives: CPS122 Lecture: From Python to Java last revised January 4, 2017 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

More information

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d.

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d. Gaddis: Starting Out with Python, 2e - Test Bank Chapter Two MULTIPLE CHOICE 1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical

More information

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA.

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA. DECLARATIONS Character Set, Keywords, Identifiers, Constants, Variables Character Set C uses the uppercase letters A to Z. C uses the lowercase letters a to z. C uses digits 0 to 9. C uses certain Special

More information

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual Contents 1 Introduction...2 2 Lexical Conventions...2 3 Types...3 4 Syntax...3 5 Expressions...4 6 Declarations...8 7 Statements...9

More information

Number Systems CHAPTER Positional Number Systems

Number Systems CHAPTER Positional Number Systems CHAPTER 2 Number Systems Inside computers, information is encoded as patterns of bits because it is easy to construct electronic circuits that exhibit the two alternative states, 0 and 1. The meaning of

More information

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed C Overview C OVERVIEW Goals speed portability allow access to features of the architecture speed C fast executables allows high-level structure without losing access to machine features many popular languages

More information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

Variables, Constants, and Data Types

Variables, Constants, and Data Types Variables, Constants, and Data Types Strings and Escape Characters Primitive Data Types Variables, Initialization, and Assignment Constants Reading for this lecture: Dawson, Chapter 2 http://introcs.cs.princeton.edu/python/12types

More information

Arithmetic Expressions in C

Arithmetic Expressions in C Arithmetic Expressions in C Arithmetic Expressions consist of numeric literals, arithmetic operators, and numeric variables. They simplify to a single value, when evaluated. Here is an example of an arithmetic

More information

PYTHON. Values and Variables

PYTHON. Values and Variables December 13 2017 Naveen Sagayaselvaraj PYTHON Values and Variables Overview Integer Values Variables and Assignment Identifiers Floating-point Types User Input The eval Function Controlling the print Function

More information

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators Operators Overview Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators Operands and Operators Mathematical or logical relationships

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Lecture 3 Tao Wang 1

Lecture 3 Tao Wang 1 Lecture 3 Tao Wang 1 Objectives In this chapter, you will learn about: Arithmetic operations Variables and declaration statements Program input using the cin object Common programming errors C++ for Engineers

More information

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming 1 Literal Constants Definition A literal or a literal constant is a value, such as a number, character or string, which may be assigned to a variable or a constant. It may also be used directly as a function

More information

A variable is a name for a location in memory A variable must be declared

A variable is a name for a location in memory A variable must be declared Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;

More information

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

More information

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University Lecture 07: Data Input and Output Readings: Chapter 4 Input /Output Operations A program needs

More information

Lecture 2 Tao Wang 1

Lecture 2 Tao Wang 1 Lecture 2 Tao Wang 1 Objectives In this chapter, you will learn about: Modular programs Programming style Data types Arithmetic operations Variables and declaration statements Common programming errors

More information

Programming Lecture 3

Programming Lecture 3 Programming Lecture 3 Expressions (Chapter 3) Primitive types Aside: Context Free Grammars Constants, variables Identifiers Variable declarations Arithmetic expressions Operator precedence Assignment statements

More information