Python Variables, Constants and Literals
Python is today's most valuable, easy-to-implement and sought-out programming language. Nowadays, developers want to focus on implementing the program rather than spending time with complex programs. So, for this reason, Python is easy to access and readability, a general-purpose programming language, and is famous for developers.
In any programming language, fundamental concepts are the foundation; hence, in this article, we will learn the concept of python variables, python constants and python literals as Python is an object-oriented programming language famous for its readability and clear syntax.
We can use it as a procedure-oriented language as well. We can run it on many platforms like Windows, Linux,and MAC.
For example, in Java, we write a code of 250 to 360 lines of code. We can write 10 to 15 lines in Python with the same code, which is a time-reducing process for developers.
What are Variables?
A variable is like a memory location where we can store a value. Now, what we store as a value may or may not change in future.
Now coming back to Python, we have to assign a value to declare a variable.
A variable is created as soon as we assign a value to it. Unlike other programming languages like C, C++, Java, etc., it does not need any commands, which require additional commands for declaration and assignment purposes.
Variable Declaration
x = 50
y = "ABC"
print(x)
print(y)
Output

From the above-given example program, we had declared two variables, x and y, and assigned values to them: 50 to x and "ABC" to variable y. When we run this code, we will get 50 and ABC.
We can also perform operations on these variables like addition, subtraction, multiplication, and division, that is, arithmetic operators.
It gives an error if we declare a variable and do not assign any value.
x
Output

Now, we try by giving a value to a variable.
x = 45
Output
Here no error will produce because we had declared a variable and assigned a value to it.
Now, we perform an example program to understand better.
x = 20
y = 20
x*y
Output

We applied an arithmetic operation that is multiplication for x and y values. The result obtained is 400.
When we declare one lower case and one upper case variable, the result will produce without errors.
x = 20
Y = 20
x*Y
Output

The result is the same as the result of the above code; it is not compulsory to declare a variable of all lower and upper cases, and it may be a combination of both.
Variable Data Types
There are six data types in Python, depending on the property they possess.
- Numbers
- String
- List
- Dictionary
- Tuple
- Set
Numbers
Numbers are numerical data types means they have numerical values, and we also have data types like integer, float,and complex numbers. So, integers mainly consist of whole numbers without any decimal point numbers.
We will produce a floating-point number if we add a decimal point number to a whole number.
For complex, we use "j" as an imaginary part,which is added to a number.
For Boolean, it only returns either true or false. So, we use Boolean only for categorical output.
First, we try this as an example.
x = 60
type(x)
Output

We used a variable and assigned a value (60) to it. We will use the type () method to find the variable type.
Let us try another example for this type.
x = 20.09
type(x)
Output

The result produced is "float" because we had given a variable with a value of 20.09. So, the value is a decimal point number we get the output as the float.
To get the output as complex, follow the below code.
x = 45j
print(x)
Output

The result produced is "complex" because we had given a variable with the value "45j". When we declare a value with an integer combined with j, the result will be as above.
To understand the Boolean variable, we take a variable and assign a value as 30>20.
When we check the type of that variable, we get it as "bool". Let us understand this by an example.
num = 30 > 20
type(num)
Result

It will show us a Boolean type variable because we have used an operator called greater than.It shows a correct type because 30 is greater than 20.
When we only give num as an input, it will give TRUE.

Now we will discuss string data type in Python.
String data types in Python are written in "single" or "double quotes". To know better about this, we will discuss an example.
x = 'hello'
y = "world"
z = input()
print("here is an example", x, y, z)
Output

From the above code, we had given two variables, x and y, of string data type, and string values 'hello' and "world". We use the square brackets with an index number to access the string values.
At first, we will learn about index numbers by taking an example.
name = 'ABC'
len(name)
Result
3
So, the length of the string is "3". The index numbers will start from "0", and here the letter A index will be "0", and it will move till the end of the string. So, here the end letter is "C", and the index number for the letter "C" is 2. The string length is three, and the index number starts from "0".
Let us try to access the letter from the string using the index number.
name = 'ABC'
name[2]
Result
C
When we write the index number as "2", we will get the letter "C", which has the index number 2.
Well, we will perform operations on strings.
For example, we can change the case of the string; we can replace the values in the string. So, let us check whether to replace the value in the strings or not.
Try to update a value here at index number 2. Instead of the letter C, take B. It throws a type error because we had given the index number as 2. The error is that the string object does not support the item assigned, meaning strings are immutable,and wecan not change them.
Now, to access the series of letters from the string, we can specify the starting index and the colon(:) we can also determine the ending index.
When we give,
name = 'ABC'
name[0:2]
The above code returns 'AB.' The starting index is "0", and the ending index is "2."
Let us make all letters into uppercase letters.
name = 'Hello World'
name.upper()
Result

It returns all the letters in uppercase.
Similarly, we can make all the letters lower case.
name = 'Hello World'
name.lower()
Result

It gives all the letters in lower case.
To access the values from the end of the string, we can specify the index numbers by giving negative values.
name = 'ABC'
name[-1]
Result

The result is "C", as we had given the negative index as "-1".
So, this was all about the string data type. Now we will move to the "List" data type.
List
A list is a collection of arrays which are changeable and ordered, which means they have indexes just like strings. So, we use the square brackets to declare a list. As we can see here, we have a list named "Fruits", and inside the square brackets, we have the list value.
Example
Fruits = ['apple', 'kiwi', 'banana']
print(Fruits)
Result

We must understand that we can declare different data types in the list and merge integers and strings or use other data types in the list. So, let us take an example.
Let's declare a list first and give some integer values and some duplicate values as well.
Example
mylist = [10, 20, 30, "hello", "courses"]
mylist
Result

We get the values which are declared in the list.
Now, let us try to access the list using index numbers like in the string.
mylist = [10, 20, 30, "hello", "courses"]
mylist = [2:4]
Result

We get the result as [30, hello]
We can also update the index values just like as strings.
mylist = [10, 20, 30, "hello", "courses"]
mylist = [2] = 35
The result will be [10, 35, 30, "hello", "courses"]
Result

We can also add the value to the list using the append() method.
By using this method, it will add the elements to the end of the list.
mylist = [10, 20, 30, "hello", "courses"]
mylist.append(40)
mylist
Result

It shows that 40 is added at the end of the list using the append() method. We can also add the element in the middle of the list.
We can also insert an element or string in the middle of the list using the "insert()" method.
Let us take an example showing the insert method.
Example
mylist = [10, 20, 35, 30, "ABC", "courses", 10]
mylist.insert(5, 100)
mylist
Result

From the above output, we noticed that element 100 is added at index number 5. So, the difference between insert and append is that by using append, we can only add elements at the end of the list, but by the insert method, we can add the values specifying the index number.
Now, let us do a few operations here on strings. So, let us try reversing the list using the reverse() function.
mylist = [10, 20, 35, 30, "ABC", "courses", 10]
mylist.reverse()
mylist
Result

So, by using the reverse() function, we can also reverse the list.
Let us move on to the topic "DICTIONARY"
Dictionary
Dictionary is a collection just like a list, but it is unordered, changeable and indexed. So, we have a key-value pair in a dictionary, and we can use the key as indexes because they are "unique", but we can duplicate the values in the dictionary.
So, let us take an example here. We have the dictionary name as animals and declare the key-value pairs in the curly braces. Let us try this one.
animals = {'mammals' : 'whale', 'reptiles' : 'snake', 'amphibians': 'frogs'}
print(animals)
Result

Let us try another example to understand better.
courses = {1: 'python', 2: 'data science', 'third': machine learning'}
courses
We have successfully declared a dictionary with the name "courses" and given values to it. When we print these values, we get the output as follows:
Result

We get the result as a key-value pair.
We can access the values in the dictionary using "keys" as indexes.
courses = { 1:'python', 2:'data science', 'third': 'machine learning'}
courses['third']
Result

From the above, we understood that when we access the third element, we get the value as "machine learning".
For a similar purpose, we can give the get() method to find the key value there.
courses = { 1:'python', 2:'data science', 'third': 'machine learning'}
courses.get('third')
Result

We get the result same as the standard method.
When we want to replace a value with other, we place the key name and the new element to add to a program.
Example
courses = { 1:'python', 2:'data science', 'third': 'machine learning'}
courses['third']='Ruby'
courses
Result

We observed that we had replaced a key with a new value, and it was "Ruby".
We can also add key-value pairs by using square brackets. So, place a key name and a new element to be added.
courses = { 1:'python', 2:'data science', 'third': 'Ruby'}
courses['four']='machine learning
courses
Result

We observed that a new key and a value are added to the dictionary.
Tuple
A tuple is ordered and unchangeable, which means it is immutable, just like a string. We can not make any changes to the tuple once we declare it. But we can have duplicate values as well. Let us try to understand it with an example.
animals = ('lion', 'tiger', 'monkey')
print(animals)
Output

We have a tuple named "animals" and a few values.
animals = (10, 10, 20, 'tiger', 'lion, 'giraffe', 'tiger')
animals[2]
Result

We see that tuples are indexed as well. We can use the index value to access the values from the tuple.
Now, since it is immutable and we cannot change it, there are not many operations we can perform on the tuple. But we can count the number of duplicate values using the count() function. We have a duplicate value named "tiger" from the above code. So we will check how many times the tiger has repeated the above.
animals = (10, 10, 20, 'tiger', 'lion', 'giraffe', 'tiger')
animals.count('tiger')
Result

So, the value "tiger" was repeated two times in the code.
Let us quickly move on to "SET" now.
Set
A set is a collection like a list or a dictionary, but it is unordered, and there are no duplicate entries. Let us discuss with an example.
Example
myset = {10, 20, 30, 40, 40, 50, 'ABC', 'courses'}
myset
Result

We observed that the output was standard set without any exact values by giving duplicate values.
Now, we try to access the elements by using the index number.
myset = {10, 20, 30, 40, 40, 50, ABC, courses}
myset[2]
Result

We observed the error that the "set" object does not support indexing which means the set does not have any indexes, and every time will print a set, it will show us a random value. So, this was all about sets, and we moved to "RANGE."
Range
The range is used whenever we are iterating through values. Suppose we want numbers from 0 to 10, and let us put them in the list to get the values.
range(10)

We get the output as a range (0,10). The range denotes the minimum and maximum values.
list(range(11)
Result

When trying to print values from 0 to 10, we used the "list" to print the range of numbers. When we give 11 in a range, it will provide the values of the list, that is, from 0 to 10.
It is all about range. We take a miscellaneous example; we have two dictionaries with some values.
a = {1, 2, 3, 4}
b = {4, 5, 4, 5, 6}
c = [a, b]
c
Result

Let us try to make a list for combining the values of a and b. Let us see by executing it. Printing the value of c will show us that the list c has dictionary a and b values.
It shows that we can make a list with other data types. For example, we can incorporate a dictionary over there. We can also do with the tuple or a set, and if we want some values that we don't want to change in the future, we can make it a tuple and declare it in a list so that we cannot change the value in the future. For example, if we don't want to access any values using indexes, we can make it by using a set so that it will not have any indexes.
So, that is all about data types.
Type Conversion
Suppose we have an integer variable with ten values and a string that says name = 'name'.
x = 10
name = 'name'
x + name
Result

When we try to add those integers and strings, it will show a "type error," which says an unsupported operand type. Now for this type, we will use a type conversion here.
Type conversion is used we are trying to covert a type of variable to another data type.
We have many functions here.
- int()-This function changes any data type to an integer data type.
- float ()-This function changes any data type to float data type.
- tuple()-This function changes any data type to the tuple.
- list()-This function changes any data type to list.
- set()-This function changes any type to a set.
- dict()-This function changes any data type to a dictionary.
Now let us look at the example.
x = 10
name = 'name'
str(x) + name

When we change the data type of integer to a string, we get the result as error-free. So, it is all about type conversion.
Let us take another example. So, we had a dictionary here with the name "b".
Example
b = {4, 5, 4, 5, 6}
list(b)
Result

We used a list function and specified "b" over there. So, we convert a dictionary into a list. So, this is what type conversion means.
Python constants
A python constant is a variable whose value cannot be changed. It is helpful to think of constants as containers containing information that will not change later.
Naming conventions for variables and constants in Python:
- Terminology should be a purpose.
- Use camelCase notation
- Use capital letters to represent a constant symbol like @, #, $, %, etc., should not be used.
- Don't start with a digit.
- Constants are put into python modules and meant not to be changed.
- Constants and variables' names should have a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_).
Let us go for a demonstration.
Assigning values to constant in Python
In Python, constants are in-built, declared, and assigned in a module.
So, the meaning of module is a new file containing variables, functions, etc., that will import to the main file.
Let us go for a demonstration using constants.
#Declaring and assigning value to constants
PI=3.14
GRAVITY=9.8
The above values we assigned are built-in constants and contain a constant value, and we must write all the constant names in capital letters. There will be no execution for the above because there is no print statement.
#Declaring and assigning value to a variable
#Declaring and assigning value to a variable
a = "Apple."
print(a)
#Changing the value of a variable
a = "Aeroplane"
print(a)
a = 100
print(a)
#Assigning multiple values to a variable
b, c, d = 1, 2.5, "Hello"
print(b, c, d)
#Assigning the same value to multiple variables
b = c = d = 5
print(b, c, d)
Result

We defined how to determine, declare, and assign values to variables.
From above, "a" is a string type, and when we print those values, it will show the same as the print statement.
Changing the value of a variable can be done by reassignment. So, a = "Aeroplane", and when we print this statement, it prints the statement.
Following the line, we gave an integer variable and assigned a value "10" to it, which prints that integer value. So, we observed that when we provide a new value for the same variable, it prints the old and unique value irrespective of data types.
We can also find that the same variable is sometimes initialized with the string and sometimes with the integer, and all these are allowed in Python because Python is a dynamic type language. It means the variable's data types will decide during the runtime. So, during runtime, the variable's value will contain that will determine the variable's data type. In the case of Python, there is no need to declare the variable separately; at the beginning of the code, we can define a variable when we require to use them. We can find that a= "Aeroplane" in the code, so that "a" has got the string data type, and the next part of the code "a" is treated as a string until and unless it is initialized with another data type.
We can also assign multiple values to a variable. So, the codes b, c, and d is the variables that will assign with 1, 2.5, and Hello in a single line.
We can also assign the same value to multiple variables using the same statement in the same line. From above, b = c = d = 5. That is, three variables are assigned to the same value in a single statement and single assignment. So, 5 5 5 will print as the output.
Literals in Python
Literal may be defined as a quantity whose value cannot be changed during the execution of a program.
Types of Literals
These literals are mainly classified into five types.
- String
- Numeric
- Boolean
- None
- Sequence
And again, strings are of two types:
- Single line
- Multi line
Numeric is categorized into three types:
- Integer
- Real
- Complex
The sequence is categorized into four types:
- List
- Tuple
- Dictionary
- Set
Let us discuss them one by one in brief.

String Literals
String literal is a collection of multiple characters. Types of string literal are:
- Single Line: It is the collection of various characters within a pair of single quotes (') or double quotes (").
Examples:
"India", 'rs.100', "A", 'Grade', "Fathers name", '1-x-5-k-9'.
2. Multiline: The collection of multiple characters across multiple lines. It can be created as given in the following examples:
Example:
str = 'Hey'\Hii'
Backslash allows continuing string at the next line.
Example 2:
str = '''Hey Hii'''
Triple quotes at the beginning and end allow the string to continue at multiple lines.
Example 3:
str = """Hey Hii"""
The triple-double quotes at the beginning and end allow the string to continue at multiple lines.
'Hii Hello'
Result

"Hii Hello"
Result

"hii\
hello"
Result

There is no use of what are the quotes for input, and the result will be displayed in a single quote.
Numeric Literal
Numeric literals are those literals which can contain digits only. Types of numeric literals are:
- Integer literals
- Floating point literals
- Complex literals
Integer literals
Integer literals are those which contain numbers without a decimal point. They can be both negative as well as positive. Types of integer literals are:
Decimal: It has the digits from 0 to 9
Example: 1234, 45, 70
Octal: It can contain digits from 0 to 7 prefixed with 0o(Zero prefixed by o).
Hexadecimal: It can contain digits from 0 to 9 and alphabets from A to F where A=10, B=11, C=12, D=13, E=14 and F=15. It is prefixed with 0x.
Example: 0X12, 0XF9A
Binary: It can contain digits 0 and 1. They are prefixed with 0b (Zero followed by alphabet 'b').
Example: 0b101
10
Result

0o12
Result

It has shown "10"; the octal will convert to a decimal value.
0x12
Result

Again, it does the same because it is an octal number, converted into a decimal value of 18.
0b101

We gave binary as an input, and we can see that it is showing "5", which is the decimal equivalent of binary 101.
It is all about string literals. Now we will discuss "Floating point literals".
Floating Point Literals
They are also known as real literals. They can contain decimal points to them. They can be written in two ways:
- Fractional form
- Exponent form
Fractional form
In fractional form, a real number contains a whole number followed by a decimal point(.), further followed by a fractional part. We can omit digits before or after the decimal point, and they can contain both negative and positive values.
Example
12.33, 0.345, -45.344
Exponential form
In this form, a real number is represented in terms of the power of 10. The power of 10 is defined by alphabets E or e. The real number in exponential form has two parts:
- Mantissa: The digits before the symbol E from the Mantissa part.
- Exponent: The exponent part can only contain integers.

Example: 1.33*105 can be represented as 1.33E5.
Let us display this one by practical.
2.5
Result

2.5e3
Result

The above value is exponential, and the output is 2500. 2.5 is multiplied by 1000, that is 10^3.
If the power is enormous, that is 2.5e35; then it will be shown as 2.5e+35.
2.5e35
Result

Complex Literal
Complex literals are of the form A + Bj.
Here A and B are real values. A is termed as real part, and B is termed as imaginary part.
"j" represents the square root of -1, an imaginary number.
Example
2.3+3.5j
Here 2.3 is the real value, and 3.5j is the imaginary value.
None literal
It represents something that has not been created yet and is described as None.
Python does not display anything when we try to declare a variable with no value stored; None will be shown.
Example
True

False

None
Sequence literals
A sequence is a group of comma-separated values. They are of four types.
- List: A collection of separate comma values within the pair of square brackets.
Example:
[10, 20, 30, 40]
Result

2. Tuple: It is a collection of separate comma values within the pair of
Parenthesis.
Example
(1, 2, 3, 4)
Result

3. Set: A collection of separate comma values within the pair of curly braces.
Example:
{11, 12, 13, 14}
Result

4. Dictionary: It is a collection of separate comma key: value pairs within the pair of braces.
Example:
(1: 'a', 2: 'b', 3: 'c', 4: 'd')
Result

These are all about python literals and their types.
Character literal
It is also a type of string literal where single or double quotes surround a single character.
Size of string
Python determines the size of a string as the count of characters in the string; for example
size of string "xyz" is 3, and "HelloWorld" is 10.
Differences between Variables, Constants and Literal
Variable: It is a name of a location in memory that enables us to store a value for later use.
It is called variable because we can change the content whenever we want.
Example:
int i=10; where "i" is a variable.
Constant: It is like a variable. The only difference between constants and variable is that they cannot be changed once defined.
Example:
Const int i = 10;
Here "i" is a constant, and we cannot change the value \\ throughout the execution life cycle of a program.
Literals: Literals are values assigned to variables and constants.
Example: const int i = 10;
"10" is literal, and "i" here is a variable, and when we declare a "const" keyword and so, it becomes constant, and we cannot change its value for further program execution.
So, there are many types of variables, constants and literals. We all learnt it here, which is also helpful for python basics.