Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Python variable and its types in details

Python variable type

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 varlist_noms = [2022, 2001, 2003, 2023]iable 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 alist_noms = [2022, 2001, 2003, 2023]nd incorrect python variable naming convention
student_per_courseValid is also used for the naming convention by some
1numInvalid
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
boolBoolean value (true or false)Yes immutable, can’t change it
intinteger (arbitrary magnitude)list_noms = [2022, 2001, 2003, 2023]Yes immutable, can’t change it
floatfloating-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 numblist_noms = [2022, 2001, 2003, 2023]er

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 list_noms = [2022, 2001, 2003, 2023]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. One of the most frequently used data structures in Python is lists, which have a variety of important methods that make them versatile for various tasks. These are some of the most frequently used list methods in Python:

list1 = ['Ionic', 'Angular', 'React', '2022', '2000']
print (list1);
list1 = ['Ionic', 'Angular', 'React', '2022', '2000']
list1.insert(3,'Flutter')
print (list1)
Output ['Ionic', 'Angular', 'React', 'Flutter', '2022', '2000']

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]);  // 2022
list = ['Ionic', 'Angular', 'React', '2022', '2000']
# Replacing item at particular index
list.insert(2, 'React native') 
print (list[0:3]);  //['Ionic', 'Angular', 'React']

# Used for loop on list
for name in list:
    print(name)


for index in range(len(list)):
    print(index)

# 0 1 2 3 4 5

#Delete an Item by Index:
my_framwork = ['Ionic', 'Angular', 'React', '2022', '2000']
del my_framwork[2]  # This deletes the item at index 2 (the third item)
print(my_framwork)  # Output: ['Ionic', 'Angular', '2022', '2000']

#Delete a Slice of Items:
del my_list[1:3"]  # This deletes items at indices 1, 2
print(my_list)    # Output: [1, 5]

del my_framwork[1:3]  # This deletes items at indices 1, 2
print(my_framwork)    # Output: ['Ionic', '2022', '2000']

del my_framwork
# Now, my_framwork no longer exists, and attempting to access it will result in an error.

Remove an Item by Value : If you want to remove an item by its value rather than its index, you can use the remove() method:

my_framwork = ['Ionic', 'Angular', 'React', '2022', '2000', 'React']
my_framwork.remove('React')  # This removes the first occurrence of the value React
print(my_framwork)    # Output:['Ionic', 'Angular', '2022', '2000', 'React']

pop(index): Removes and returns the item at the specified index. If no index is provided, it removes and returns the last item.

list1 = ['Ionic', 'Angular', 'React', '2022', '2000']
item = list1.pop(1) # Output:['Ionic', 'React', '2022', '2000']
item = list1.pop() # Remove l

index(item): Returns the index of the first occurrence of the specified item.

list1 = ['Ionic', 'Angular', 'React', '2022', '2000']
index = my_list.index('Ionic')
# Result: index = 0

count(item): Returns the number of times an item appears in the list.

list1 = ['Ionic', 'Angular', 'React', 'Ionic', 'Ionic 2']
count = list1.count('Ionic')
print(count) 2

sort(): Sorts the list in ascending order (in-place).

list1 = ['Ionic', 'Angular', 'React', 'Ionic', 'Ionic 2']
list1.sort()
print(list1)

reverse(): Reverses the order of elements in the list (in-place).

list1 = ['Ionic', 'Angular', 'React', 'Ionic', 'Ionic 2']
list1.reverse()

To check the item present in the list, used in here is our example

list = ['Ionic', 'Angular', 'React', '2022', '2000']

if "React" in list:
    print('Present')
else :
    print('No ')

append(item): Adds an item to the end of the list. extend(iterable) Appends the elements of an iterable (e.g., another list) to the end of the list.

my_list = ['Ionic', 'Angular', 'React', '2022', '2000']
my_list.append(2023)
# Result:['Ionic', 'Angular', 'React', '2022', '2000', '2023']
my_list.extend(['React native', 'Flutter'])

copy(): Returns a shallow copy of the list.

list1 = ['Ionic', 'Angular', 'React', 'Ionic', 'Ionic 2']
new_copy = list1.copy()
print(new_copy)

clear(): Removes all items from the list.

list1 = ['Ionic', 'Angular', 'React', 'Ionic', 'Ionic 2']
list1.clear()
print("list : ", list1) 

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.

Python variable and its types in details

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top