Lesson - 5      Python -Variables and Operators
Write notes on Python.
   Python is a general purpose programming language
   It was developed by Guido Van Rossum from CWI (Centrum Wiskunde & Informatica) which is a
      National Research Institute for Mathematics and Computer Science in Netherlands in 1991.
   It is named after “Monty Python’s Flying Circus” a BBC comedy series from seventies.
   It supports both Procedural and Object Oriented programming approaches.
Key Features:
    It is a general purpose programming language which can be used for scientific and
     non-scientific programming.
    It is platform independent
    The programs written in Python are easily readable and understandable.
                                               Part - II
Answer the following questions: (2 Marks)
1. What are the different modes that can be used to test Python Program?
  In Python, programs can be written in two ways, they are:
   Interactive mode:
   Script mode:
   Interactive mode:
    Interactive mode allows us to write codes in Python command prompt (>>>).
    We can write code directly and the interpreter displays the result immediately.
    To open interactive mode:
     Start → All Programs → Python 3.x → IDLE (Python 3.x)
   Script mode:
    In script mode programs can be written and stored as separate file with the extension .py and
    executed. Script mode is used to create and edit python source file.
    To open script mode:
    File → New File or press Ctrl + N in Python shell window
2. Write short notes on Tokens.
  Python breaks each logical line into a sequence of elementary lexical components known as
  Tokens. The tokens are classified into five types; they are:
  1) Identifiers
  2) Keywords
  3) Operators
  4) Delimiters and
  5) Literals
3. What are the different operators that can be used in Python?
  Operators:
  Operators are special symbols which represent computations, conditional matching etc. Value
  and variable when used with operator are known as operands.
  Operators are classified as:
              Arithmetic
              Relational
              Logical
              Assignment
              Conditional
4. What is a literal? Explain the types of literals?
  Literals:
    Literal is a raw data given to a variable or constant.
    There are three types of literals, they are:
         Numeric
         String
         Boolean.
5. Write short notes on Exponent data?
  An Exponent data contains decimal digit part, decimal point, exponent part followed by one or
  more digits. EX: 1.5e2
                                      Part - III
Answer the following questions: (3 Marks)
1. Write short notes on Arithmetic operator with examples.
An arithmetic operator is a mathematical operator that takes two operands and performs a
calculation on them. They are used for simple arithmetic. (Assume a=5, b = 2)
      OPERATOR                   OPERATION                EXAMPLE              RESULT
                +            Addition                       a+b                   7
                 -           Subtraction                     a-b                  3
                 *           Multiplication                 a*b                  10
                 /           Division                        a/b                 2.5
                %            Modulus Division               a%b                   1
                **           Exponent                       a ** b               25
                //           Floor Division                 a // b                2
2. What are the assignment operators that can be used in Python?
  In Python, = is a simple assignment operator to assign values to variable. (Assume x=10)
   OPERATOR                                   DESCRIPTION                                EXAMPLE
           =          Assign right side operands to left side variable.                       x=10
                                                                                        x=”computer”
        +=            Added and assign back the result to left operand.                       x+=2
                                                                                          (i.e) x=x+2
           -=         Subtracted and assign back the result to left operand.                  x-=2
                                                                                          (i.e) x=x-2
           *=         Multiplied and assign back the result to left operand.                  x*=2
                                                                                          (i.e) x=x*2
         /=         Divided and assign back the result to left operand.                         x/=2
                                                                                            (i.e) x=x/2
        %=          Take modulus (remainder) and assign back the result to left                x%=3
                    operand.                                                               (i.e) x=x%3
        **=          Perform exponential calculation and assign back the result to left        x**=3
                    operand.                                                               (i.e) x=x**3
         //=        Perform floor division and assign back the result to left operand.          x//=3
                                                                                            (i.e) x=x//3
3. Explain Ternary operator with examples.
   Ternary operator is also known as conditional operator that evaluates something based on a
   condition being true or false. It simply tests the condition in a single line replacing the multiline if-
   else making the code compact.
    Syntax:     Variable Name = [on_true] if [Test expression] else [on_false]
   EX: min = 50 if 49<50 else 70 (i.e) min=50
4. Write short notes on Escape sequences with examples.
   In Python strings, the backslash "\" is a special character, also called the "escape” character.
   It is used in representing certain white space characters: "\t" is a tab, "\n" is a newline, and
   "\r" is a carriage return. It is preceded with a backslash (\) followed by any character.
    ESCAPE SEQUENCE CHARACTER                                   EXAMPLE                    RESULT
                       \\                                       print(“\\test”)               \test
                       \’                                     print(“Doesn\’t”)             Doesn’t
                       \”                                      print(“\”test\””)             “test”
                                                                                               test
                       \n                                 print(“test”, “\n”, “run”)
                                                                                               run
                       \t                                 print(“test”, “\t”, “run”)       test run
5. What are string literals? Explain.
    String Literals
    String Literals is a sequence of characters surrounded by quotes.
    Python supports single, double and triple quotes for a string.
    A character literal is a single character surrounded by single or double quotes.
    The value with triple-quote "' '" is used to give multi-line string literal.
    EX: a = ‘s’      b = ”s” c = “Hi” d = ‘Hi’           e = ’’’Hi               f = “””Hi
                                                               Jayendra’’’           Jayendra”””
                                                   Part - IV
Answer the following questions: (5 Marks)
1. Describe in detail the procedure for Script mode programming.
   Script mode programming:
  In script mode programs can be written and stored as separate file with the extension .py and executed.
  Script mode is used to create and edit python source file.
  STEP: 1 To open Python in script mode: File → New File or press Ctrl + N in Python shell window.
  STEP: 2 An untitled blank script text editor will be displayed on screen, Now it is ready to type code.
  STEP: 3 Once we entered the code and save the file using FILE  SAVE or Ctrl + S
  STEP: 4 Save As dialog box appears on the screen, Now type the file name in File Name box. Python
            files are by default saved with extension .py Thus, no need to specify the file extension.
  STEP: 5 Finally, click Save button to save your Python script.
  STEP: 6 To execute Python Script Choose Run → Run Module or Press F5
2. Explain input( ) and print( ) functions with examples.
   input( ) Function:
   input() function helps to enter data at run time by the user.
  It accepts all data as string or characters but not as numbers.
  To enter a numeric value, use int( ) function, it converts string data as integer data explicitly.
  Syntax:         Variable = input(“prompt string”)
     EX: city = input(“Enter your city:”)                    Output: Enter your city: TVL
          print(“I am from”, city)                                     I am from TVL
  print( ) Function:
  print( ) function is used to display the result of the program on the screen after execution.
  It evaluates the expression before printing it on the monitor.
  Comma ( , ) is used as a separator in print( ) function to print more than one item.
  Syntax: print( )
   EX: print(“WELCOME”)                   Output: WELCOME
  3. Discuss in detail about Tokens in Python
  Python breaks each logical line into a sequence of elementary lexical components known as
  Tokens. The tokens are classified into five types; they are:
   1) Identifiers
   2) Keywords
   3) Operators
   4) Delimiters and
   5) Literals
   Identifiers:
      Identifier is a name used to identify a variable, function, class, module or object.
      EX: sum, num1
       Valid Identifiers : sum, num1, total_marks.
       Invalid Identifiers: 12Name, name$, total-mark, continue
   Keywords:
    Keywords are special words used by Python interpreter to recognize the structure of
    program. These words have specific meaning for interpreter; they cannot be used for any
    other purpose. EX: import, break, True, False, etc.
   Operators:
    Operators are special symbols which represent computations, conditional matching etc. Value
    and variable when used with operator are known as operands.
    Operators are classified as
           Arithmetic
           Relational
           Logical
           Assignment and
           Conditional.
   Delimiters:
    Python uses the symbols and symbol combinations as delimiters in expressions, lists,
    dictionaries and strings. EX: ( ) [ ] { } , ‘ “ : ; .
 Literals:
  Literal is a raw data given to a variable or constant.
  There are three types of literals, they are:
       Numeric
       String
       Boolean.
  (i) Numeric Literals
 Numeric literals consist of digits and are immutable. Numeric literals are of three types, they are:
  Example:
  Integer
     Binary Literals               0b1010
     Decimal Literal               100
     Octal Literal                 0o36
     Hexadecimal Literal           0x1F
  Float                             a = 10.5, b = 1.5e2
  Complex                           x = 1 + 3.14 j
 (ii)String Literals
 String Literals is a sequence of characters surrounded by quotes.
 Python supports single, double and triple quotes for a string.
 A character literal is a single character surrounded by single or double quotes.
 The value with triple-quote "' '" is used to give multi-line string literal.
 EX: a = ‘s’      b = ”s” c = “Hi” d = ‘Hi’           e = ’’’Hi               f = “””Hi
                                                            Jayendra’’’           Jayendra”””
 (ii) Boolean Literals
 Boolean Literals can have any of the two values True or False.
 Example: a = True
              b = False
****************************************************************************
Other Important Qns:
1. What are the different operators that can be used in Python?
Operators are special symbols which represent computations, conditional matching etc. Value
and variable when used with operator are known as operands.
Classifications of operators:
        Arithmetic
        Relational
        Logical
        Assignment and
        Conditional.
(1)Arithmetic:
An arithmetic operator is a mathematical operator that takes two operands and performs a
calculation on them. They are used for simple arithmetic. (Assume a=5, b = 2)
    OPERATOR                 OPERATION              EXAMPLE            RESULT
           +             Addition                     a+b                 7
            -            Subtraction                   a-b                3
            *            Multiplication               a*b                10
            /            Division                      a/b               2.5
           %             Modulus Division             a%b                 1
           **            Exponent                     a ** b             25
           //            Floor Division               a // b              2
(2)Relational:
A Relational operator is also called as Comparative operator which checks the relationship
between two operands. If the relation is true, it returns True; otherwise it returns False.
(Assume a=5, b = 2)
 OPERATOR                OPERATION                 EXAMPLE             RESULT
      ==           is Equal                          a==b               False
       >           Greater than                       a>b               True
       <           Less than                          a<b               False
      >=           Greater than or Equal to          a>=b               True
      <=           Less than or Equal to             a<=b               False
      !=           Not equal to                      a!=b               True
(3)Logical:
Logical operators are used to perform logical operations on the given relational expressions.
There are three logical operators they are and, or and not. (Assume a=5, b = 2, c=3)
 OPERATOR              OPERATION                EXAMPLE                RESULT
       or          logical or                    a<b or a<c             False
      and          logical and                  a<b and a<c             False
      not          logical not                    not a<b               True
(4)Assignment:
In Python, = is a simple assignment operator to assign values to variable. Ex: a=5
There are various compound operators in Python like +=, -=, *=, /=, %=, **= and //= are also available.
(5)Conditional operator:
Ternary operator is also known as conditional operator that evaluates something based on a
condition being true or false. It simply tests the condition in a single line replacing the multiline
if-else making the code compact.
 Syntax:        Variable Name = [on_true] if [Test expression] else [on_false]
EX: min = 50 if 49<50 else 70 (i.e) min=50
****************************************************************************
2. Explain Python Data types:
 Python has Built-in or Fundamental data types such as Number, String, Boolean, tuples, lists and dictionaries.
 Number Data type: The built-in number objects in Python supports integers, floating point and complex numbers.
 Integer Data can be decimal, octal or hexadecimal.
  Example:         Datatype                  Description
  102              Decimal integers
                                             octal integer use O (both upper and lower case) to
  0O102, 0o876 Octal integers
                                             denote octal digits
  0X102, 0X876     Hexadecimal integers hexadecimal integer use 0X (both upper and lower case)
  34L              long integer              L (only upper case) to denote long integer.
 A floating point data is represented by a sequence of decimal digits that includes a decimal point. Ex:123.34
 An Exponent data contains decimal part, decimal point, exponent part followed by one or more digits. Ex: 12.E04
 Complex number is made up of two floating point values, one each for the real and imaginary parts. Ex: 1+3.14i
 String Data type: String data can be enclosed with single quote or double quote or triple quote. Ex: x=”god”
 Boolean Data type: A Boolean data can have any of the two values True or False. Ex: a=True b=False
****************************************************************************
Python comments:
In Python, comments begin with hash symbol (#). The lines that begin with # are considered as
comments and ignored by the Python interpreter. Comments may be single line or no multi-lines. The
multiline comments should be enclosed within a set of #.
# It is Single line Comment
‘’’ It is multiline comment
    which contains more than one line ‘’’
****************************************************************************
Python Indentation:
Python uses whitespace such as spaces and tabs to define program blocks to indicate blocks of
codes for class, functions or body of the loops and block of selection command. The number of
whitespaces (spaces and tabs) in the indentation is not fixed, but all statements within the block
must be indented with same amount spaces.
****************************************************************************
Rules for writing an identifier:
    An identifier must start with an alphabet (A..Z or a..z) or underscore ( _ ).
    Identifiers may contain digits (0 .. 9)
    Python identifiers are case sensitive i.e. uppercase and lowercase letters are distinct.
    Identifiers must not be a python keyword.
    Python does not allow punctuation character such as %, $, @ etc., within identifiers.
Floor division is also called as integer division, it returns the quotient of division in which the digits after
the decimal point are removed. The result of” floor division” is an integer.
   Ex:                                                    Output:
   a=5                                                    2
  b=2
  c=a//b
  print(c)