Variables

When starting with the basics of Python, the first thing to understand is Python variables. We’ve been running some basic codes in the introduction section, but when you’re getting deep into Python, you need to declare variables.

In Python, a variable is a named location used to store data in the memory. It acts as a container for storing data values. Every value needs some location, and by declaring a variable, you’re securing that position for that value. You do not need to declare the variable type in Python.

Rules of declaring a variable

  1. The first character of the variable should not consist of digits or special characters.

  2. The variable name must start with an alphabet or underscore.

  Example:

  Valid: _color12, color12_, color_12

  Invalid: 1color

  1. A variable name can consist of numbers from 0-9, alphabets (lowercase and uppercase), and the underscore character.

  2. Python keywords like Boolean True, and, or, and if, etc., cannot be used as variable names.

  3. The variables are case-sensitive. For example, color, COLOR, and color_ are three different variables.

Types of variables

  • Local variables: A local variable is declared inside a function or block and can only be accessed within that function or block. The lifetime of a local variable extends as long as the function is executing, and it gets destroyed once the function call is completed.

  • Global variables: A global variable is declared outside any function or block and can be accessed from any part of the program. The lifetime of a global variable spans the entire runtime of the program.