Download as pdf
Download as pdf
You are on page 1of 7
CHAPTER qe : 1 PYTHON PROGRAMMING: ~ AN INTRODUCTION CHAPTER OUTLINE @ 1.1 IDLE —An Interpreter for Python @ 1.5 Bitwise Operators @ 1.2 Python Strings @ 1.6 Variables and Assignment Statements @ 1.3 Relational Operators @ 1.7 Keywords @ 1.4 Logical Operators @ 1.8 Script Mode thon is an interactive programming language. Simple syntax of the fe age makes Python programs easy to read and write,) Python was sloped by Guido Van Rossum in 1991 at the National Research Institute Mathematics and Computer Science in the Netherlands. Guido Van um named Python by getting inspired from his favourite comedy show Python’s Flying Circus. Eyer since the language was developed, it is becoming popular day day amongst the programmers. Various versions of Python have been eased til] date ranging from version 1.0. This book uses Python 3.6, Python sed in various application areas such as the web, gaming, scientific and ic computing, text processing, and network programming. Toye lao Aa DLE stands for Integrated Development and Learning Environment, thon IDLE comprises Python shell and Python Editor. While Python is an interactive interpreter, Python Editor allows us to work in’script . While using Python shell, we just need to type Python code at the >> prompt and press the enter key, and the shell will respond with the ult of the computation. For example, when we type >>> print ("hello world') press enter key, Python shell will display: ‘operators: Tn Thy %y and ** Python shell window “5 on which the operator + is applied, are c+ hello world calculator, for example, when we hell may also be used as a a = followed by enter, Python shell outputs the value of th expression, i. 23, as shown below: >>> 18 + 5 23 18 + 5,+ iscalled the operator, The numbers, 18 a alled the operands. In general, an ‘on is a valid combination of operators and operands. In Python, a forms of data are called values or objects. For example, 18, 5, and 23 a objects, The expression 18 + 5 yields the value 23. Similarly, the expres 18 — 5 yields the value 13. The expression 18 * 5 yields 90, as P uses * asthe symbol for the multiplication operation. The expression 27 / yields 5. 4. Note that the result of division 27 / 5 is real number. In Pytl result of division is always a real number. However, if you wish to ob an integer result (for example, floor(5.4)), Python operator // (two slashes without any intervening blank) can be used. For example, 27 // 5 yields 5. However, while using the operator //, if at least, one of the two operands is a real number; the result is a real number, for example, the exp In the expression in Computer Science terminology in view of the floating point representa used to represent real numbers. However, the number representation is the subject matter of this book. Python operator % (percentage sign), ki as modulus, yields the remainder of the division, for example, 27 % 5 yi 2 because on dividing 27 by 5 we get 2 as the remainder. In Fig. 1.1, v illustrate these examples in Python shell. fe rE file _Edit_Shell Debug Options Window |Help Type "copyright", “credite® or * 2 ; >> e+ 8 ‘cenee()* for more information. 23 7; >> ee 5 Or 90 tA =1 yields 0.5 as expected. The s mentioned above involved onl tin practice, we would require more complex expressions, Note that yhereas the expression 6 / 3 / 2yields1.0(= (6 / eee ety le expression 2 ** 3 ** 2yields 512 (= 2 ** (3 ** 2)) . This So because whereas the operator / (as also +, ~, *, //, 4) is evaluated fi to right, the exponentiation operator is evaluated right to left, We say at the operators, +, =, *, /, //, andi, are left associative operators and operator ** i ociative. Python operator ~ (negation) yields jegative of the operand. For example, 10 * -5 multiplies 10 and -5 egative of 5), yielding ~50 as a result. Next, we evaluate the foregoing pressions in Python shell expressions in each of ly single mathematical operator, 1.0 S>> 2 **°3 ee 2 512 >>> 10 * -5 -50 hhen we enter the expression 7 + 4 * 3, the system responds with lue 19 asa result. Note that in the expression 7 + 4 * 3, Python valuates the operator * before + asf the input expression was 7 + (4 * ) because the operator * has higher precedence than +. In Table 1.1, we list the operators in decreasing order of their precedence. The expressions ithin parentheses are evaluated first; for example, given the expression (7 + 3) * 10 / 5, the system would yield 20 . 0. Parentheses are ten used to improve the readability of an expression. Table 1.1 () (parentheses) Precedence of arithmetic operators (exponentiation) i decreasing f easton) = order J (division) // (integer division) * (multiplication) % (modulus) + (addition) - (subtraction) ‘n error Occurs when the input expression is not correctly formed. For ample, the expression 7 + 3(4 + 5) generates an error because the perator between 3 and ( is missing: >>>M+ 3:(aegaeD Traceback (most recent call last): File "", line 1, in 3 left associative oper- ators:+, -, =, /, Wy % = operator works as negation operator ses have the highest Python Programminy 4 division by zero is a meaningless operation a Python string may be enclosed within single, double, or triple quotes 7: Wet 05): nypeBurones Wnthloblechihennes callable Similarly, the expression 7 / (yields a zero division error since division imilarly, by zero is a meaningless operation. >>> 7/0 traceback (most recent call last): File "", line 1, in V4, 0) zeroDivisionError: division by zero 1.2 PYTHON STRINGS A string is a sequence of characters. To specify a string, we may enclose a sequence of characters between single, double, or.triple quotes. Thi "Hello world’, ' "Ajay " (0, “what's alamo "action" plan?''' are the examples of strings. A string enclosed in single quotes may include double quote marks and vice versa. A stri enclosed in triple quotes (also known as docstring, ic. documen string) may include both single and double quote marks and may ext over several lines, for example: >>> 'Hello World' "Hello World! >>> print ('Hello World') Hello World >>> """Hello What's happening""™ "He11o\nlthat's\nhappening” >>> print("""Hello What's happening""™") Hello What's happening i) ea aL& 4 Fa Python Programming: An Introduction 5 which is used to produce a string by concatenating two strings; for example, the expression "hello ' + '!1" yields the string ‘hello !!'. imilarly, the expression ‘how’ + ' are’ + ' you?! yields how (ugelofasitheléon: are you?' (=('how’ + ' are') + ' you') as shown below: catenation operator >>> ‘hello | + ‘iy ‘hello !!' >>> "how' + ' are’ + ' you?! ‘how are you?! 1 operator * (multiplication) is used to repeat a string a specified use of » operator for umber of times; for example, the expression ‘hello’ * 5 yields the ‘peating a string ing "hellohellohellohellohello': sere oes) >>> "hello' * 5 "hellohellohellohellohello' 1.3 RELATIONAL OPERATORS Relational operators are used for comparing two expressions and yield True or False. In an expression involving both arithmetic and relational operators, the arithmetic operators have higher precedence than the relational operators. In Table 1.2, we give a list of relational operators Table 1.2 Relational operators (equal to) < (less than) > (@reaterthan) tors for comparing < = (less than or equal to) ! = (not equal to) relational operator applied on expressions takes the following form: expression expression hus, the expressions, 23 < 25, 23 != Beguand.2s.— 2.9 >= * 4, yield True, False, and True, respectively. As arithmetic s have higher precedence than the relational operators, the 23 - 2.5 >= 5 * 4 is evaluated as if it were (23 - ( 4). When the relational operators are applied to Python 3 does not allow string values to be compared with numeric values combining expres sions using logical ‘operators logical operators not, yield val- Python Programmin called ASCII values. For example, ASCII 9° lie in the range [65, 90], ‘on their ASCII codes, also Set te a RISE ‘i+ Ce 104) is greater than ASCII value of *H' (= as ASCII va 72). Also, thello' > ‘Hel Lo" yields True since "h' is greater than 'H'. Similarly, hd > "hello! yields True because the first scter in the two strings is identical and ASCII code of "i is greater ‘Also, if a string is a prefix of another string, the than ASCH code of 'e Jonger string will be considered larger. 1.4 LOGICAL OPERATORS The logical operators not, and, and or are applied to logical operands prue and False, also called Boolean values, and yield either True or False. The operator not is a unary operator, i.e. it requires only one operand. The expressions not True andnot False yield False and True, respectively. An expression involving two Boolean operands and the and operator yields True if both the operands are True, and False otherwise. Similarly, an expression involving two Boolean operands and: the or operator yields True if at least one operand is True, and False otherwise. This is shown in Table 1.3. Table 1.3 not, and, and or operators not True False False ey aoe True False True aes False False Beles False ce True False gaue True True False True False Precedence of logical operators is shown in Table 1.4. Table 1.4 Precedence of logical operators hon Programming: An Introduction ile evaluating an expression involving an and operator, the second sub-expression is evaluated only if the first sub-expression yields True jr example, in the expression (10 < 5) and ((5 / 0) < 10), ince the first sub-expression (10 < 5) yields False, and thus short-circuit evalu- ation of @ boolean ‘expression ate the second sub-expression. This is called short-circuit evaluation e on. However, the expression (10 > 5) and ((5 0) = 10) yields an error since the first sub-expression yields True, \d Python attempts to evaluate the second sub-expression ((5 / 0) < yields an error because division by zero is an illegal operation: 10 < 5) and ((5 / 0) < 10) > (10 > 5) and ((5 / 0) < 10) Traceback (most recent call last): File "", line 1 (10 > 5) and ((5 / 0) < 10) zeroDivisionError: division by zero Similarly, while evaluating an expression involving an ox operator, the second sub-expression is evaluated only if the first sub-expression yields ‘alse. Thus, whereas the expression (10 > 5) or ((5 / 0) < H0) yields True, the expression (10 < 5) or ((5 / 0) < 10) byields an error. To evaluate an expression comprising arithmetic, relational, and gypressionsiaveling logical operators, the operators are applied according to precedence order arthmetio, elaional, or the operators given in Table 1.5. For example, the expression not 9 andlogical operators t= 8 or 6 < 4.5 isevaluated as if it were the ((not (9 == 8)) and ((7 + 1) 8)) or (6 < 4.5) — laepression’ evaluation iss) cal U7 4 1) 2B) Re I< Sa) fpreosdence ie. (True and ((7 + 1) $= 8)) ox (6 < 4.5) les ie. (True and (8 != 8)) ox (6 < 4.5) ie. (True and False) or (6 < 4-5) ie. False or (6 < 4-5) ie. False or False ie. False = 8 and 7 +1 following equivalent parenthesized expression: Table 1.5 Precedence of operators

You might also like