Python - Variables

A variable is a name that is used to refer to reserved memory location to store values or hold the value.
Variables can be declared with by name with alphabets, digits, and underscore.

Rules to define the variable names in Python:

  • Variable name can contain any alphabetic characters (A-Z and a-z)
  • Variable name can contain digits (0-9)
  • Variable name can contain underscore “_”.
  • Variable names are case sensitive. Uppercase and lowercase letters are distinct. For example, Height and height are two different variable names.
  • Variable names can’t start with a digit. For example, address1 is a valid variable name, whereas 1address is not a valid variable name.
  • Shouldn’t use built-in function or keywords as variable names. For example, print, min, max etc., are not valid variable names.

Some examples:

Valid Invalid
Address 1address
Address Address_*
Address1 @address
Address_ 1address_
_Address ~address
_address address1_$

Creating a Variables:

A variable can be created when assign the value.

a = 2;
print(a)  # output is 2

Re-declare a variable:

A variable value can change after you have declared it again.

a = 3;
print(a)  # output is 3
a="Mike"
print(a) # output is Mike;

Multiple assignment:

Multiple variables can be assigned with same value.

a = b = c = 2;

Here, all three (a, b, and c) variables are representing the same memory location of integer object with value 2. Hence, the value of all these variables is 2.

a, b, c = 1, 2, 3;

Here, all three integer objects assign to variables a, b and c respectively.

a, b, c = “Mike”, 2, 3;

Here, one string object assign to variable a, and the two integer objects assign to variables b, c.



Related Tutorials