Python Tutorials – Variables

Python Tutorial - What is a Variable? - How to use Variables in Python - Syntax - Exceptions - Type Error - Examples

A Variables is a value holder which store a data and it can be used in the program.

In Python there is no need to declare anything for a variable. We can just go ahead and initialize the value. Datatype need not to be mentioned. We have already seen this as Dynamic Typing.

Later the Python Interpreter will decide what datatype suits the variable and parse it to that datatype. You don’t need to bother about those details at this point.

It’s a less work for the developer and many developers love Python for this.

The thing is just start using the variables without any declarations. Python will take care of the rest.

Syntax:

<variable_name> = <value>

Just the variable name, “=” equal to symbol and then followed by the value assigned to it.

a = 10
b = 'test string'
c = '10'
print("a =", a)

print("Datatype a:", type(a))
print("Datatype b:", type(b))
print("Datatype c:", type(c))

Output:

a = 10
Datatype a: <class 'int'>
Datatype b: <class 'str'>
Datatype c: <class 'str'>

If a variable is not initialized but used in program, then “NameError” will be raised.

#variable test is not defined/initialized
print(test)

Output:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-8-7a7fa8f2f46a> in <module>
      1 #variable test is not defined/initialized
----> 2 print(test)

NameError: name 'test' is not defined

That means, python does not know the name given in the program as a variable.

Even though the declaration is not needed, the variable must be initialized before using it.


Asha Ponraj
Asha Ponraj

Data science and Machine Learning enthusiast | Software Developer | Blog Writter

Articles: 86

Leave a Reply

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