This post at hand is thus, all about the different Python variables and data types that are used. We will also get to learn the different ways to change one data type into another. We will also get ourselves acquaint with what are Local and Global variables? There uses, and hence, How to declare variables in Python ?

So, let’s begin with Python variables and the various data types.

What are Python Variables?

A variable is like a container or a storage for a value thus. It is usually assigned a name, which is then used to refer to it later or access it later in the program. Its datatype is thus decided by the interpreter of the coding language based on the value it contains. You can though, store different type of values in a variable also, but, then, the datatype of the variable will change accordingly. We will see its various applications a bit later. Before that, lets see the naming rules for these.

Variables Naming Rules — How to declare variable in Python

There are certain rules to follow when naming a variable (called an identifier).

  • Python variables can only begin with a letter(A-Z/a-z) or an underscore(_) thus.
  • Also, the rest of the identifier may contain letters(A-Z/a-z), underscores(_), and numbers(0-9).
  • Python is case-sensitive, and so are Python identifiers. Thus, Name and name are two different identifiers.
  • Also, Reserved words (keywords) cannot be used as identifier names.
anddefFalseimportnotTrue
asdelfinallyinortry
assertelifforispasswhile
breakelsefromlambdaprintwith
classexceptglobalNoneraiseyield
continueexecifnonlocalreturn
How to declare variables in Python

Assigning values to Variables — How to declare variables in Python

To assign a value to Python variables, the variable declaration is also not compulsory. We just need to follow the various Naming Rules confinements and then type the value of the variable after the “equal” sign known as the assignment operator.

.>>> name = shubham
>>> print(name)

Output

shubham

Assigning Multiple Values to a Variable

One can assign values to multiple Python variables in one statement also.

>>> age,city=21,'Indore
'>>> print(age,city)

Output

21 Indore

Variables deletion

We are thus, able to delete different variables using the keyword ‘del’.

>>> a = 'shubham'
>>> del a
>>> a

Output

Traceback (most recent call last):
File "<ipython-input-15-d97c97b5d095>", line 3, in <module>
    a
NameError: name 'a' is not defined

Data Types in Python

The following datatypes get support in Python.

Numbers

There are basically four numeric Python data types.

  • int

The int datatype thus as the name suggests stands for integer. It holds only integer values thus. We can also use the type() function to find which class it belongs to.

>>> a = -7
>>> type(a)

Output

<class ‘int’>
  • float

The float datatype holds floating-point real values, i.e. decimal numbers.

.>>> a=3.0
>>> type(a)

Output

<class ‘float’>
  • long

This datatype holds long integer values of unlimited length also. It is though unavailable in Python 3.0 and above.

  • complex

It thus, holds a complex number. Also, a complex number is of the form : a+bj . Here, a and b are the real parts of the number, and i is imaginary.

>>> a = 2 + 3j
>>> type(a)

Output

<class ‘complex’>

Strings

A string is thus, a sequence of characters. Python does not have a char data type, unlike C++ or Java. You can also delimit a string using single quotes or double-quotes.

>>> city = 'Noida'
>>> city

Output

'Noida'’

Lists

A list is a collection of values. It can thus, contain any type of values and not necessarily just a single type. To define a list, you must thus, put values separated with commas in square brackets. Also, you don’t need to declare a type for a list either.

>>> names =['Shubham','Rohit',3,14,5,6,7]
>>> name

Output

['Shubham','Rohit',3,14,5,6,7]

Tuples

A tuple is like a list. You declare it using parentheses instead.

>>> names = ('Shubham','Rohit',3,14,5,6,7)
>>> name

Output

('Shubham','Rohit',3,14,5,6,7)

Dictionaries

A dictionary holds key-value pairs also separated by a colon(:). It is thus, declared in curly braces, with pairs separated by commas.

>>> person = {'name' : 'Shubham', 'age' : 25}
>>> person
>>> type(person)

Output

{'name' : 'Shubham', 'age' : 25}
<class ‘dict’>

bool

A Boolean value can be True or False thus.

>>> a = 2 > 1
>>> type(a)

Output

<class ‘bool’>

Sets

A set can thus, have a list of values. It is an unordered list, so it doesn’t support indexing of values.

>>> a = {12,22,23}
>>> a
>>> a[1]

Output

{12,22,23}

OutputTraceback (most recent call last):
File “<pyshell#127>”, line 1, in <module>
a[2]
TypeError: ‘set’ object does not support indexing

Get your hand on our article on the conversion method from Set to Lists.

Type Conversion

Type conversion is the process of converting the value of one data type (integer, string, float, etc.) into another data type. Python basically has two types of type conversion.

  • Implicit Type Conversion, and
  • Also, Explicit Type Conversion

Implicit Type Conversion

In Implicit type conversion, Python automatically converts one data type to another data type. Also, it doesn’t require any user involvement.

Thus, let’s see this with an example.

Converting integer to float

a = 123
b = 1.23

c = a + b

print("The datatype of a is : ",type(a))
print("The datatype of b is : ",type(b))

print("Value of c is equal to : ",c)
print("The datatype of c is :",type(c))

Output

The datatype of a is :  <class 'int'>
The datatype of b is :  <class 'float'>
Value of c is equal to :  124.23
The datatype of c is : <class 'float'>

In the above program, thus, we have converted an integer value to a float value. Now, let’s try adding a string and an integer also.

a = 123
b = "456"

print("Data type of a is : ",type(a))
print("Data type of b is : ",type(b))

print(a + b)

Output

Data type of a is :  <class 'int'>
Data type of b is :  <class 'str'>

Traceback (most recent call last):

  File "<ipython-input-13-0cd0f6d6dffa>", line 7, in <module>
    print(a + b)

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Explicit Type Conversion

In this type of conversion, users can convert the data type of an object to any required data type hence. Thus, we use the predefined functions like int(), float(), str(), etc to perform explicit type conversion. This type of conversion is also called typecasting because the user casts the data type of the objects.

Syntax :

<required_datatype>(expression)

Typecasting can be done by assigning the required data type function to the expression also. Thus, now let’s see an example now.

a = 123
b = "4526"

print("Data type of a is : ",type(a))
print("Data type of b before Type Casting is : ",type(b))

b = int(b)
print("Data type of b after Type Casting is : ",type(b))

sum = a + b

print("Sum of a and b is equal to : ",sum)
print("Data type of the sum variable is : ",type(sum))

Output

Data type of a is :  <class 'int'>
Data type of b before Type Casting is :  <class 'str'>
Data type of b after Type Casting is :  <class 'int'>
Sum of a and b is equal to :  4649
Data type of the sum variable is :  <class 'int'>

Local and Global Variables

Another classification of Python variables is based on scope.

Local Variables

When you declare a variable in a function or a class, its scope becomes limited and it is only visible in that scope. If you invoke it outside of that scope, you also get an error which states ‘undefined’.

>>> def func():
              a = 2
              print(a)
>>> func()

Here, the variable ‘a’ is limited and local to the func() function also.

Global Variables

When you declare a variable outside its scope, it is visible and accessible in the full program whenever and wherever called or invoked.

>>> a=3
>>> def func():
               a=0
               a+=1
       print(a)
>>> func()

One may use the ‘global’ keyword when needed to use a variable as a global one in a local scope.

>>> shubham = 1
>>> def func():
              global shubham
              shubham = 2
      print(shubham)
>>> func()

SUMMING UP — How to declare variables in Python

Through this post, we have got ourselves acquaint with various topics like, the different Python variables and also data types that are used. We also got to learn about the different ways to change one data type into another. We have also got ourselves acquaint with what are Local and Global variables? There uses, and hence, How to declare variables in Python ? Thus, now I suppose and hope that the topic at hand is quite clear to you. Since, we have covered the topic in great depth with the help of ample interesting examples.