Variables in Python – Tutorial

Variables are used to store values in Python. These variables can be used later on in the program for computing purpose.

Variables have a name, value and a memory location in computer.

For Example:

X = 56

Here X is the Variable Name and 56 is its value.

= is known as assignment operator.

The meaning of this statement is – A value 56 of integer datatype has been assigned to a variable named X.

Another Example :

>>> name = “Rohit”

Here variable name is name

Here value of variable is “Rohit” 

>>> type(name)

<class – str>

How to Print a Variable

>>> print(name)

Output : Rohit

We can use variables to perform mathematical operations.

>>> x = 56

>>> y = 67

>>> print(x + y)

Output : 123

Variable values can also be changed.

>>> name = “Mohan”

>>> print(name)

Mohan

>>> name = “Sohan” # We have changed the previously assigned value.

>>> print(name)

Sohan

You can call variables – value-holder.

These values can be of any datatype.

>>> # Valid Variable Names

>>> first_name = “Mohan”

>>> FirstName = “Mohan”

>>> Firstname = “Mohan”

>>> firstName = “Mohan”

>>> # Invalid Variable Names

>>> first name = “Mohan” # using spaces is not allowed in variable names

SyntaxError: invalid syntax

>>> first-name = “Mohan” # using – sign means subtraction so it is not allowed

# No symbol is allowed except _ (underscore)

>>> We cannot start a variable name with number

>>> 1name = “Mohan” # invalid

>>> name1 = “Mohan” # valid

Conclusion

In Python, a variable is a named location in memory used to store a value. It can change dynamically during the execution of a program. Variables are used to store values such as numbers, strings, lists, etc. Variables in Python are created by assigning a value to a name using the “=” operator. For example:

x = 10 y = “hello”

You can also dynamically change the type of the value stored in a variable by re-assigning it to a new value of a different type.

Leave a Comment