GE Chapter1
GE Chapter1
PYTHON PROGRAMMING:
           1                            AN INTRODUCTIOON
CHAPTER OUTLINE
                             >>> 27/5
                             5.
                             »         27 /1 5
                             5
                            >> 27.0 // 5
                             S.0
                             27 5
Lne15 Cok4
                           The exponentiation operator (**) yields raise to the power operation, i.e.
                           a. For example, 32 is expressed as 3                                    2 , and yields the value 9.
           Programming:
                                      An lIntmduction                                                                                      3
Athon
>> 3 ** 2
    9
    >6                   3            2
      1.0
      >>        2   **       3    **       2
laddition) (subtraction)
 An eTor occurs when the input expression is not corectly formed. For                                                Python complains
                                                                                                                     when it encounters
 Xample, the exp
             expression 7                             3(4     +       5) generates an error because the              a wrongly formed
Perator between 3 and
                                           (    is missing                                                           expression
      > 7+          3(4   5)
                eback (most recent call last)
            ile
           * l e " P y s h e l 1 # 17>",                      1ine             1,    in    <module>
                                                                                                    Python Programming
                                         7      3(4         5)
                                   TypeError:         'int'      object is not calllable
                      r"action" plan?'
single,     double,    or  in single quotes may include double quote marks and vice versa. A string
triple quotes
                           enclosed in triple quotes (also known as docstring, i.e. documentation
                           string) may include both single and double quote marks and may extendd
                           over several lines, for example:
                                   "Hello\nWhat's\nhappening"
                                   >>> print ("" "Hello
                                   What'ss
                                   happening" " ")
                                   Hello
                                   What's
                                   happening
                           Note that enclosing quote marks are used
                                                                    only to specify a string, and  they
                           do not form part of the
 escape sequence \n
 marks a new line
                                                    string. When we  print a string using the   print
                           instruction, the value of the string, i.e. the sequence of characters within
                           quotes is printed. Also,     note     that, within   a   string,   \n denotes the
                          of   a     line. When a string having \n is
                                   new
                                                                                                               beginning
                                                                       printed, everything after \n
                          (excluding \n) is printed on the next line. In this section, we shall study
                          basic operations on strings. Let us
                                                                      begin
                                                                with the                   concatenation operator (+),
                         An
          m Programming: An                  Intvduction
                                                                                                                                           5
             used
                 sed to produce a string by concatenating two strings; for example,
                  to r
          is
     which
    theCxpression ' h e l ]                           +         !!' yiclds the string 'hello                !!'
                          expression             'how'         +'are' + ' you?'
                                                                                        yields
                 the
             ou?' (=('how' +
    Similarly,                                                                                             'how      use of+ as the con
                                                               are') +       you') as shown                          catenation operator
    are    you
                                                                                                         below:
          >>>
                  'hello
                                 '
                                         +       '!!
          h e l l o ! !
                                     are'                 +         you?'
       >>>       'howt
          how are             you?'
    The o p e r a t o r   *
                               (multiplication) is used to repeat a string a specified                               use of operatorfor
 mber oftimes; for example, the expression 'hello'                                              5      yields the    repeating    string
                                                                                                                     several times
 cring 'hellohellohellohellohello':
>>>'hello' * 5
hellohellohellohellohello
                                                 (equal to)
                                                 (less than)                                                         relational  opera
                                                 (greater than)                                                      tors for comparing
                                                                                                                     expression values
                                                 (less than or equal to)
                                                 (greater than or equal to)
                              |!=(notequal to)
A                  operator applied on expressions takes the following form:
                                                 tor> expression
       Lession                 <comparison opera
       are used
                  for      codes of                                         'h
                                                                            Thus,
acters
                                  122. and |48,
                                                571. respectively.      than ASCIH
                                                                                       value of 'H' (=
string comparison          197.                         l04) is greater
                                      value of ' h ' =                   T r u e since
                                                                                        ' h ' is greater
                           as ASCIl                                        yields
                                           'hello'>
                                                             'Hello'
                                                                                    yields True because
                                                                                                                  the first
                           72).Also.                     'hi'
                                                                  >'hello'
                                   'H'.    Similarly,                                          code of
                                                                                                         '
                                                                                                             i ' is greater
                                                          is identical and ASCII
                           than
                                            two strings                                                                the
Python 3 does
              not          character in the
                                                                   string is a prefix           of another string,
                                                ' e ' . Also, if a
alow     string   values   thanASCll code of
               with                          will be
                                                       considered      large.
to be compared             longer string
numeric values
not
                                                                         False
                                                  True
                                                                         True
                                                 False
                                                                         True                   False
                                                  True
                                                                         False                  False
                                                 False
or True False
                                                                 and        Decreasing
                                                                                 order
                                                                 or
 Phthon Programming:
                               An Intduction
  sub-expressIOn
                 is evaluated only if the first sub-expression yields True.
     example, in the expression (10        5) and ((5/ 0)<10)),                                    short-circuit evalu
 For            first sub-expression        (10         <     5)                                   ation of a boolean
   c*     the                                                        yields False, and thus
                                                                                                   expression
 rmines the value of the entire expression as False, Python does not
 ate the second sub-expression. This is called short-circuit evaluation
 holean expression, However, the expression (10> 5) and ((5
of1 0 ) yields an error since the first sub-expression yields True,
 dPvthon attemptsto evaluate the second sub-expression ( (5                               0)<
 0 that yields an error because division by zero is an illegal operation:
     >>>     (10          5)    and    ( ( 5 / 0)           <10)
     False
     >       (10> 5)            and ( (5           0)       < 10)
   1.e. ( (not       False) and ((7 1 ) != 8)) o r (6< 4.5)                                       using     precedence
                                                                                                  rules
   1.e.(True         and (7+1) != 8)) o r (6 < 4.5)
   .e, (True         and        (8!=    8))       or    (6    <    4.5)
                     Arithmetic operators
                                                             Decreasing
                         Relational operators                     order
                     Logical operators
                                                                                                       Python Programming
2: 00000010
+X X, ~x
and
or
 When the     above statement is executed,      Python associates   the variable    assignment    state
 english with value 57. We can also say that the the variable english               ment
 5signed the value 57, or that the variable english refers to value 57.
 uch a
       statement that assigns value to a variable is called an assignment
 aiement. In Fig. 1.2, we see that the variable english refers to the value
     A figure such as Fig. 1.2 is known as reference diagram or state
 r a m as it shows the
                        current state of the variable.
english
                                                                                    variable    english
                                                                                    refers to value 57
                                         57
                                         >   english
                                    57
Commerce = 62
                            Assignment         Statement
                              As discussed above, values are assigned to variables using an assignment
                              statement. The syntax for assignment statement is as follows:
syntax for assign-                variable           =       expressi on
ment statement
                             where expression may yield a value such as numeric, string, or Boolean. In
rules for naming vari                A variable must           begin    with   a    letter or(underscore character)
ables                                A variable may contain any                    number of letters, digits, or underscOe
                                     characters. No other character apart from these is allowed.
TotalMarks
totalMarks
TOTAL_MARKS
However, one must be consistent in following a style. In this book, we prefer     follow a consistent
to use the lowerCamelCase style in which the first letter of every word is        style in choosing
capitalized, except the first word which begins with a lowercase letter, for      variables
       >>age             =       24
                                                                                  Python is case-sen-
                                                                                  sitive.
       >Age                                                                       age and Age are dif
                                                                                  ferent names
       Traceback (most recent call last)
         File "<pyshell#1>", 1ine 1, in <module>
                Age
       NameError:                 name     'Age'     is not defined
       >>        a   =       5
                                                                                  more than one vari-
       >         b = a                                                            able may refer to the
       >>        a   =                                                            same object
Shorthand
  By
          Notation
   fW, we have seen several examples of assignment statements. The
               g assignment statement updates value of the variable a by adding
   to the existing value.
           a         = a+ 5
 12
                                                                                                                                  Python Programminy
                                                                                                          b
5 5 7 5
                                   >>> a          a a                        (b+c)
                        can be written as follows, respectively:
                                >>>      a        += b                 +     c
                               >>>       a        **= b                    +c
is equivalent to
a <opera tor>= b
                              >>>day = 'Mon'
                              >>>        time              =           '9'
                                                                                                        'Meeting', Mon', 9
                        Thus,      we can
                                                       specify               more              variables than  the left side ot an
                                                                                                                    one on
                        assignment statement, and the
                        expr1>, <expr2>,                                                 corresponding number of expressions, like
                        the
                              syntax for
                                                                                   .
                                                                                       ..,   <exprk>, on the right side. Formally.
                                                  an
                                                           assignment                  statement may be described as follows:
                              namel>, Kname2>,                                             .
                                                                                               ..,        <nameK>     =
                                                                                                                              <exprl>, <expr
                                    exprk>
         Progrnamming:
                                 An Intmduction
n.chon
                                                                                                                                13
                   be used to enhance the
   notation
This
                   can
                                           readability of the program. We
     also assign a comm      value to multiple variables, for example, the
may
assignment s t a t e m e n t
      >totalMarks                           =       Count      =    0
                                                                                                            assigning       same
                                                                                                            value to multiple
                                                                                                            variables in a single
may he used to replace the following two assignments:                                                       statement
    >>>tota lMarks = 0
            Count            =    0
S upposo we wish to Swap values of two variables, say, num1 and num2.
For this purpose, we use a variable temp as follows:
>>numl = num2
1.7 KEYWORDS
 Keywords      are   the reserved words that                        are   already defined by
                                                                         the Python
 Tor specific uses.                                                                                         keywords have spe
                             They cannot be used for any other purpose. Hence, make                         cial meaning
 Sure that none of the names used in a program should match any of the
  Keywords. The list of the keywords in Python 3.6 is given in Fig. 1.4.
                                                                                                    Chapret 1
                               File   Edit       Format    Run    Options   Window   Help
                               numberl              input ()
a simple script                number2= input ()
                               print (number1,             number2)
                                                                                                                                             Ln: 5 Cot0
                                   on win32
                                                                                                           more   information.
                                                                                  "license    ()"    for
                                                                 "credits"   or
                               TYpe "copyright",
output on executing                                 =RESTART:         F:/Python      Programs/Chapter-1/readNshow.py
the script S
3 6
Lne 13 Cob 4
                                                              Python 3.6.1Shell
  File Edit      Shell    Debug      options     Window       Help
 Python 3.6.1             (v3.6.1:69codb5,                 Mar 21 2017,       17:54:52)     [MSC v.1900 32 bit   (Intel)
 on win32
  pe "copyright",                   "credita"         or    "1icense ()   *
                                                                              tor   more   information.
Ln:8 Cok4
SUMMARY
       .Python interpreter executes one expression (command) at a time.
      .         An expression is a valid combination of operators and operands. Operands are the objects
        on which
                 operators are applied.
      .Arithmetic, relational, logical, and bitwise operators are used for performing computations
                in a program.
                A String is a sequence of characters. To specity a string, we may use single, double. or
                triple quotes.
      h e operator + (addition) applied on two string operands is used for concatenating them.
                the             (multiplication) is used to repeat a string a specitic number of
       milarly,     operator*
                times.
                                                    strings, strings                                                 are   compared   lett   to   right
    When relational operators are applied ASCIl
                                                                                            on
                                           their        values
      aracter by character according to
    .
                       a Boolean expression
                                              involving and operator, the second sub-expression
      nile  evaluating
      s evaluated only if the first sub-expression yields True.
                                                                                                                                          is
       8.                                                                                             operator, the second sub-expression
             e evaluating an expression involving
                                                                                                 or
                                                            False.
          auated only if the first sub-expression yields
       9.
          Precedence order for the operators is as follows:
16                                                                                                          Python Programming
+Xr
                                                                                       Decreasing
                                                                                             order
not
and
or
                                                                                         variable associates a
     10. A variable is           a name   that refers to a value. We may also say that a
                                                                                or Boolean.
            name      with   a   data object such as number, character, string,
                                                                       statement. The syntax for assignment
     11. Values        are   assigned   to variables using assignment
            statement is as follows:
                      variable          = e x p r e s s i on
            allowed.
                                                  Thus,    age and   Age      are   different variables.
     14.    Python is        case-sensitive.
                      a   <operator>= b
                                                                                     line as follows:
      T6.   In   Python, multiple assignment statements can be specified in a single
                      name1>, <name2>, . . .         Kexpressi on1>, <expression2>,
      T7. A keyword is a reserved word that is already defined by Python for a speciie Usc
            Keywords cannot be used for any other purpose. The list of the Python keywords is giv en
below:
                                                                                                                                             except
                                     raise                          elif
  s Python
    Python programming
           programm    can be done in an interactive and script mode.
  18.
ExERCISESs
         (a)   x   =
                       0, y          =
                                             6,   z           =10
         b)    x=      1,    y       =
                                             1,       z       =1
   Evaluate the following expressions involving arithmetic operators:
        (a) -7 * 20 +                                     8 / 16 * 2 +                            54
        b) 7           **        2           //           9         3
(c) 7 - 4 *2) * 10 5 ** 2 + 15
(d) 5 10 + 10 25 * 8// 5
         (e)       hello'                         2                      5
   3. Evaluate the following expressions involving relational and logical operators:
      (a) 'hi' > hello'         and 'bye' <'Bye"
      (b) 'hi' > 'hello' or 'bye' < 'Bye'
         c) 7> 8 or 5 < 6 and                                                           ' I am fine'> 'I am not fine'
         (d) 10 != 9 and 29 >= 29
         e) 10          != 9 and 29>= 29 and 'hi'                                                                          >       'hello'      or    'bye'   <   'Bye'   and
                   7 <= 2.5
   4. Evaluate the following expressions involving arithmetic, relational, and logical operators:
         (a) 5 8 10                                   10<               50 and 29                                  29
         (b) 7 *                 2           <= 5              //       9       8       3    or        'bye'                   <    'Bye'
         (a) 15& 22
         (b) 15 22
          c-15 & 22
          (d) -15 I 22
          (e)15
           ()22
           g)-20
          (h) 15                         22
                                                                                                             Python Programmin
18
                 8             3
           (i)        <<
                 40       >>       3
          ()
           Differentiate between the                      following operators   with the   help   of   examples:
     6.
          (a) and=            ==
          (b)and
          (c)and//
                              **
          (d)    *
                     and
     7. What output will be displayed when the following commands are executed in Pytha
          shell in sequence:
          (a)>> a = 6
                 >>>      a        ==          6
                 >>b /                     6
                 >>> b             //          6
                 >>> b /4
                 >>> b             % 4
                 >>>b   7
                 >>> b *2
                 >>>      b        **          2