Variables in Python

Variables in Python are fundamental components used for storing and manipulating data. They act as symbolic names or labels for values in your program. Variables allow you to work with data in a more dynamic and flexible manner. Here's a detailed explanation of variables :


1. Variable Assignment:

In Python, you create a variable by assigning a value to it using the assignment operator (=). The variable name is on the left side, and the value you want to store is on the right side. For example:

age = 25

name = "John"


2. Data Types:

Variables can store various types of data, including integers, floats, strings, lists, dictionaries, and more. Python is dynamically typed, which means you don't need to explicitly declare the data type of a variable. The interpreter determines the data type based on the assigned value.

age = 25            # Integer

height = 6.2        # Float

name = "John"       # String

scores = [90, 85]   # List


3. Variable Names:

Variable names, also known as identifiers, follow certain rules and conventions:

  • Must start with a letter (a-z, A-Z) or underscore (_): Variable names can't start with a digit or special character (e.g., 1value or @name are invalid).
  • Can contain letters, numbers, and underscores: Variable names can contain alphanumeric characters and underscores. For example, age_1, student_name, or total_score are valid.
  • Case-sensitive: Variable names are case-sensitive, meaning myVar and myvar are considered different variables.
  • Cannot be a Python keyword: You can't use Python reserved words (keywords) as variable names. For example, you can't name a variable if, while, or for.


4. Naming Conventions:

While Python's naming rules are flexible, it's important to follow naming conventions for readability and maintainability. Here are some commonly used naming conventions:

  • Snake_case: Use lowercase letters and underscores to separate words in variable names. This convention is typically used for variable names, function names, and module names (e.g., my_variable, calculate_total).
  • CamelCase: Capitalize the first letter of each word except the first one and use no spaces or underscores. This convention is often used for class names (e.g., MyClass, calculateTotal).
  • UPPER_CASE: Use all uppercase letters and underscores to separate words in variable names when defining constants (e.g., PI, MAX_VALUE).



5. Reassigning Variables:

You can change the value of a variable by simply assigning a new value to it. The variable will now reference the new value.

age 25

age = 30 # Reassigning the variable

 

6. Deleting Variables:

You can also delete a variable using the del statement. After deleting, the variable will no longer exist.

age 25

del age # Deletes the variable age

Post a Comment

Previous Post Next Post