What is a Variable in Python?

Think of a variable as a storage box where you can keep different items. In Python, a variable allows you to store a value (like a number, a string of text, or a list of items) that you can use and manipulate in your code.

Creating Variables

Creating a variable in Python is straightforward. You just need to choose a name for your variable and then assign a value to it using the equals sign =.

greeting = "Hello, World!"
age = 25
height = 5.9

Rules for Naming Variables

When naming your variables, there are a few rules you should follow:

  1. Names can contain letters, numbers, and underscores, but they can’t start with a number.
  2. Avoid using Python’s built-in keywords (like if, for, return, etc.) as variable names.
  3. Variable names are case-sensitive (Age, age, and AGE would be three different variables).
  4. Use names that are descriptive and make your code easier to understand.

Using Variables

Once you have created your variables, you can use them in various ways. You can print their values, combine them with other variables, or use them in calculations. Here are some examples:

# Printing variables
print(greeting)  # Output: Hello, World!
print("I am", age, "years old.")  # Output: I am 25 years old.

# Using variables in calculations
next_year_age = age + 1
print("Next year, I will be", next_year_age, "years old.")  # Output: Next year, I will be 26 years old.

# Combining strings (concatenation)
welcome_message = greeting + " I am a Python program."
print(welcome_message)  # Output: Hello, World! I am a Python program.

Changing Variable Values

One of the great things about variables is that their values aren’t set in stone—you can change them as needed. Here’s how you can update the value of a variable:

# Changing the value of a variable
age = 26
print("My new age is", age)  # Output: My new age is 26

In this example, we updated the age variable from 25 to 26. You can update a variable to not only a different number but also a different type of data altogether, like changing from a number to a string.