What are Literals in Python?



Literals in Python are the values assigned to variables or constants. Here, we will discuss the types of Literals.

  • Numeric Literals
  • String Literals
  • Boolean Literals

Numeric Literals

Numeric Literals are digits. Python supports four different numerical types −

  • int (signed integers) − They are often called just integers or ints, are positive or negative whole numbers with no decimal point.

  • long (long integers ) − Also called longs, they are integers of unlimited size, written like integers and followed by an uppercase or lowercase L.

  • float (floating point real values) − Also called floats, they represent real numbers and are written with a decimal point dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).

  • complex (complex numbers) − are of the form a + bJ, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Complex numbers are not used much in Python programming.

Example

Let us see an example.

# Python int Literal val1 = 25 print(val1) # Python float Literal val2 = 11.89 print(val2) # Python complex Literal val3 = 6+2.9j print(val3) # Python hexadecimal Literal val4 = 0x12d print(val4) # Python octal literal val5 = 0o021 print(val5)

Output

25
11.89
(6+2.9j)
301
17

String Literals

We can easily create a string literal simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable.

Let’s see how to easily create a String in Python -

myStr = Thisisit!'

Example

We will now see an example of creating single-line and multi-line strings -

str1 = "John" print(str1) # Multi-line string str2 = """ This, is it! """ print(str2)

Output

John
 This,
is it!

Boolean Literals

Example

Boolean has two values i.e. True and False. True is for 1 and False 0. Let’s see an example −

a = (1 == True) b = (1 == False) print(a) print(b)

Output

True
False

Advertisements