Python : Variables

In Python, variables are used to store data values. They act as named containers that hold a value, which can be of any data type, such as numbers, strings, booleans, or more complex objects. Here's a guide to working with variables in Python:

Variable Assignment:
To assign a value to a variable, you use the assignment operator (`=`). You don't need to declare the variable type explicitly; Python infers it based on the assigned value.


x = 5         # Assign the integer value 5 to the variable x
name = "Alice"    # Assign the string value "Alice" to the variable name
is_cool = True    # Assign the boolean value True to the variable is_cool

 

Variable Naming Rules:

  • Variable names can contain letters (both uppercase and lowercase), numbers, and underscores.
  • They must start with a letter or an underscore.
  • Variable names are case-sensitive, so `age` and `Age` are considered different variables.
  • Avoid using reserved keywords like `if`, `for`, `while`, etc., as variable names.

 

Variable Reassignment:
You can change the value of a variable by assigning a new value to it.


x = 5        # Assign the value 5 to x
x = 10       # Reassign the value 10 to x

 

Variable Types:
Python variables are dynamically typed, which means you can assign values of different types to the same variable.


x = 5        # Assign an integer value to x
x = "Hello"  # Reassign a string value to x
x = True     # Reassign a boolean value to x

 

Variable Usage:
You can use variables in expressions, print statements, function calls, and more.


x = 5
y = 10
result = x + y   # Use variables in an expression

print("The value of x is:", x)   # Use variables in print statements

def greet(name):
    print("Hello, " + name)

greet("Alice")   # Use variables as function arguments
 

Multiple Variable Assignment:
You can assign values to multiple variables in a single line using a comma-separated list.


x, y, z = 1, 2, 3    # Assign 1 to x, 2 to y, and 3 to z
name1 = name2 = "Alice"   # Assign the same value "Alice" to name1 and name2

 

Using variables helps make your code more flexible and reusable. You can manipulate and operate on the values stored in variables, allowing you to write more dynamic programs.