Understanding Variables

What is a Variable?

A variable is like a container that holds information you want to use in your program. You can give it a name and store a value inside it.

Think of it as a labeled box where you can keep things like numbers, words, or other data.


Creating Variables

To create a variable in Python, follow these steps:

Examples:

# Creating variables

name = "Alice"  # A string

age = 12        # An integer

height = 5.4    # A float (decimal number)


print(name)  # Output: Alice

print(age)   # Output: 12

print(height)  # Output: 5.4



Rules for Naming Variables


Using Variables

Once you create a variable, you can use it in your program. You can print it, perform calculations with it, or combine it with other variables.

Examples:

# Using variables

x = 5

y = 10

sum = x + y

print(sum)  

# Output: 15


greeting = "Hello"

name = "Alice"

message = greeting + ", " + name + "!"

print(message)  

# Output: Hello, Alice!



Updating Variables

You can change the value stored in a variable at any time by assigning a new value.

Examples:

# Updating variables

score = 0

print(score) 

 # Output: 0


# Updating the value

score = score + 10

print(score)  

# Output: 10



Practice Exercises







Why are Variables Important?

Variables make your code reusable and flexible. Instead of writing the same value multiple times, you can just use the variable name. This makes your code easier to read and update.


Challenge Yourself!

Try creating a program where you:

Example Code:

name = "Alice"

age = 12

hobby = "painting"


print(f"Hi, my name is {name}. I am {age} years old and I love {hobby}.")


Notice how in the example above, we have used an f-string inside a print( ) method to print a string. 

We use curly braces to use a variable value inside f-strings.

Conclusion

Variables are the building blocks of programming. Practice creating, using, and updating variables to become a pro!