/
๐Ÿ

Python Literals

https://docs.python.org/3/reference/lexical_analysis.html#literals
python
On this page
  • Python literals

Python literals

Python literals are a data type and can hold any value type, such as strings, numbers, and more.

Because Python literals are used to store base data for the source code of your software, they need to be robust enough to work with any data. Python literals can hold any data you need.

Strings

Strings are one of the most common data value types you will work with in Python. All string literals are enclosed between two quotes ('') or double quotes ("") characters.

python
s = 'It\'s Always Sunny' # in a single quote
t = "It's Always Sunny" # in double quotes
m = '''It\'s
Always
Sunny''' # multi-line String
sqc = 'D' # character literal in single quote
dqc = "R" # character literal in double quotes

Numeric

Numeric values are another value you will find yourself working with often.

python
nb = 0b10100 # Binary Literals
nd = 50 # Decimal Literal
no = 0o320 # Octal Literal
nh = 0x12b # Hexadecimal Literal
nf = 24.8 # Float Literal

Booleans

Boolean values are beneficial, especially in the source code of your software, as they are frequently used to set operating parameters.

Booleans are two: True and False; each one are an alias of 0 (False) and 1 (True).

python
one = (1 == True) # true
two = (2 == False) # false
three = (3 == True) # false
boolTruMath = True + 10 # Result is 11
boolFalseMath = False + 10 # Result is 10

Collections

Collections are also helpful, and the fact is you will likely need them to store collections of data in your source code.

python
numList = [1, 2, 3, 4, 5] # List
numTuple = (1, 2, 3, 4, 5) # Tuple
numSet = {'1', '2', '3', '4', '5'} # Set
peopleDict = {'D': 'Deandra', 'C': 'Charlie', 'M': 'Mac'} # Dictionary

Special

Finally, a special literal is used to signify a null value, and the None keyword can be used in a literal when you need a value to be null or โ€” no value.

python
iAmNone = None # Special literals
Want to make your own site like this?
Try gatsby-theme-code-notes by Zander Martineau.
Life of Code