
Hello Techies,
In this tutorial, you will learn about Python Literals and Constants with the help of examples.
I have also covered the topic which is based on Python Variables.
Table of Contents
Python Literals
Literal is raw data that is given in variable or constant.
Below are some of the literal types present in Python:
- Numeric literals
- String literals
- Boolean literals
- Special literals
- Literal Collections
Let’s check Python literals types one by one.
Numeric literals
The Numeric literals are immutable, which means we can’t change them. There are 3 types of Numeric literals: Integer, Float, and Complex.
Types of Numeric Literals in Python:
Integer | Number can be both positive and negative including 0 with no fractional part. eg: 50 |
float | These are real numbers that have both integers and fractions. eg: 50.50 |
Complex | The numerals will be in the form of a+bj, where ‘a‘ forms the real part and ‘b‘ form the imaginary part of the complex number. |
Numeric literal example: How to use Numeric Literal in Python?
# integer literal a = 0b10101 # Binary Literals b = 55 # Decimal Literal c = 0o300 # Octal Literal d = 0x13b # Hexadecimal Literal print(a, b, c, d) # Float literal a = 10.6 b = 2.6e2 print(a, b) # Complex Literal a = 5.24j print(a, a.imag, a.real)
Output:
# integer literal 21 55 192 315 # Float literal 10.6 260.0 # Complex Literal 5.24j 5.24 0.0
String literals
String literal is a collection of multiple characters. There are 2 types of String Literals: Single Line, Multi-Line.
- Single Line String Literal: It is the collection of multiple characters within a pair of single quotes(‘) or double quotes(“).
Example of Single Line String Literal:
'TechPlusLifeStyle', "Python"
- Multiline String Literal: It is the collection of multiple characters across multiple lines.
Example of Multiline String Literal:
#Adding black slash at the end of each line. data ='Python ' \ 'Literals ' print(data) #Using triple quotation marks data='''welcome to TechPlusLifeStyle''' print(data)
Output:
Python Literals welcome to TechPlusLifeStyle
Boolean literals
Boolean literals can have 2 values: True or False
Example of Boolean Literals in Python:
x = (True == 1) y = (6 == False) z = (3 == True) xy = (False == 0) a = True + 5 b = False + 6 print("x is", x) print("y is", y) print("z is", z) print("xy is", xy) print("a:", a) print("b:", b)
Output:
x is True y is False z is False xy is True a: 6 b: 6
Special literals
Python has one special literal that is “None“. We use it to specify that the field is not created.
If we compared ‘None’ with anything else other than a ‘None’ value, it will return False.
Example of Special literals in Python:
test = None if test == None: print("This value is a Special literals.") else: print("This is not a Special literals.")
Output:
This value is a Special literals.
Literal Collections
Python offers four types of Literal collections: List Literals, Tuple Literals, Dict Literals, and Set Literals.
List Literals
- The list contains different data types.
- Values stored in the list are separated by commas (,) and enclosed in square brackets ([]).
- We can store different types of data in a list.
- Lists are mutable.
Example of List Literals in Python:
number = [1, 2, 3, 4, 5] name = ['a', 'b', 'c', 2, 5] print(number) print(name)
Output:
[1, 2, 3, 4, 5] ['a', 'b', 'c', 2, 5]
Tuple Literals
- A tuple is a collection of different data types.
- It is enclosed in parentheses ‘()’ and each element is separated by a comma (,)
- It is immutable.
Example of Tuple literals in Python:
number = (2, 4, 6, 8) names = ('b', 3, 'a', 'c') print(number) print(names)
Output:
(2, 4, 6, 8) ('b', 3, 'a', 'c')
Dict Literals
- The dictionary stores data in key-value pairs.
- It is closed by a curly bracket “{}” and each pair is separated by a comma (,).
- We can store different types of data in a dictionary.
- Dictionaries are mutable.
Example of Dict Literals in Python
dict_example = {'a': 1, 'b': 2, 'c':3 } print(dict_example)
Output:
{'a': 1, 'b': 2, 'c': 3}
Set literals
- A set is an unordered collection of elements.
- The set is created by placing all the items (elements) in curly brackets {} and separating them with commas.
- A set itself is mutable. We can add or remove items from it.
Example of Set literals in Python:
alphabets = {'a', 'e', 'i', 'o', 'u'} numbers = {1, 2, 3} print(alphabets ) print(numbers)
Output:
{'o', 'a', 'u', 'i', 'e'} {1, 2, 3}
It’s about Python Literals. Let us now check some information about Python Constants.
Python Constants
Constant is a type of variable whose value cannot change or cannot be modified. There is no concept in Python, the way they exist in C and Java. In Python, we can define constants in a module, where the module is a file that can be imported to access defined constants and methods.
Rules to create Constants in Python
- The variable name should contain a combination of letters (A to Z) or uppercase (A to Z) or numbers (0 to) or underscore (_). For example IS_VAL, is_true, IsFalse.
- Use capital letters possible to declare a Constant value. For EVEN, EVEN_LIST
Example: How do you declare a constant in Python?
Create a constant.py file and declare all the constant values in it.
IS_VAL = True EVEN_LIST = [2,4,6]
Now check out how to use this static file throughout the project. Suppose your project has a views.py file, so you need to import a constant module to the views.py file to fetch constant values in the views.py file, see the examples below.
import constant print(constant.EVEN_LIST)
Output:
[2,4,6]
Note: We don't use constants in Python. Putting their names in all capital letters is a convention to separate them from variables.
Conclusion
In this tutorial, you learned about Python Literals and Constants, We have covered the following points:
- Python literals types with examples.
- Python constants with rules for how to create constants and how to declare constants.
