In this lesson, You will learn about Python literal and its types with examples to better understand the topic.
A literal is a variable or constant that gives raw data. There are different kinds of literal in Python. They are:
Numeric Literals are immutable (unchangeable). Numeric literals can be of three types: Integer, Float, and Complex.
Let’s see an example of how to use Numeric literals in Python.
Example
binaryLiteral = 0b1010 #Binary Literals decimalLiteral = 100 #Decimal Literal octalLiteral = 0o310 #Octal Literal hexadecimalLiteral = 0x12c #Hexadecimal Literal #Float Literal floatLiteral = 10.5 #Complex Literal complexLiteral = 3.14j print(binaryLiteral, decimalLiteral, octalLiteral, hexadecimalLiteral) print(floatLiteral) print(complexLiteral, complexLiteral.imag, complexLiteral.real)
Output
10 100 200 300 10.5 3.14j 3.14 0.0
decimalLiteral
is literal decimal, octalLiteral
is literal octal, and hexadecimalLiteral
is literal hexadecimal.The name String Literals refers to a group of characters inside quotes. You can use single, double, or triple quotes for a string literal.
Conversely, a character literal is a single character inside single or double quotes.
Example
stringLiteral = "Python Literal" charLiteral = "C" multilinestrLiteral = """Multiline string""" unicodeLiteral = u"\u00dcnic\u00f6de" rawstrLiteral = r"raw \n string" print(stringLiteral) print(charLiteral) print(multilinestrLiteral) print(unicodeLiteral) print(rawstrLiteral)
Output
Python Literal C Multiline string Ünicöde raw \n string >
stringLiteral
is a string literal in the program above, and charLiteral is a character literal.multilinestrLiteral
is a literal multi-line string.In Python, a Boolean literal can have any of these two values:
Let’s see an example of how to employ a Boolean literal in Python.
Example
boolx = (1 == True) booly = (1 == False) boola = True + 4 boolb = False + 10 print("boolx is", boolx) print("booly is", booly) print("boola:", boola) print("boolb:", boolb)
Output
boolx is True booly is False boola: 5 boolb: 10
Python has one special literal, which is the word “none.” It tells us that the field has not yet been made.
Example
Color = "Favorite" Red = None def menu(x): if x == Color: print(Color) else: print(Red) menu(Color) menu(Red)
Output
Favorite None
We set up a menu function in the program we just looked at. When the argument is set to Color inside the menu, it says Favourite. And when Red is the argument, it shows None.
This concludes the Python Literals lesson. In the next lesson, you will learn namespaces in Python and their usage.