Python: How to Declare a Variable

Ilyas Mukhlisin
2 min readJan 18, 2025

--

Declaring a variable in Python is simple and does not require specifying its type, thanks to Python’s dynamic typing. Here’s everything you need to know about declaring variables in Python.

How to Declare a Variable

In Python, you declare a variable by assigning a value to a name using the equals sign (=). There is no need to use keywords like var, int, or string. Python automatically determines the variable's type based on the value assigned.

# Examples of variable declarations
x = 10 # An integer variable
name = "Mukhlis" # A string variable
pi = 3.14 # A float variable
is_active = True # A boolean variable

In this example:

  • x is an integer.
  • name is a string.
  • pi is a float.
  • is_active is a boolean.

Variable Naming Rules

When declaring a variable, you should follow these rules:

  1. Variable names must start with a letter or an underscore (_).
  2. They cannot start with a number.
  3. Names can only contain letters, numbers, and underscores.
  4. Variable names are case-sensitive (Name and name are different variables).
# Valid variable names
_age = 25
user_name = "Ahmad"
totalScore = 100

# Invalid variable names
2user = "Budi" # Cannot start with a number
user-name = "Beni" # Hyphens are not allowed

Reassigning Variables

In Python, you can reassign variables to values of different types without any error. This is because Python is dynamically typed.

x = 10
x = "Hello" # Now x is a string
print(x) # Output: Hello

Declaring Multiple Variables

You can declare and assign values to multiple variables in one line.

a, b, c = 1, 2, 3  # Assign different values to multiple variables
x = y = z = 0 # Assign the same value to multiple variables

Constants in Python

Python does not have built-in support for constants, but you can indicate a variable is a constant by using all uppercase letters.

PI = 3.14159
MAX_USERS = 100

Though these are not enforced by Python, it’s a convention used by developers to signify that the value shouldn’t be changed.

Conclusion

Declaring a variable in Python is straightforward — just assign a value to a name. Remember to follow the naming rules and conventions for clarity and maintainability. Python’s simplicity in handling variables makes it beginner-friendly while still being powerful for complex applications.

--

--

Ilyas Mukhlisin
Ilyas Mukhlisin

Written by Ilyas Mukhlisin

just a beginner who wants to learn programming and share knowledge

No responses yet