Python Literals
In Python, a literal is a notation for representing a fixed value in source code. Python has several types of literals for representing different types of values, including numbers, strings, lists, and dictionaries.
Numeric Literals In Python
Numeric literals can be written in different bases such as decimal, octal and hexadecimal. Decimal literals are written with digits 0-9, octal literals are written with digits 0-7, and hexadecimal literals are written with digits 0-9 and letters A-F. For example,
1decimal_literal = 10 2octal_literal = 0o12 # starts with 0o 3hexadecimal_literal = 0xA # starts with 0x
String Literals In Python
String literals are written using single or double quotes. For example,
1string_literal = "Hello, World!" 2string_literal_single_quote = 'Hello, World!'
In the above example, "Hello, World!"
and 'Hello, World!'
are both string literals. The only difference is that the first one is enclosed in double quotes and the second one is enclosed in single quotes. Both are equivalent and can be used interchangeably.
You can also use triple quotes for multi-line strings, for example:
1string_literal_multi_line = """ 2This is a 3multi-line 4string 5"""
List Literals In Python
List literals are written using square brackets and separated by commas. For example,
1list_literal = [1, 2, 3, 4, 5]
Dictionary Literals In Python, dictionary literals are written using curly braces and key-value pairs separated by colons. For example,
1dictionary_literal = {'name': 'William', 'age': 30}
Boolean Literals In Python
Boolean literals are written using the keywords True
and False
. For example,
1bool_literal = True