Python: lesson 1 of 7
Python
Variables in Python
Learn how to name, assign, and safely reuse values in Data Science Python code.
Concept
A variable is a name that refers to a value. It gives a value a useful label so you can reuse it, inspect it, and combine it with other values. In Data Science, variables often represent a dataset name, a model setting, a metric, a target column, or an intermediate result.
Why It Matters
Analytical work becomes difficult to trust when values have unclear names. A notebook with x, x2, and temp3 may run, but it is hard for another person, or your future self, to tell what each value means. Clear names make a business rule visible in the code.
Intuition
Think of a variable as a labeled container in a data workspace. The label should describe the role of the value. accuracy says more than a, and target_column says more than column_name_2.
Assignment and Naming Rules
Use = to assign a value to a name. Python reads the value on the right and associates it with the name on the left.
dataset_name = "customer_churn"
accuracy = 0.84
learning_rate = 0.05
customer_count = 1250
target_column = "churned"
Names can contain letters, digits, and underscores, but cannot start with a digit. Python is case-sensitive, so Accuracy and accuracy are different. Use lowercase snake_case for ordinary variables. Avoid spaces, hyphens, and built-ins such as list, dict, and sum.
Real-World / Data Science Example
An e-commerce team wants to flag high-value orders. The variables explain both the data and the rule.
order_amount = 620
high_value_threshold = 500
is_high_value = order_amount > high_value_threshold
print(is_high_value)
Expected output:
True
The names let a reader understand the decision without decoding the numbers.
Reassignment and Dynamic Typing
You can assign a new value to an existing variable. This is useful when a value genuinely changes during a calculation.
remaining_rows = 1000
remaining_rows = remaining_rows - 125
print(remaining_rows)
Expected output: 875.
Python is dynamically typed: you do not declare a type before assignment. A name can even point to a value of another type later.
score = 92
score = 92.5
score = "92.5"
print(type(score))
Expected output:
<class 'str'>
This flexibility is convenient, but accidental type changes are a common source of data errors. The final score is text, not a number you can safely average.
Explanation of the Code
The assignment operator stores a value under a name. Reassignment changes which value the name refers to. In the order example, the comparison creates a Boolean variable; in the score example, the same name ends as a string because its last assignment was text.
When to Use It
Use variables whenever a value has meaning beyond one expression: thresholds, file names, feature names, metric values, and cleaned outputs are all good candidates. A short loop index can be fine in a tiny local loop; an important business value deserves a descriptive name.
Failure Signals
Common Mistakes
- Using vague names in a long notebook.
- Reusing one name for unrelated meanings.
- Treating numeric strings such as
"120"as numbers. - Starting a name with a digit or using a hyphen.
- Shadowing built-ins with names such as
list,dict, orsum.
Best Practices
Keep a variable's meaning stable. Prefer cleaned_customer_count over silently changing what customer_count represents. For values intended to stay fixed by convention, use uppercase names such as DEFAULT_THRESHOLD = 0.70; Python does not enforce this, but the convention communicates intent.
Data Science Perspective
Variables become column names in Pandas, arrays in NumPy, hyperparameters in ML workflows, and outputs of cleaning steps. Clear names make feature engineering easier to review: days_since_last_purchase is much safer than feature_7. Type awareness also prepares you for Pandas dtypes.
Interview Perspective
Question: What does it mean that Python is dynamically typed? A strong answer: Python determines a variable's type at runtime from the object currently assigned to it. The same name can later reference another type, so data code needs type awareness.
Worked Example: Preserve Meaning During a Calculation
When a calculation has more than one step, use names that preserve the business meaning of each intermediate value.
monthly_revenue = 54000
active_customers = 1200
average_revenue_per_customer = monthly_revenue / active_customers
print(average_revenue_per_customer)
Expected output: 45.0. Avoid replacing monthly_revenue with the result of the division; later code may still need the original value. Separate names make it possible to inspect each step and spot an unexpected denominator.
Practice Questions
- Create variables for a customer's age, country, and lifetime value.
- Write a Boolean variable that becomes
Truewhen lifetime value is above 10,000. - Explain why
revenue = "5000"may cause a problem when calculating total revenue.
Quick Quiz
- Which name follows the usual Python convention:
customer-age,2nd_score, orcustomer_age? Answer:customer_age. - After
metric = 0.91and thenmetric = "0.91", what ismetric? Answer: a string. - Why is
target_columnbetter thanxin a shared notebook? Answer: it communicates the value's role.
Key Takeaway
Key Takeaways
Variables are simple, but naming and type awareness directly affect the readability and reliability of Data Science code.
Next Lesson
Next, learn how Python's data types affect calculations, comparisons, and values read from data sources.
Finish this lesson on your terms
Mark it complete when you have worked through the material and are ready to move on.