Chapter 2: Variables and Data Types

In the first chapter, we learned how to output text to the screen. Now, we move to the heart of programming: storing and manipulating data. To create useful programs, we need to remember information, and we do this using Variables.

What is a Variable?

Think of a variable as a labeled box in your computer's memory. You put a piece of data into the box and give it a name (the label). Later, you can refer to that name to see what is inside the box. In Python, creating a variable is incredibly simple—you don't even need to tell Python what kind of data is in the box!

user_name = "Alex"
age = 25

Here, user_name and age are variables. The equals sign (=) is called the assignment operator; it tells Python to store the value on the right into the variable name on the left.

Core Data Types

Python categorizes data into different "types." Understanding these is crucial for writing bug-free code.

Why Type Matters

You cannot perform mathematical operations on all data types. For example, you can multiply two integers to get a larger number, but if you try to multiply a string by another string, Python will show an error. However, Python allows "string multiplication" by an integer, which repeats the string.

print("Ha" * 3)  # This outputs: HaHaHa

Type Casting

Sometimes you need to convert data from one type to another. This is called Type Casting. If you receive user input (which always comes in as a string), you must convert it to an integer before you can perform math on it.

age_string = "25"
age_int = int(age_string)
print(age_int + 5)  # Results in 30

Common Beginner Mistakes

Try It Yourself

  1. Create three variables: one integer, one float, and one string.
  2. Use the print() function to display them.
  3. Try to add your string variable to your integer variable and observe the error message.

Converting Between Types

Sometimes you need to convert a value from one type to another — this is called type casting. Python makes this easy with built-in functions like int(), float(), and str().

age_text = "25"
age_number = int(age_text)   # converts string to integer
print(age_number + 5)         # 30

price = 19.99
print(str(price) + " dollars")  # converts number to string

Trying to convert something that isn't a valid number, like int("hello"), will raise a ValueError, so always be sure the data actually looks like a number before converting it.

Naming Your Variables Well

Python variable names should be descriptive and follow the "snake_case" convention (lowercase words separated by underscores), such as total_price or user_name. Avoid vague names like x or data1 in real projects — future you will thank present you for writing monthly_salary instead of m.