Python Literals

Literal is a raw data given in a variable or constant. Literals can be defined as a data that is given in a variable or constant .

  Python support the following literals

  1) String literals

  2) Numeric literals

  3) Boolean literals

  4) Literal Collections such as List , Tuples , Dictionary

  5) None Literal


1) String literals

String literals can be formed by enclosing a text in the quotes. We can use both single as well as double quotes for a String.


name='John'
fathers_name="Petter"
print(name)
print(fathers_name)
John
Petter

\ can be used to escape quotes


name=' \" John \"'
fathers_name=" \" Petter \" "
print(name)
print(fathers_name)

address=''' \' \"Gomti nagar Lucknow\" \''''
print(address)
 " John "
 " Petter "
 ' "Gomti nagar Lucknow" '

Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated.

var ="py" "thon"
print(var)
var="python " "is " "easy " "programmng"
print(var)
python
python is easy programmng

2) Numeric literals

A number that is directly assign to a variable is called Numeric Literal. Numeric Literals are immutable. Numeric literals can belong to following four different numerical types.

Int(signed integers) Long(long integers) float(floating point) Complex(complex)
numbers( can be both positive and negative) with no fractional part.eg: 500 Integers of unlimited size followed by lowercase or uppercase L eg 1422L Real numbers with both integer and fractional part eg: -26.2 In the form of a+bj where a forms the real part and b forms the imaginary part of complex number. eg: 45+54j

n1=4564 #integer literal
n2=454.54 #float literal
n3=45+54j #complex number literal
print(n1)
print(n2)
print(n3)

4564
454.54
(45+54j)

3) Boolean literals

A Boolean literal can have any of the two values: True or False


flag=True
flag1=False
print(flag1)
print(flag)
False
True

4) Literal Collections such as List , Tuples , Dictionary

eg


#going to create list
numbers=[1,2,3,4,5,6,7]
print(numbers)

#going to create tuple
alph=('a','b','c')
print(alph)

#going to create Dictionary 
detail={'name':'John',
		'phone':8896163869
		}
print(detail)
[1, 2, 3, 4, 5, 6, 7]
('a', 'b', 'c')
{'name': 'John', 'phone': 8896163869}

5 ) None Literal

Python contains one special literal i.e., None.


var=None
print(var)
None

Example :


#create a function to print numbers
def print_s(n=None):
	if n is not None:
		for i in range(1,n+1):
			print(i)
	else:
		print("value of n is required !!")

# now call print_s function
print_s(5)
print_s()
1
2
3
4
5
value of n is required !!