Python: Literals
Literals are the fixed values assigned to variables in Python. It is the data that doesn’t change during the program execution.
Get Nilesh Saini’s stories in your inbox
Join Medium for free to get updates from this writer.
Example-
num = 10
str = 'Hello'
isBool = TrueWhen you assign values like an integer 10, a string ‘Hello’ or a boolean ‘True’ to a variable, these constant values don’t change during program execution and are called literals.
Where are literals used?
- Assigning Values to Variables
name = 'Sheldon Cooper' #String Literal
age = 29 #Integer Literal
price = 2.9 #Float Literal
valid = True #Bool Literal2. Function Parameters
print('Hello world')
type(10)
# 'Hello world' and 10 are Literal, directly passed in the function3. Default Values in Function
def sayHi(name = 'Guest'):
print('Hello', name)
# 'Guest' is a literal, if no argument is given then it will be used. 4. Conditional Statements
if True:
print('Bazinga!!!')
# True is a literal5. Loops
for i in range(5):
print(i)
# Integer 5 is a literalLiterals vs Non-Literals
✅ a = 10 # Integer 10 is directly assigned to 'a'
❌ b = a + 5 # This is an expression, b is dependent on variable 'a'.
❌ c = input() # Value comes from the user is not constant.
❌ d = len('Howard') # Value is computed dynamically
#as len function counts the length of argument one by one.Types of Literals
Numeric
- Integer Literals
- Floating-Point Literals
- Complex Number Literals
a = 10 # Decimal (Base 10)
b = 0b1010 # Binary (Base 2)
c = 0o12 # Octal (Base 8)
d = 0xA # Hexadecimal (Base 16)String Literals
- Single Quote ( ‘ )
- Double Quotes ( “ )
- Triple Quotes ( ‘‘‘ )
str1 = 'Bazinga!!!'
str2 = "Bazinga!!!"
str3 = '''Bazinga
!!!'''
str4 = "Sheldon says \n Bazinga!!!" # Escape CharacterBoolean
- True
- False
isValid = True
notValid = FalseNone
It represents an absence of value. It is used to indicate that the variable has no value assigned.
x = NoneCollection Literals
Python has several built-in data types for collections
- List
- Tuple
- Directory
- Set
# List
l1 = []
l2 = [1,2,3]
# Tuple
t1 = ()
t2 = (10, 20)
# Directory
d1 = {}
d2 = {"name": "Sheldon"}
# Set
s1 = set()
s2 = {1,2,3,4,5}

