Python variable and its types in details

Python is both a strongly typed and a dynamically typed language. A variable is a name that represents a storage location in memory, and its container that can store data inside it. Each variable is given a specific type that defines what data we can store in memory, what operation we can perform, and how many bits it has used.

In this article, we learn about python variables, variable types, naming conventions for variables, python global variables, and more. Let’s get started.

Python variable intro

A variable is nothing, just a name given to a storage area that our programs can manipulate. You can think variable as a container where we can store data of a specific type like a number, or string. Each variable in Python has a specific type, which determines the

  1. Size it can consume in memory
  2. Type and range of values that can be stored within that memory
  3. Set of operations that can be applied to the variable.

Python doesn’t have a command for declaring a variable as we do in C or Java. Variables do not need to declare with any particular type. Variable is can change its value over time.

Python is both a strongly typed and a dynamically typed language. Strong type means it has a strict variable type and type matter while performing an operation. Adding a number and string will generate an error.

num1 = 10;
num2 = 'ten';
sum = num1 + num2;  //TypeError: unsupported operand type(s) for +: 'int' and 'str'
print (sum);

Dynamic typing means that the type of the variable is determined only during runtime. In Python, there is no advance declaration associating an identifier with a particular data type. Just python allows variables to have different types at different instances or times during their execution.

Python variable naming conventions

Python variable names can be the content of letters, digits, and the underscore character. It must begin with either letter or an underscore. Upper and lowercase letters are distinct because Python is case-sensitive. But is better to follow Python variable naming conventions, the variable is written in camelCase, and its best practice is to follow python variable naming conventions, we can have a general naming convention as follow.

  1. All variable name begins with lowercase letters.
  2. The first character of subsequent words is written in uppercase.
  3. Variable names are case-sensitive.
  4. Variable names cannot contain spaces
  5. Variable names cannot start with a number.

For example, the following variable names are written in camelCase:

courseName
paymentMode
Variable NameValid or InValid?
courseNameValid and correct python variable naming convention
CoursenameValid and incorrect python variable naming convention
_num = 5;Valid and incorrect python variable naming convention
student_per_courseValid is also used for the naming convention by some
1num Invalid
course3Valid
course#3Invalid and can’t have a special character inside a variable.
Python variable naming conventions

What are the Python variable types: built-in class for variable types?

Everything in Python is an object and even variables are objects of having a type. The type of a variable in Python is usually decided automatically based on the value we assign to it. For instance, the statement

num = 10; Object of type integer
amount = 10.5; Object of type floating point number

print(type(num)); //Output <class 'int'>

By running the type function on the variable we get object type, as objects are instances of the class.

Python variable type
Python variable type
ClassDescription Immutable
bool Boolean value (true or false)Yes immutable, can’t change it
int integer (arbitrary magnitude)Yes immutable, can’t change it
float floating-point numberYes immutable, can’t change it
list A mutable data objectNo, can change it
strSequence of characterYes immutable, can’t change it
setAn unordered set of distinct objectsNo, can change it
tupleAn immutable sequence of objectsYes immutable, can’t change it
dictset of distinct keys to associated valuesNo, can change it
Python variable type

Python variable boolean type

As we know everything in python is an object. A boolean variable can hold only two values true|false. The bool class is used to manipulate logical (Boolean) values and we can have only two instances of that class expressed as the literals True and False. The default constructor, bool( ), returns False.

isSummer = False;
print(type(isSummer));

Python variable type number

Number variables can store numeric values, we have three types of number variables in Python. Unlike Java and C++ which support different integral types with different precisions (e.g., int, short, long). Python automatically determines an internal representation of an integer-based on its value magnitude.

The int and float classes are the primary numeric types in Python.

Integer type

Integer variables are whole numbers, can’t have decimal points, and can have both positive and negative numbers. Long integers are bigger than whole numbers and they can also be represented in octal and hexadecimal.

num = 10;
or num = int(10); 
x = int() 
print(x);

The integer constructor, int( ), returns value 0 by default.

Floating type

Floating variables are numbers having decimal points and they can have both positive and negative numbers. We can declare floating numbers with float glass and float class with no value return 0.

x = float(-100.50)
print(x);
y = 12.233;

String type

A string is a contiguous sequence of characters based on the Unicode international character set. We can define strings using single or double quotes in Python.

name = 'edupala.com'
print(name);
description = "Python is OO language"

String in Python is an immutable object, meaning that once we assign a value, its state can’t be changed or modified.

name = 'edupala';
name ='Edupala site';

Although this might seem like the above statement 2 modified name string object but not, assigning a new value to the variable will create a completely new object. We can access strings using it index like

str = 'Edupala.com';
print (str[0]);         //OP E
print (str[8:11]) ;     //OP com

Python list data types

Python list is mutable data object and is most flexible ordered collect can have any sort of objects like numbers, string, and even other lists. We can display lists using square brackets.

list1 = ['Ionic', 'Angular', 'React', '2022', '2000']
print (list1);

Like string, the list is the collection and we can access its value using the slice operator ([ ] and [:]) with indexes starting at 0 at the beginning of the list and working their way to end -1.

list = ['Ionic', 'Angular', 'React', '2022', '2000']
print (list[3]);  // React
print (list[0:3]);  //['Ionic', 'Angular', 'React']

Python tuple data types

Python tuple is an immutable data object and once it is created, it can’t change it change later. It is similar to a list, but can’t be modified and is defined by using parenthesis instead of a square bracket. We can use a tuple for the collection of related items that are not meant to modify later.

tuple = ('Ionic', 'Angular', 'React', 'Flutter', 'Vue');
print (tuple[3]);
print (tuple[0:3]);
print(type(tuple))

is most flexible ordered collect can have any sort of object like numbers, string, and even other lists. We can display lists using square brackets.

Python dictionary type

Python’s dict class represents a dictionary, or mapping, from a set of distinct keys to associated values. Dictionary is a mutable object, here values are stored in key and value pairs and we can’t index on the dictionary as we do in a string, list, and tuple.

countries = { 'in' : 'India' , 'fr': 'France', 'jp': 'Japan', 'de' : 'German' } ;
print(countries['in']);   //OP India
print(type(countries))    // OP <class 'dict'>

Python dictionaries are defined using a curly brace, dictionary with the key we can access its value very fast. Accessing particular values from billion of records from a dictionary is very quick, thus saving computing time and power.

Python set type

Set are mutable data types in Python, set works much like a list but it can hold only unique objects in a collection. We can’t have duplicate entries in the set variable.

frameworks = {'Angular', 'React', 'Vue'};
print(type(frameworks))

How to create a python variable?

We now know that variables are containers and value type is determined by assigning a value to it. In python, variables are created when we assign a value to them. Here we create variables of the following types.

name = 'edupala'; // variable of type string
amount = 10.5; // varaible of type floating point
age = 6; //variable of type integer

Here we create a variable name, which automatically gets type str or string. We can use the python variable type check function to determine the type of a variable. Here we have a python variable type check example

print(10 : type(10));             //Ouput: <class 'int'>
print(type(10,50));              //Output <class 'float'>
print(type('Hello edupala'));   //Output <class 'str'>

Type conversion python

As python is dynamic typing means that the type of the variable is determined only during runtime. The process of converting the value of one data type (float, integer, string, etc.) to another data type is called type conversion. We can achieve python type conversion by two approaches.

  1. Implicit Type Conversion
  2. Explicit Type Conversion

In implicit type conversion, python automatically converts one type to another, here is an example of it.

num = 5;
num = 'Five';
print(type(num)); // Output : <class 'str'>

In explicit type conversion, a user manually has to add code to convert one type to another, for example, we convert string to float.

amount = '10.50';
amount = float(amount);
print(type(amount));
type conversion python
type conversion python

Conclusion
Finally, we have completed the Python variable and its types. I hope you liked this tutorial, please consider it sharing with others.

Leave a Comment

Your email address will not be published.

Scroll to Top