Python Variables

A variable is a location in memory used to store some data (value). They are given unique names to differentiate between different memory locations. The rules for writing a variable name is same as the rules for writing identifiers in Python.
We don't need to declare a variable before using it. In Python, we simply assign a value to a variable and it will exist. We don't even have to declare the type of the variable. This is handled internally according to the type of value we assign to the variable.

Variable assignment

We use the assignment operator (=) to assign values to a variable. Any type of value can be assigned to any valid variable.

a = 5
b = 3.2
c = "Hello"
Here, we have three assignment statements. 5 is an integer assigned to the variable a. Similarly, 3.2 is a floating point number and "Hello" is a string (sequence of characters) assigned to the variables b and c respectively.

Multiple assignments

In Python, multiple assignments can be made in a single statement as follows:

a, b, c = 5, 3.2, "Hello"
If we want to assign the same value to multiple variables at once, we can do this as

x = y = z = "same"
This assigns the "same" string to all the three variables.

No comments:

Post a Comment