Python Variables

Variables are the names given to memory locations used in our program. There are some rules that we must follow to create a valid variable name –

  • Variable name must start with a letter(a-z) or underscore(_) and not a number(0-9).
  • Variable name should not contain any white spaces or blank space.
  • Variable name cannot be a keyword like if, else, while, for, etc.
  • No special character except underscore(_) is allowed.

Variable in python don’t need data type declaration as int, float or char as was expected in C and C++. In python the moment we assign a value to the variable it gets created in our program. For example in below mentioned code x and y are created the moment we assign them 5 and variable respectively, No need to specify the data type.

In cases where we are assigning string to a variable, we can use both double as well as single quotes, its totally fine no error will be generated as demonstrated in below mentioned code.

When we try to assign different values to the same variables, Only the last assignment is considered as demonstrated below, the value of x will be ‘variable and not ‘5’.

We can perform casting during assigning a value to a variables as demonstrated below

Accordingly the results are generated as for int its ‘5’ and for float its ‘5.0’.

If you want to know about the type of a variable, just use type(variable_name) method.

Case Sensitivity exists in python as demonstrated below x=5 and X=done both are treated a different.

Leave a Reply

Your email address will not be published. Required fields are marked *