Python Variables | Rules and Conventions

Variables are used in programs to store and compute your desired data. To declare variables in Python '=' is used. It is also used to assign some value to it. Unlike languages like C, C++ , JAVA where each name is "declared" in advance with its type. In Python variable typis not fixed. Variables inherit their type from their current value.

Note:  Although it is not a good programming practise to assign values of mixed types to same variable. It can lead to errors in program logic. To find the type of a variable or expression use type(e). type(e) returns the data type of expression or variable name passed as parameter.

Let's look at few examples below:

num = 1
Num = 3
Name = "Henry"
X = 8.5

Let's see how they print:

Python variables - declaration and prinitng
























Key Points:
  • num = 1 is also known as assignment statement. Left hand side is a variable name and right hand side is an expression.
  • Variable names are case-sensitive. You can clearly see that when we try to print 'x' there is an error showing that it is not defined. Hence 'x' and 'X' are two different variables.
  • There is no need to specify the type of value that the variable will hold. 
  • Numeric values can be int or float ( Integers or fractional numbers). 145, -3,471456123 are values of type int. no fractional no decimals.
  •  float having fractional or decimals.0.6, 0.3334333, 5.5
  • For an int, this sequence is read off as a binary number. int value is stored in one single cell. Int had values where decimal is fixed or no decimal.
  •  For a float, this sequence breaks up into a mantissa and exponent. float values are stored in two part one for mantissa and exponent.
  • 0.602 x 1024
  • 0.602 is mantissa and 1024 is exponent.
  • For add, sub and multiplications, if (add or sub or multi) to int number you get int and two float then you get float.
  • Division will always produce a float. 7/3.5 is 2.0. 7/2 is 3.5.
  • Python allows mix of int and float. Such as 8 + 2.5 = 10.5. Output will be float.