Posted in

Variables in Python: Concept, Classification, and Illustrative Examples

Variables in Python Concept, Classification, and Illustrative Examples

In programming, a variable can be understood as a container used to store information and reuse it in different parts of a program. In each programming language, variables have their own definitions and characteristics. Python – a language well known for its simplicity and flexibility – makes declaring, assigning, and using variables even easier.

This article will help you clearly understand what variables in Python are, how to declare and use them, naming conventions, related data types, as well as analyze their strengths and important considerations for more effective learning.

1. Concept of Variables in Python

  • A variable is a name associated with a memory location where data is stored during program execution.
  • When you assign a value to a variable, Python automatically creates that variable without requiring prior declaration of its data type.
  • The data type is inferred from the assigned value, which makes Python a dynamically typed language.
  • Each variable in Python is a name that represents a memory location. When you assign a value to a variable, Python stores that value at a specific memory address and binds the variable name to that address.
x = 9
print(id(x)) #trả về địa chỉ bộ nhớ nội bộ (memory address)

2. Variable Declaration and Assignment

Python does not require any special keywords; you simply use the following syntax:

tên_biến = giá_trị

Assigning a single variable:

  • Assigning a single variable:
age = 25
  • Assigning multiple variables in one line:
a, b, c = 1, 2, 3
  • Assigning multiple variables the same value:
x = y = z = 0

Note: The reassigned value can have a different type from the previous one.

x = 9
x = "Python"  # bây giờ x là string

3. Types of Variables in Python

In Python, variables are generally classified into several main types:

  • Global variables: Declared outside all functions, and can be accessed anywhere in the program.
x = 10  # biến toàn cục
def show():
    print(x)
show()   # In ra 10
  • Local variables: Declared inside a function and only exist within that function.
def greet():
    msg = "Hello"  # biến cục bộ
    print(msg)
greet()
# print(msg)  # lỗi, vì msg chỉ tồn tại trong hàm
  • Nonlocal variables: Used in nested functions, allowing modification of variables in the enclosing (parent) function.
def outer():
    x = "outer"
    def inner():
        nonlocal x
        x = "inner"
    inner()
    print(x)  # In ra "inner"
outer()

In addition, there are some special variables:

  • _ is used when the value is not needed (for example, in loops).
  • __name__ helps Python determine whether a file is being run directly or imported as a module.

4. Variable Naming Rules

To avoid errors and write readable code, you should follow these rules:

  • Variable names must start with a letter or an underscore (_), not a number.
  • They may contain only letters, numbers, and underscores.
  • They are case-sensitive (Age and age are two different variables).
  • They must not match Python keywords such as for, while, class, def, etc.

✅ Valid examples:

  • name, user_age, _count

❌ Invalid examples:

  • 1user, my-name, for

5. Data Types Associated with Variables

Each variable has a data type, which is inferred from its value:

  • Numbers: int, float, complex
  • Strings: str
  • Boolean: True, False
  • Data structures: list, tuple, set, dict

Important characteristics:

  • Some data types are immutable (cannot be changed): int, float, str, tuple.
  • Some data types are mutable (can be changed): list, dict, set.

Example:

fruits = ["apple", "banana"]
fruits[0] = "orange"  # list có thể thay đổi

5. Deleting Variables

Python allows you to delete a variable using the del statement:

x = 100
del x
print(x)  # Lỗi: x không tồn tại

6. Type Casting for Variables

If you want to specify the data type of a variable, you can use type casting.

x = str(9)  # x sẽ là '9'
y = int(9)  # y sẽ là 9
z = float(9)  # z sẽ là 9.0
print(x)
print(y)
print(z)

7. Getting the Type of a Variable

You can use the type() function to get the data type of a variable.

x = 9
y = "KienThucMo"
print(type(x))
print(type(y))

#kết quả
<class 'int'>
<class 'str'>

8. Constants in Python

Python does not have formally defined constants; however, you can use a naming convention with uppercase letters to indicate that a variable is a constant and its value should not be changed.

PI = 3.14159
GRAVITY = 9.8

9. Common Errors

  • Using a variable that has not been assigned a value:
print(y)  # lỗi NameError
  • Assign duplicate keyword variables:
def = 10  # lỗi SyntaxError
  • Perform operations between incompatible types:
result = "age: " + 25  # lỗi TypeError

Conclusion

Variables in Python are a fundamental yet extremely important concept. You need to clearly understand:

  • How to declare and assign variables.
  • Standard naming conventions.
  • The differences between data types (mutable vs immutable).
  • Common errors and how to avoid them.

Understanding and using variables correctly will help you write cleaner, more efficient, and more maintainable code.

References

  1. Python Software Foundation. (2024). The Python Tutorial: Using Python as a Calculator. Retrieved from https://docs.python.org/3/tutorial/introduction.html#using-python-as-a-calculator
  2. W3Schools. (2024). Python Variables. Retrieved from https://www.w3schools.com/python/python_variables.asp
  3. Real Python. (2024). Python Scope & the LEGB Rule: Resolving Names in Your Code. Retrieved from https://realpython.com/python-scope-legb-rule/
  4. GeeksforGeeks. (2024). Python Variables. Retrieved from https://www.geeksforgeeks.org/python-variables/
  5. Python for Professionals: Learning Python as a Second Language: https://www.kobo.com/us/en/ebook/python-for-professionals-3
  6. Python: Deeper Insights into Machine Learning: https://www.kobo.com/us/en/ebook/python-deeper-insights-into-machine-learning
  7. DataFusion Python Bindings in Practice: The Complete Guide for Developers and Engineers: https://www.kobo.com/us/en/ebook/datafusion-python-bindings-in-practice

Leave a Reply

Your email address will not be published. Required fields are marked *