Literal

Python

Literal Types

Python 2.7
``````booleanVar = True
integerVar = 12
floatingPointVar = 1.618
complexVar = 2j+1
stringVar = "Hello"
listVar = [1, 2, 3]
tupleVar = (1, 2, 3)
dictVar = { "name": "Sam", "age": 21}
setVar = {"apple", "banana", "orange"}
noneVar = None``````

Literals represent values, like: `True`, `12` or `"Hello"`.

Literals in Python can be grouped into these categories:

• Boolean
• Integer
• Floating-point
• Complex number
• String
• List
• Tuple
• Dictionary
• Set
• None

Boolean Literal

Python 2.7
``````enable   = True
disable  = False``````

There are 2 Boolean literals, `True` and `False`.

Integer Literal

Python 2.7
``````ans1 = 42         # Base10
ans2 = 0b101010   # Binary
ans3 = 0o52       # Octal

There are 4 Integer Literal representations:

• Base10
• Binary (base 2)
• Octal (base 8)

All the variables defined here are equal to value 42.

Floating-Point Literal

Python 2.7
``````pi1 = 3.14159     # Normal
pi2 = 314159E-5   # Scientific``````

There are 2 Floating-point Literal representations:

• Normal
• Scientific

Both variables defined here are equal.

Complex Literal

Python 2.7
``complexVar = 2j+1``

Python natively supports Complex Numbers.

Complex numbers are an extension of the familiar real number system in which all numbers are expressed as a sum of a real part and an imaginary part.

String Literal

Python 2.7
``````name1 = 'sam'
name2 = "sam"
name3 = '''sam'''``````

String is a sequence of characters.

There are 3 String Literal representations:

• Single quote
• Double quote
• Triple quote

The differences between these Literals will be explained in the String topic.

List Literal

Python 2.7
``groceries = ["Milk", "Egg", "Corn"]``

List is an ordered sequence of items.

Lists in Python are similar to Arrays in other Languages.

Here, We are creating a list of 3 elements named `groceries`.

Lists will be discussed in the Array topic.

Tuple Literal

Python 2.7
``groceries = ("Milk", "Egg", "Corn")``

Tuple is an immutable List.

Here, We are creating a Tuple of 3 elements named `groceries`.

Tuples will be discussed in the Array topic.

Dictionary Literal

Python 2.7
``sam = {"name": "Sam", "age": 21}``

Dictionary is a collection of key/value pairs, in which keys are unique.

Here, We are creating a dictionary with two keys `name` and `age`.

Dictionary will be discussed in the Map topic.

Set Literal

Python 2.7
``groceries = {"Milk", "Egg", "Corn"}``

Set is a collection of unique items.

Here, we are creating a set with 3 items.

Set will be discussed in the Map topic

None Literal

Python 2.7
``nextElement = None``

`None` is used to represent the absence of a value.

It is similar to `null` in other programming languages.