Python: lesson 2 of 7

Python

PATH 01MODULE 02LESSON 02 OF 07Next: Operators and Expressions

Data Types and Type Conversion

Understand Python's core value types and why converting data safely matters for analysis.

Beginner13 min readpythondata-typestype-conversiondata-quality

Concept

Every Python value has a type. The type tells Python what operations make sense: numbers can be added, text can be joined, and Boolean values represent a yes-or-no condition. The core types you will meet constantly are int, float, str, bool, and None.

Why It Matters

Real data is often messy before analysis begins. An age may arrive as the text "25", a revenue value may have a currency symbol, and a missing field may be represented by an empty value. If the type is wrong, calculations can fail or, worse, give a misleading result.

Intuition

Types are like instructions attached to a value. 25 tells Python it is a whole number; "25" tells Python it is two text characters. They look similar to a person, but Python must treat them differently.

Core Python Types

customer_age = 25           # int: whole number
average_order_value = 84.50 # float: decimal number
customer_city = "Pune"      # str: text
is_active = True            # bool: True or False
discount_code = None        # no value available yet

print(type(customer_age))
print(type(average_order_value))
print(type(customer_city))

Expected output:

<class 'int'>
<class 'float'>
<class 'str'>

None is useful when a value is absent or not known yet. It is different from 0, False, and an empty string: each of those is still a value with its own meaning.

Real-World / Data Science Example

Imagine age is read from a CSV export as text.

age = "25"
age_number = int(age)
next_year_age = age_number + 1

print(next_year_age)

Expected output:

26

The conversion makes the intended analysis explicit. It also gives you a place to handle invalid values rather than quietly treating text as a number.

Technical Explanation

Use type() to inspect a value when you are unsure what Python received. Use conversion functions deliberately:

order_count = int("12")
conversion_rate = float("0.084")
report_label = str(2025)
has_purchased = bool(3)

print(order_count, conversion_rate, report_label, has_purchased)

Expected output:

12 0.084 2025 True

bool() follows Python's truthiness rules. Non-empty strings and non-zero numbers are generally True; 0, "", and None are False. That is useful in conditions, but do not use bool("False") to parse a text flag: it returns True because the string is non-empty.

Explanation of the Code

int() converts compatible text to a whole number. float() supports decimals. str() is useful when building labels or messages. Each conversion can fail when the input is not compatible, such as int("unknown"), so inspect and clean data rather than assuming every record is valid.

When to Use It

Check types when reading files, receiving user input, combining data sources, or calculating features. Later, Pandas provides its own dtype system for whole columns, including numeric, string, datetime, and nullable types. The principle stays the same: a value's representation must match the operation you want to perform.

Failure Signals

Common Mistakes

  1. Assuming values that look numeric are numbers.
  2. Using bool("False") to parse a string flag.
  3. Converting missing or invalid text without deciding how to handle errors.
  4. Treating None as identical to zero.

Best Practices

Inspect a small sample before converting an entire field. Keep the original value when debugging a conversion problem, and choose a name that signals the cleaned type, such as age_number or revenue_float. Validate expected ranges after conversion: an age of 250 is numeric but still suspicious.

Data Science Perspective

Type conversion is a data-cleaning task. In Pandas you will convert entire columns and inspect dtypes, while NumPy arrays normally hold values of a consistent type. ML models expect numeric inputs, so text, dates, categories, and missing values must eventually be represented deliberately.

Interview Perspective

Question: Why can "25" + "1" work while "25" + 1 fails? A strong answer: the first joins two strings; the second mixes text and an integer, so Python needs an explicit conversion.

Worked Example: Inspect Before Converting

Suppose a survey export uses several representations for an age field. A direct conversion is safe only after you decide which values are usable.

raw_age = " 25 "
cleaned_age = raw_age.strip()

if cleaned_age.isdigit():
    age = int(cleaned_age)
else:
    age = None

print(age)

Expected output: 25. This small example is not a complete production parser, but it shows the right habit: inspect and clean text before treating it as a measurement.

Practice Questions

  1. What type is 0.0, and why would it be useful for a model score?
  2. Convert "1250" into an integer and add 50.
  3. A customer export stores is_active as the text "False". Why is bool(is_active) not a reliable parser?

Quick Quiz

  1. What does type(None) represent? Answer: NoneType.
  2. Which conversion is appropriate for "3.14"? Answer: float().
  3. Is 0 truthy or falsy? Answer: falsy.

Key Takeaway

Key Takeaways

Types determine what Python can do with a value. Inspect types, convert deliberately, and treat invalid values as a data-quality decision rather than an inconvenience.

Next Lesson

Next, use operators and expressions to calculate metrics, compare values, and combine conditions.

Finish this lesson on your terms

Mark it complete when you have worked through the material and are ready to move on.