Python Variables And example

aimtocode

Variable Definition

A variable is a name and a way of referring the memory location of a value used by a computer program.

This means that when you create a variable you reserve some space in memeory. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory.

A variable is a symbolic name for this physical location. This memory location contains values, like numbers, text or more complicated types.

We do not need to declare variables before using them, or declare their type. A variable is created the moment we first assign a value to it.

A variable is a good way to store information while making it easy to refer to that information in our code later.


Rules for Variables

  • The first character of the variable must be an alphabet or underscore ( _ ).
  • All the characters except the first character may be an alphabet of lower-case(a-z), upper-case (A-Z), underscore or digit (0-9).
  • Variable/Identifier name must not contain any white-space, or special characters such as (!, @, #, %, ^, &, *).
  • Variable/Identifier name must not be similar to any keyword defined in the language.
  • Variable/Identifier names are case sensitive for example hello world, and HelloWorld are not the same.
  • Examples of valid identifiers : a123, _n, n_9, etc.
  • Examples of invalid identifiers: 1a, n%4, n 9, etc.

Example:



Output:

 10
 15
 20

Multiple Assignment



Output:

 10
 10
 10

Assign Value to Multiple Variables



Output:

 Prayag
 Verma
 aimtocode

Global Variables

Global variable in Python is a variable that can be used globally anywhere in the program. It can be used in any function ormodule, and even outside the functions, without having to re-declare it.



Output:

 
 Welcome to Python 


Local Variable

A variable that is declared inside a python function or a module can only be used in that specific function or Python Module.

The global variable with the same name will remain as it was, global and with the original value.


Example:



Output:

 I am Local variable
 I am Global Variable
aimtocode