No history yet

Introduction to Variables

Storing Information

Think of a variable as a labeled box where you can store information. When you write a program, you often need to remember things, like a player's score, a user's name, or the price of an item. Instead of writing that information over and over, you can store it in a variable and just refer to the label on the box.

This makes your code cleaner and easier to understand. If the information needs to change, you only have to update it in one place: inside the box.

To create a variable in Python, you give it a name and assign it a value using the equals sign (=). This process is called assignment.

player_name = "Alex"

In this example:

  • player_name is the name of the variable (the label on our box).
  • = is the assignment operator. It tells Python to put the value on the right into the variable on the left.
  • "Alex" is the value we are storing. It's a piece of text.

Python's Flexibility

One of Python's handy features is dynamic typing. This means you don't have to tell Python what kind of information you're storing. Python automatically figures it out based on the value you assign. You can store text, whole numbers, or numbers with decimals, and Python handles it for you.

# Storing text
greeting = "Hello there!"

# Storing a whole number
player_score = 100

# Storing a number with a decimal
item_price = 19.99

The name "variable" implies that its contents can vary, or change. You can update a variable by assigning it a new value. The old value is simply replaced by the new one.

# The player starts with 0 points
points = 0

# The player finds a treasure chest
points = 150

Here, the points variable first held the value 0. After the second line, it was updated to hold 150.

You can even change the type of value stored in a variable completely. A variable that once held a number can be reassigned to hold text.

current_status = 10

# Later, the status changes to a message
current_status = "Offline"

This flexibility is a core part of what makes Python easy to learn and use.