Literal is a raw data given in a variable or constant. In Python, there are various types of literals.
(I) Numeric Literals
Numeric Literals consists of digits and are immutable (unchangeable). Numeric literals can belong to 3 different numerical types Integer, Float and Complex. To demonstrate Numeric literals
# Program to demonstrate Numeric Literals a = Ob 1010
#Binary Literals b = 100 #Decimal Literal c = 0o310
#Octal Literal d = Ox 12c
#Hexadecimal Literal print (“Integer Literals :” ,a, b, c, d)
#Float Literal float_1 = 10.5 float_2 = 1.5e2 print (“Float Literals :” ,float_1, float_2)
#Complex Literal x = 1 + 3.14 j print (“Complex Literals:” , x) Print (“x = “ , x , “Imaginary part of x = “ , x.imag, “Real part of x = “ , x.real)
#End of the Program
Output: Integer Literals: 10 100 200 300
Float Literals: 10.5 150.0
Complex Literals: x = (1.3.14) Imaginary part of x = 3.14 Real part of 9 x = 1.0
(II) String Literals:
In Python a string literal 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. To test String Literals
# Demo Program to test String Literals strings = “This is Python” char = “C” multiline_str = ‘”This is a multiline string with more than one line code.'” print (strings) print (char) print (multiline_str)
# End of the Program
Output: This is Python C C This is a multiline string with more than one line code.
(III) Boolean Literals
A Boolean literal can have any of the two values: True or False.
# Demo Program to test String Literals boolean _ 1 = True boolean _ 2 = False print (“Demo Program for Boolean Literals”) print (“Boolean Value 1 :” ,boolean_1) print (“Boolean Value2 :” ,boolean_2)
# End of the Program
Output:
Demo Program for Boolean Literals Boolean
Value 1: True Boolean
Value2: False
(iv) Escape Sequences
In Python strings, the backslash “\” is a special character, also called the “escape” character. It is used in representing certain whitespace characters: “\t” is a tab, “\n” is a newline, and “\r” is a carriage return.
For example to print the message “It’s raining” , the Python command is >>> print (“ItVs rainning”)
It’s rainning
Python supports the following escape sequence characters.