Chapter 2: Variables, Data Types, and Basic Operations
Welcome back, future Pythonista! In Chapter 1, we got Python up and running (specifically, the latest stable version, Python 3.14.1, as of December 2, 2025 – pretty cool, right?) and learned how to make our programs say “Hello!” using the print() function. That was just a taste, though. To really make our programs do useful things, we need a way to store information and manipulate it.
That’s exactly what this chapter is all about! We’re diving into the fundamental building blocks of almost any program: variables, data types, and basic operations. Think of it like learning the nouns, adjectives, and simple verbs of the Python language. By the end of this chapter, you’ll be able to store different kinds of information, perform calculations, and combine text in meaningful ways. Get ready to level up your coding skills!
2.1 What Are Variables? (The Labeled Boxes of Code)
Imagine you’re packing for a trip. You have clothes, toiletries, books, and snacks. Instead of just throwing everything into one big pile, you use different bags or containers and label them: “Clothes,” “Toiletries,” “Books.” This keeps everything organized and easy to find, right?
In programming, variables are exactly like those labeled containers. They are names you give to memory locations to store data. When you want to use that data later, you just refer to its label (the variable name).
How to Create a Variable in Python
Creating a variable in Python is super straightforward. You simply choose a name, use the = (assignment) operator, and then provide the value you want to store.
# This is a variable named 'my_age' storing the number 30
my_age = 30
See? No fancy declare keyword or type specification needed! Python is smart; it figures out the type of data you’re storing automatically. This is called dynamic typing.
Variable Naming Rules & Best Practices (PEP 8 Friendly!)
Just like you wouldn’t label all your boxes “Stuff,” there are some rules and best practices for naming variables in Python, following the PEP 8 style guide (which is the official style guide for Python code):
- Start with a letter or an underscore (
_):my_variable,_internal_varare valid.1st_variableis NOT valid. - Contain only letters, numbers, and underscores:
user_name,score_2,total_countare valid.user-nameis NOT valid (hyphens are used for subtraction). - Case-sensitive:
my_variableis different fromMy_Variable. - Descriptive names: Choose names that clearly indicate what the variable holds (e.g.,
user_nameinstead ofx). - Snake case for multiple words: Use underscores to separate words (e.g.,
total_score,first_name). This is the Pythonic way!
Let’s start by creating a new Python file. Open your code editor (like VS Code) and create a file named chapter_2_code.py.
Now, let’s put some variables into action!
# chapter_2_code.py
# Step 1: Create your first variable
# We're storing the number 25 in a variable named 'current_year'
current_year = 2025
# Step 2: Create another variable to store your name (or any name!)
# Text data needs to be enclosed in single or double quotes
my_name = "Alice"
# Step 3: Let's print them out!
# We'll use an f-string (formatted string literal) for a nice output.
# F-strings are a modern (Python 3.6+) and very readable way to embed variables directly into strings.
print(f"The current year is {current_year}.")
print(f"My name is {my_name}.")
Run this code! Save your chapter_2_code.py file and run it from your terminal:
python chapter_2_code.py
You should see:
The current year is 2025.
My name is Alice.
Great job! You’ve just created and used your first variables.
2.2 Data Types (The Kinds of Information)
Not all information is the same, right? A number like 30 is different from text like "Hello", and both are different from a true/false statement. Python, like other programming languages, categorizes data into data types. Knowing these types is crucial because different types behave differently and have different operations you can perform on them.
Python automatically determines the type, but it’s good for you to understand them!
Common Python Data Types:
Integers (
int): Whole numbers, positive or negative, without a decimal point.- Examples:
5,-100,0,12345
- Examples:
Floating-Point Numbers (
float): Numbers with a decimal point.- Examples:
3.14,-0.5,100.0,2.71828
- Examples:
Strings (
str): Sequences of characters (text). They are always enclosed in single quotes ('...'), double quotes ("..."), or triple quotes ('''...'''or"""...""") for multi-line strings.- Examples:
"Hello, Python!",'2025',"This is a sentence."
- Examples:
Booleans (
bool): Represent one of two values:TrueorFalse. Used for logical operations and conditional checks. Notice the capitalTandF!- Examples:
True,False
- Examples:
Checking a Variable’s Type
Python provides a built-in function called type() that tells you the data type of any variable or value. This is super handy for understanding what’s going on under the hood.
Let’s extend our chapter_2_code.py file to explore data types:
# chapter_2_code.py
# ... (previous code) ...
print("\n--- Exploring Data Types ---")
# Integer
age = 30
print(f"age: {age}, type: {type(age)}")
# Float
price = 19.99
print(f"price: {price}, type: {type(price)}")
# String
city = "New York"
print(f"city: {city}, type: {type(city)}")
# Boolean
is_student = True
print(f"is_student: {is_student}, type: {type(is_student)}")
# What about a number as a string?
zip_code = "90210"
print(f"zip_code: {zip_code}, type: {type(zip_code)}")
Observe the output when you run this code. You’ll see <class 'int'>, <class 'float'>, etc., confirming Python’s recognition of these types. Notice how zip_code is a string, even though it looks like a number, because it’s enclosed in quotes! This distinction is crucial.
2.3 Basic Operations (Making Things Happen!)
Now that we can store different kinds of data, let’s learn how to do things with them. Python provides operators for performing calculations with numbers and manipulating strings.
2.3.1 Arithmetic Operators (Math Time!)
These are what you’d expect for numbers:
+: Addition-: Subtraction*: Multiplication/: Division (always returns a float, even if the result is a whole number)//: Floor Division (divides and rounds down to the nearest whole number, returning an integer)%: Modulo (returns the remainder of a division)**: Exponentiation (raises a number to a power)
Let’s add some arithmetic to our chapter_2_code.py:
# chapter_2_code.py
# ... (previous code) ...
print("\n--- Arithmetic Operations ---")
num1 = 10
num2 = 3
print(f"Numbers: num1 = {num1}, num2 = {num2}")
# Addition
sum_result = num1 + num2
print(f"Addition ({num1} + {num2}): {sum_result}")
# Subtraction
difference = num1 - num2
print(f"Subtraction ({num1} - {num2}): {difference}")
# Multiplication
product = num1 * num2
print(f"Multiplication ({num1} * {num2}): {product}")
# Division (float result)
quotient_float = num1 / num2
print(f"Division ({num1} / {num2}): {quotient_float}") # Expected: 3.333...
# Floor Division (integer result)
quotient_floor = num1 // num2
print(f"Floor Division ({num1} // {num2}): {quotient_floor}") # Expected: 3
# Modulo (remainder)
remainder = num1 % num2
print(f"Modulo ({num1} % {num2}): {remainder}") # Expected: 1 (10 divided by 3 is 3 with remainder 1)
# Exponentiation
power_result = num1 ** num2 # 10 to the power of 3
print(f"Exponentiation ({num1} ** {num2}): {power_result}") # Expected: 1000
Run your file and check the results. Pay close attention to the difference between / and // – it’s a common point of confusion for beginners!
2.3.2 String Operations (Playing with Text)
Strings aren’t just for displaying text; you can manipulate them too! The most common operations are concatenation (joining strings) and repetition.
+: Concatenation (joins two or more strings together)*: Repetition (repeats a string a specified number of times)
Let’s add these to our file:
# chapter_2_code.py
# ... (previous code) ...
print("\n--- String Operations ---")
first_name = "Ada"
last_name = "Lovelace"
greeting = "Hello"
# Concatenation
full_name = first_name + " " + last_name # We add a space in between
message = greeting + ", " + full_name + "!"
print(f"Full name: {full_name}")
print(f"Message: {message}")
# Repetition
cheer = "Go! "
repeated_cheer = cheer * 3
print(f"Repeated cheer: {repeated_cheer}") # Expected: Go! Go! Go!
Run this section. Notice how we use + to combine strings and * to repeat them. Pretty neat, right?
2.3.3 Type Conversion (Casting)
What if you have a number stored as a string ("123") but you want to perform math on it? Or you have a float (3.14) but only care about the whole number part? This is where type conversion (often called “casting”) comes in handy.
Python provides built-in functions to convert data from one type to another:
int(value): Convertsvalueto an integer. If it’s a float, it truncates (chops off the decimal part). If it’s a string, the string must represent a whole number.float(value): Convertsvalueto a float.str(value): Convertsvalueto a string.
Why is this important? A common scenario is when you get input from the user. Python’s input() function (which we’ll use in our challenge!) always returns a string. If you ask for a number, you’ll need to convert it before you can do math with it!
Let’s add type conversion examples:
# chapter_2_code.py
# ... (previous code) ...
print("\n--- Type Conversion (Casting) ---")
# String to Integer
string_number = "42"
print(f"Original string_number: '{string_number}', type: {type(string_number)}")
integer_number = int(string_number)
print(f"Converted integer_number: {integer_number}, type: {type(integer_number)}")
print(f"Performing math after conversion: {integer_number + 8}")
# Float to Integer (truncates decimal)
decimal_value = 7.89
print(f"\nOriginal decimal_value: {decimal_value}, type: {type(decimal_value)}")
whole_number = int(decimal_value)
print(f"Converted whole_number: {whole_number}, type: {type(whole_number)}") # Notice the .89 is gone!
# Integer to Float
my_int = 100
print(f"\nOriginal my_int: {my_int}, type: {type(my_int)}")
my_float = float(my_int)
print(f"Converted my_float: {my_float}, type: {type(my_float)}") # Notice the .0 added
# Number to String
calculated_result = 500
print(f"\nOriginal calculated_result: {calculated_result}, type: {type(calculated_result)}")
result_message = "The answer is: " + str(calculated_result)
print(f"Converted result_message: '{result_message}', type: {type(result_message)}")
Run this final section of chapter_2_code.py. You’ll clearly see how types change and why it’s necessary for certain operations.
2.4 Mini-Challenge: Your Personal Greeter!
Alright, time to put your new knowledge to the test!
Challenge: You’re going to create a small Python program that acts as a personal greeter.
- Ask the user for their name using the
input()function. - Ask the user for their favorite whole number.
- Convert their favorite number from a string to an integer.
- Multiply their favorite number by 5.
- Print a personalized greeting that includes their name and the result of the multiplication.
Example interaction:
What is your name? [User types: Sarah]
What is your favorite whole number? [User types: 7]
Hello, Sarah! Your favorite number multiplied by 5 is 35.
Take a moment, try to solve this on your own. Remember to use input() and the type conversion functions we just learned!
Hint (Click to reveal if you're stuck!)
Remember that input() always returns a string. If you want to perform math on the user's favorite number, you *must* convert it to an integer using int() first!
What to Observe/Learn:
- How
input()works to get information from the user. - The critical need for type conversion when mixing strings from
input()with numerical operations. - Combining string concatenation and f-strings for dynamic messages.
Here’s a possible solution once you’ve given it a good try:
# Mini-Challenge Solution
print("\n--- Mini-Challenge: Your Personal Greeter ---")
# 1. Ask for the user's name
user_name = input("What is your name? ")
# 2. Ask for their favorite whole number
fav_number_str = input("What is your favorite whole number? ")
# 3. Convert the favorite number to an integer
# This step is CRUCIAL for math operations!
fav_number_int = int(fav_number_str)
# 4. Multiply their favorite number by 5
multiplied_number = fav_number_int * 5
# 5. Print a personalized greeting
print(f"Hello, {user_name}! Your favorite number multiplied by 5 is {multiplied_number}.")
2.5 Common Pitfalls & Troubleshooting
Even experienced programmers make mistakes! Here are a few common issues you might encounter and how to deal with them:
TypeError: can only concatenate str (not "int") to str:- What it means: You’re trying to combine a string and a number (or another non-string type) directly using the
+operator. Remember,+for strings means concatenation, but for numbers, it means addition. Python gets confused when you mix them! - Example:
print("Your score is: " + 100) - Solution: Convert the number to a string first using
str(), or better yet, use an f-string!print("Your score is: " + str(100))print(f"Your score is: {100}")(Recommended modern practice)
- What it means: You’re trying to combine a string and a number (or another non-string type) directly using the
NameError: name 'some_variable' is not defined:- What it means: Python can’t find a variable with the name you used. This usually happens for one of three reasons:
- Typo: You misspelled the variable name (e.g.,
my_namevsmy_nam). - Not assigned: You tried to use a variable before you gave it a value.
- Scope issue: The variable was defined inside a specific block of code (like a function, which we’ll learn later) and you’re trying to access it outside that block.
- Typo: You misspelled the variable name (e.g.,
- Solution: Double-check your spelling, ensure the variable is assigned a value before it’s used, and review where the variable was defined.
- What it means: Python can’t find a variable with the name you used. This usually happens for one of three reasons:
Forgetting to convert
input()to a number:- What it means: You asked the user for a number, but
input()returned a string. If you try to do math with that string, you’ll get aTypeError(like the first one above, but often specific to the math operation). - Example:
num_str = input("Enter a number: ") # num_str is "5" result = num_str + 10 # This will cause an error! - Solution: Always convert
input()results toint()orfloat()if you intend to perform numerical operations.num_str = input("Enter a number: ") num_int = int(num_str) # Convert to integer result = num_int + 10 # Now it works!
- What it means: You asked the user for a number, but
2.6 Summary
Phew! You’ve covered a lot of ground in this chapter. Let’s recap the essential takeaways:
- Variables are named containers for storing data in your programs.
- Python uses dynamic typing, meaning you don’t explicitly declare a variable’s type; Python figures it out.
- Key data types include:
int(whole numbers)float(decimal numbers)str(text, enclosed in quotes)bool(True/False)
- You can check a variable’s type using the
type()function. - Basic operations allow you to manipulate data:
- Arithmetic operators (
+,-,*,/,//,%,**) for numbers. - String operators (
+for concatenation,*for repetition) for text.
- Arithmetic operators (
- Type conversion (casting) functions like
int(),float(), andstr()are vital for changing data from one type to another, especially when dealing with user input. - Always remember that
input()returns a string, so convert it if you need a number!
You’re now equipped to store, categorize, and perform basic actions on data in your Python programs. This is a massive step towards writing more interactive and functional code!
In the next chapter, we’ll learn how to make our programs smart enough to make decisions using conditional statements. Get ready to add some logic to your code!