Python Variable

A Python variable is a name that refers to a value or object in memory. Variables are used to store data that can be manipulated or referenced throughout a program. In Python, you can assign values to variables without explicitly declaring their data types (Python is dynamically typed), and the type is inferred from the value assigned.

When you run an assignment statement such as a = 3 in Python, it works even if you’ve never told Python to use the name a as a variable or that a should stand for an integer-type object.

 Variable types: A variable never has any type information or constraints associated with it. The notion of type lives with objects, not names. Variables are generic in nature; they always simply refer to a particular object at a specific point in time.

Variable Assignment

In Python, you can create a variable by simply assigning a value to it using the = operator.

Example:


x = 20          # Assigns integer 20 to variable x
name = "John"  # Assigns string "John" to variable name
pi = 3.14       # Assigns floating-point number 3.14 to variable pi

Rules for Naming Variables

1. Variable names must start with a letter (a-z, A-Z) or an underscore _.

2. They can contain letters, digits (0-9), and underscores.

3. Variable names are case-sensitive (name, Name, and NAME are different variables).

4. Python reserved keywords (such as if, while, for, etc.) cannot be used as variable names.

Example:


age = 38 # Integer variable
height = 6.2  # Float variable
is_employee = True  # Boolean variable
greeting = "Hello, Friends!"  # String variable

Reassigning Variables

Variables can be reassigned to new values at any time. Since Python is dynamically typed, the type of a variable can also change when reassigned.


x = 10      # x is an integer
x = "Hello!"  # Now x is a string

Variables are essential for storing and manipulating data in Python programs.