Core Fundamentals: Variables & Data Types
7 min read
Core Fundamentals: Variables & Data Types
Welcome to the foundational concepts of Python! Before we can build amazing applications, we need to understand how to work with data. This guide will walk you through storing information and the different types of data you'll encounter.
1. Variables: Dynamic Memory Boxes for Your Data 📦
The Problem: Imagine you're building a simple game. You need to keep track of the player's score, their username, and how many lives they have left. How do you "remember" these pieces of information while the program is running? You can't just write them on a sticky note.
The Solution: Variables
A variable is a named location in memory used to store a value. Think of it like a labeled box where you can put some information. You give the box a name, and later you can look inside to see what's there, or you can replace the contents with something new.
In Python, creating a variable is as simple as choosing a name and using the equals sign (=) to assign it a value.
# variable_name = value
player_score = 100
player_name = "Alex"
lives_remaining = 3
# You can then use the variable name to access the value
print(player_name)
print(player_score)Under the Hood: When you create a variable, Python finds an empty spot in your computer's memory, stores the value (e.g., 100) there, and then attaches your chosen name (player_score) to that location like a label.
🧠 Industry Practice: Naming Conventions
How you name your variables is important for writing clean, readable code. In Python, the standard is snake_case.
- Do:
player_score,first_name,user_input. All words are lowercase and separated by underscores. - Don't:
playerScore,PlayerScore,p_score.
Naming a variable x is like labeling a moving box "stuff." You'll have no idea what it is later. Be descriptive!
Interesting Fact: Python is a dynamically typed language. This means you don't have to tell Python what type of data the variable will hold. Python figures it out automatically when you assign the value. You can even change the type later!
my_variable = 10 # Python sees this is an integer
print(my_variable)
my_variable = "Hello" # Now it's a string. No problem!
print(my_variable)2. Numbers and Math: Integers, Floats, and Operations 🔢
The Problem: Computers were originally invented to, well, compute. We need a way to work with numbers to do everything from counting inventory in an e-commerce app to calculating the trajectory of a rocket in a simulation.
The Solution: Numeric Data Types
Python has built-in data types for handling numbers. The two you'll use most often are integers and floats.
- Integers (
int): These are whole numbers, both positive and negative, without any decimal points.- Examples:
10,-35,0,15000
- Examples:
- Floats (
float): These are numbers that do have a decimal point. They are used for values that require more precision.- Examples:
3.14,-0.025,99.99
- Examples:
# An integer
player_level = 5
# A float
account_balance = 250.75Basic Math Operations
Python uses standard arithmetic operators that you're already familiar with.
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 5 - 3 |
2 |
* |
Multiplication | 5 * 3 |
15 |
/ |
Division | 5 / 2 |
2.5 |
** |
Exponent | 5 ** 2 |
25 |
Two Incredibly Useful Operators: // and %
- Floor Division (
//): This operator divides and then rounds the result down to the nearest whole number. - Modulo (
%): This operator gives you the remainder of a division.
Real-world Scenario: Let's say you have 77 eggs and you want to put them into cartons that hold 12 eggs each.
total_eggs = 77
carton_size = 12
# How many full cartons can we make?
full_cartons = total_eggs // carton_size
print(f"Full cartons: {full_cartons}") # Output: Full cartons: 6
# How many eggs will be left over?
leftover_eggs = total_eggs % carton_size
print(f"Leftover eggs: {leftover_eggs}") # Output: Leftover eggs: 53. Strings: Working with Text and Formatting 📝
The Problem: Our programs need to communicate with humans, and that means working with text. We need to store names, display messages, and create reports. How do we handle textual data?
The Solution: Strings (str)
A string is a sequence of characters enclosed in quotes. You can use either single quotes (') or double quotes (").
greeting = "Hello, World!"
user_name = 'freecodecamper'Combining Strings (Concatenation)
You can "add" strings together using the + operator.
first_name = "Ada"
last_name = "Lovelace"
full_name = first_name + " " + last_name
print(full_name) # Output: Ada Lovelace🧠 Industry Standard: F-Strings are Your Friend
While using + works, it can become messy. The modern, preferred way to format strings in Python is with Formatted String Literals, or f-strings.
Start the string with the letter f before the quotes, and then you can place your variables directly inside curly braces {}.
item = "coffee"
price = 3.50
# The old way
message_old = "The price of the " + item + " is " + str(price) + "."
# The new, better way with f-strings
message_new = f"The price of the {item} is {price}."
print(message_new) # Output: The price of the coffee is 3.5.It's cleaner, easier to read, and less prone to errors. Use them!
Common String Methods
A "method" is like an action you can perform on your data. Strings have many useful built-in methods. Here are a few you'll use constantly:
.upper(): Converts the string to all uppercase..lower(): Converts the string to all lowercase..strip(): Removes any whitespace (spaces, tabs, newlines) from the beginning and end.
user_input = " LoGiN "
clean_input = user_input.strip().lower()
print(f"'{user_input}' becomes '{clean_input}'")
# Output: ' LoGiN ' becomes 'login'4. Booleans and Type Conversion ✅❌
The Problem: How does a program make a decision? For example, how does a game know if the "game over" screen should be displayed? Also, what happens if you get a number from a user, but it's given to you as text?
The Solution: Booleans (bool)
The boolean data type is simple but powerful. It can only have one of two values: True or False. They are the foundation of logic and decision-making in your code.
is_game_over = False
has_premium_access = TrueThe Solution: Type Conversion (Casting)
Sometimes you have data in one type, but you need it in another. For example, the input() function in Python always gives you a string, even if the user types a number.
Trying to do math with a string will cause an error.
user_age_string = "30"
# This will cause a TypeError!
# print(user_age_string + 5)To fix this, you must explicitly convert the type. This is called type casting.
int(): Converts a value to an integer.float(): Converts a value to a float.str(): Converts a value to a string.
user_age_string = "30"
# Convert the string to an integer before doing math
user_age_number = int(user_age_string)
print(user_age_number + 5) # Output: 35You can also convert numbers to strings, which is useful when you want to join them with other text without using an f-string.
item_count = 10
message = "You have " + str(item_count) + " items in your cart."
print(message) # Output: You have 10 items in your cart.References for Extra Reading
- Official Python Documentation on Built-in Types: docs.python.org/3/library/stdtypes.html
- Official Documentation on Numeric Types: docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex
- Documentation on String Formatting (f-strings and
.format()): docs.python.org/3/library/string.html#format-string-syntax - Mathematical Functions (
mathmodule): docs.python.org/3/library/math.html
Challenge
Challenge: E-commerce Receipt Calculator
You are tasked with writing a Python script to calculate the final cost of an online order and generate a formatted receipt string. You will be given several initial variables representing the item details and business rules.
Your goal is to perform the necessary calculations and store the results in new variables, ultimately producing a formatted summary string.
Requirements:
- Convert the
item_base_price_strinto a floating-point number and store it in a new variable. - Calculate the subtotal (item price * quantity) before any taxes or discounts are applied.
- Calculate the total sales tax amount. The tax is calculated on the subtotal. Remember that the given tax rate is a percentage.
- Calculate the discount amount. The discount is also calculated on the subtotal. Crucially, the discount should only be applied if the
is_membervariable isTrue. Ifis_memberisFalse, the discount amount should be0.0. - Calculate the final total cost for the customer (subtotal + tax - discount).
- Store each of the calculated values (subtotal, tax amount, discount amount, and final total) in its own separate, descriptively named variable using
snake_case. - Using an f-string, create a final multi-line string assigned to a variable named
order_summarythat presents all the details of the transaction.
Expected result
Your script should correctly define and populate the following variables:
- A variable to hold the floating-point representation of the item's price.
subtotal: The total cost before tax and discounts.tax_amount: The calculated tax based on the subtotal.discount_amount: The calculated discount. This should be0.0ifis_memberisFalse.final_total: The final calculated price.order_summary: A multi-line f-string that formats the results clearly. The output string should look similar to this structure, with the calculated values embedded:
--- Order Summary ---
Item: Quantum Widget
Quantity: 7
Subtotal: $139.93
Discount: -$20.99
Tax: +$11.20
---------------------
Total: $130.14