Variable

What is a Variable?

In Python, a variable acts as a container for storing data values. Unlike other programming languages, in Python, you don’t need to declare a variable’s type, the interpreter infers the type based on the assigned value.

Naming Conventions

Names of variables in Python can be made up of letters (a-z, A-Z), underscore (_), and numbers(0-9), but can’t start with a number. Moreover, Python is case-sensitive, meaning myvar and Myvar will be treated as different variables.

Declaring Variables in Python

In Python, variables are declared by using the assignment operator =. The variable name is on the left side of = and the value to be stored is on the right side.

Let’s declare a variable myVar and assign it the value 10.

1myVar = 10

Dynamic Typing

Python is dynamically typed, which means you can change the type of value assigned to a variable even after the variable has been declared.

You can verify this as follows:

1myVar = 10
2print(type(myVar))  # Output: <class 'int'>
3
4myVar = "Hello"
5print(type(myVar))  # Output: <class 'str'>

In the above example, we first assigned an integer value to myVar and then a string value. We used Python’s built-in type() function to ascertain the data type of the value currently stored in myVar.

Assigning Multiple Variables

Python allows you to assign values to multiple variables in one line:

1x, y, z = "Apple", "Orange", "Grapes"

In this example, x will be “Apple”, y will be “Orange”, and z will be “Grapes”.

Python also enables you to assign the same value to multiple variables in one line:

1x = y = z = "Orange"

Here, all three variables (x, y, z) are assigned the value “Orange”.

Deleting Variables

In Python, you can delete a variable using the del keyword:

1myVar = 100
2print(myVar)  # Output: 100
3
4del myVar
5
6print(myVar)  # Output: NameError: name 'myVar' is not defined

In the above example, after deleting the variable myVar, when we try to print myVar, it raises a NameError because myVar is no longer defined.

To Wrap-up, understanding the concept of variables is fundamental in Python as it plays an essential role in storing data which can be manipulated through the course of your code.