How to declare a variable in Python

Declaring a variable in Python is an easy task. Dynamically typed variables do not require an explicit declaration of their type. In Python, a variable is declared by assigning a value.

1. Variable Declaration

To declare a variable, just choose a name and assign a value to it.

x = 10  # x is a variable assigned the integer value 10

Here:

  • x is the variable name.
  • = is the assignment operator.
  • 10 is the value assigned to x.

2. Rules for Naming Variables

Python has some rules and conventions for naming variables:

  • Start with a letter or underscore (_): Variable names cannot begin with a number.
    • Valid: name, _value
    • Invalid: 1name, @value
  • Use alphanumeric characters and underscores only: Names can contain letters (A-Z, a-z), numbers (0-9), and underscores (_).
    • Valid: my_var, var123
    • Invalid: my-var, my var!
  • Case-sensitive: age and Age are treated as two different variables.
  • Avoid keywords: You cannot use keywords for the Python language (such as if, else, while) as variable names.

3. Dynamic Typing

Python infers the type of the variable based on the value assigned to it.

x = 10        # x is an integer
y = 3.14      # y is a float
name = "Alice" # name is a string
is_valid = True # is_valid is a boolean

You don’t need to declare the type explicitly, but you can always check the type of a variable using the type() function:

print(type(x))  # Output: <class 'int'>
print(type(y))  # Output: <class 'float'>

4. Changing Variable Values

You can reassign variables to values of different types at any time.

x = 10       # x is initially an integer
x = "Python" # Now x is a string

Python will automatically update the type of the variable.

5. Multiple Assignments

Python allows assigning values to multiple variables in a single line.

a, b, c = 1, 2, 3  # a=1, b=2, c=3

You can also assign the same value to multiple variables:

x = y = z = 0  # x, y, and z are all 0

6. Global and Local Variables

Variables declared outside any function are global and can be accessed anywhere in the script. Variables declared inside a function are local and accessible only within that function.

Example:

x = 10  # Global variable

def my_function():
    y = 5  # Local variable
    print(x)  # Access global variable
    print(y)

my_function()
# Output: 
# 10
# 5

Attempting to access y outside my_function() will result in an error.

7. Constants

Python doesn’t have built-in constant support, but by convention, you can use uppercase names to indicate a variable is a constant.

PI = 3.14159  # A constant (by convention)