Identifiers And Literals

M3-R5.1 · Chapter 3: Introduction to Python · 9 min read

2. Identifiers

  • In a python program we have to use names to identify variable or to identify classes, methods/functions or modules , that names itself called as “Identifiers” which can be used for Identification.

  • They are essentially user-defined names and must follow certain rules to be valid.

Rules for identifiers:

  • It cannot start with a digit.
  • It consists of letters and digits in any order except that the first character must be a letter.
  • _ (underscore) can be used in identifier and underscore (_) counts as a character.
  • Spaces are not allowed. ·
  • Special Characters are not allowed. Such as @, #, $, %, + etc. in identifier
  • An identifier must not be a keyword of Python.
  • Variable names should be meaningful which easily depicts the logic
  • Commas or blank spaces are not allowed within an identifier

Testing the Validity of Python Identifiers:  The .isidentifier() function is used to check the validity of an identifier but, this method doesn’t take reserved keywords into consideration. So, we can use this function with keyword.iskeyword() to check if the name is valid or not.

  • print ("jai".isidentifier())                      Output:   True
  • print ("123jai".isidentifier())              Output:   False
  • print ("_jai".isidentifier())                     Output:   True
  • print ("for".isidentifier()  )                   Output:   True    # because for is keyword

3. Literals

  • Literals are the fixed values that are assigned to variables or constants.
  • These values are directly represented in the code and are of specific data types.

Type of Literal :

1. Numeric literals:

Numeric Literals are immutable. Numeric literals can belong to following four different numerical types.

  • Int (Signed Integers): Numbers ( can be both positive and negative) with no fractional part(decimal point). Ex: 100
  • Long (Long Integers): Integers of unlimited size followed by lowercase or uppercase L

Ex.: 87032845L

Note : - In Python 3, there is only the int data type for integers. The types long, short, signed, and unsigned were used in Python 2, but they are no longer supported in Python 3.

Float (Floating Point):  Also called floats, they represent real numbers and are written with a decimal point dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).

Complex(complex): A complex literal in Python represents a complex number, which consists of a real part and an imaginary part.

Syntax :   complex_number = real_part + imaginary_partj

  • The real part is a float or integer.
  • The imaginary part is followed by j or J (Python uses j instead of i like in mathematics).

Examples:

c1 = 3 + 4j    # Complex number with real=3, imaginary=4

c2 = -5.2 - 2j # Complex number with real=-5.2, imaginary=-2

c3 = 0 + 1j    # Purely imaginary number

Program :

a = 2 + 3j

b = 1 - 4j

print(a + b)        # Output (3 - 1j)      Explanation :  (2+3j)+(1−4j)=(2+1)+(3−4) j       => 3−1j

print(a - b)        # Output (1 + 7j)      Explanation :   (2+3j)−(1−4j)=(2−1)+(3+4)j       => 1+7j

2.String Literals: 

String literals in Python represent sequences of characters enclosed in quotes. String literals are formed by enclosing text in the single or double or both a single and double (Triple) quote.

Example: String literals are a sequence of characters surrounded by quotes: single, double or triple.

                 Eg.: ‘John’, “Tom”, ‘Class 12’, “200453A”, ‘12345’

Single-line string: String created by enclosing text in single quotes, double quotes are normally single-line string, i.e., they must be terminated in one line.

Example: a=’John’

Example: text1= ’helloThere’

Multi-line string:  In multi-line string, text is spread across multiple lines as one single string. It can be created in 2 ways:

  1. By adding a backslash at the end of normal single quote or double quote string. In normal strings, just add a backslash before pressing ‘enter’ to continue.

             Example:  a=”nielit\

                                O LEVEL”  # do not indent when continuing typing in next line after’\’

  1. By typing the text in triple quotation marks.

              Example.  a=”””nielit

                              OLEVEL”””

                  b=’’’nielit

                             CCC’’’

# Single-line string

str1 = "John"

print(str1)

           # Multi-line string

str2 = """ This,

 is it!

"""

print(str2)

Size of String: Python determines the size of a string as the count of characters in the string.  e.g. size of  string “abc” is 3 and ‘hello’ is 5.

But, if our string literals have an escape sequence contained within it, then make sure to count the escape sequence as one character.

“abc”

Size is 3

 ‘\\’

Size is 1

\\ is escape sequence to represent backlash

“\ab”

Size is 2

\a is escape sequence, thus one character

“jai\’s pen

Size is 9

For typing apostrophe (‘) sign, escape sequence \’ has been used

“Amy’s”

Size is 4

Python allows a single quote (without escape sequence) in double-quoted string and vice-versa

For multi-line string with triple quote, while calculating the size, the EOL (End Of Line), the character at the end is also counted.

a=””” X    # enter keys are considered as EOL(End of Line) characters and counted in the length of multiline

 y

 z ”””      

Then size of string a is 5 (three characters x,y,z and two EOL character that follow character respectively But backslashes (\) at the end of intermediate lines are not counted in the size of the multiline strings.

 a=”c\

      d\

      e”

for multiline strings created with single/double quotes and backslash character at end of the line, while calculating size , the backslashes are not counted in the size of the string: also we cannot put EOLs using return key in single/double quoted multiline strings. so the size of string str is 3 (only three character no backslash counted)

Boolean Literals: Used to represent one of the two Boolean values, that is True and False .True is for 1   and False for 0.

For example:

>>>jai=(6>10)

>>>print (jai)

Output: False

4. Special Literals (None) :

The special literal  in Python represents the absence of a value or a null value. It is used to indicate that a variable exists but doesn't hold any meaningful data. It is commonly used in function definitions, default arguments, and as a placeholder when a value hasn't been assigned yet.

   5. Collection Literals :

Python provides four different types of literal collections:

  • List literals: [1, 2, 3]
  • Tuple literals: (1, 2, 3)
  • Dictionary literals: {“key”: “value”}
  • Set literals: {1, 2, 3}

Note - We will study collection literals in Chapter - 5( Sequence data types) in detail.



Constants

Python does not have built-in support for constants (like const or final in other languages). Instead, constants are defined by convention:
Variable names are written in UPPERCASE to indicate they should not be modified. Example:

>>> PI = 3.14159            # Ratio of circle circumference to diameter
>>> E = 2.71828             # Euler's number (base of natural logarithm)
>>> PHI = 1.61803           # Golden ratio
>>> SPEED_OF_LIGHT = 3e8    # Speed of light in vacuum (m/s)
>>> PLANCK_CONSTANT = 6.626e-34  # Planck's constant (J·s)
>>> AVOGADRO = 6.022e23     # Avogadro's number (particles per mole)
>>> BOLTZMANN = 1.38e-23    # Boltzmann constant (J/K)

It is up to the programmer to respect the constant nature of these variables.