Types and Conversions¶
Every value in Python has a type. The type determines what you can do with it.
Learn Your Way¶
| Read | Build | Watch | Test | Review | Visualize |
|---|---|---|---|---|---|
| You are here | Projects | Videos | Quiz | Flashcards | Diagrams |
Visualize It¶
See how type conversions change values and what happens when they fail: Open in Python Tutor
Basic types¶
| Type | What it holds | Examples |
|---|---|---|
str |
Text (string) | "hello", 'world', "123" |
int |
Whole number | 42, -3, 0 |
float |
Decimal number | 3.14, -0.5, 2.0 |
bool |
True or False | True, False |
None |
Nothing / empty | None |
Checking a type¶
print(type("hello")) # <class 'str'>
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type(True)) # <class 'bool'>
Converting between types¶
| Function | Converts to | Example |
|---|---|---|
str() |
String | str(42) → "42" |
int() |
Integer | int("42") → 42 |
float() |
Float | float("3.14") → 3.14 |
bool() |
Boolean | bool(0) → False |
Why conversion matters¶
input() always returns a string. If you want to do math with it, you must convert:
age_text = input("Age? ") # User types 30 → age_text is "30" (string)
age = int(age_text) # Convert to integer
print(age + 1) # 31 (math works now)
Without conversion:
Truthy and falsy values¶
Python treats some values as True and others as False in conditions:
Falsy (treated as False):
- False, 0, 0.0, "" (empty string), [] (empty list), {} (empty dict), None
Truthy (treated as True):
- Everything else: True, any non-zero number, any non-empty string/list/dict
Common mistakes¶
Comparing different types:
Converting non-numeric strings:
int("hello") # ValueError: invalid literal
int("3.14") # ValueError: cannot convert float string to int directly
float("3.14") # 3.14 — use float() for decimal strings
Practice¶
- Level 00 / 05 Numbers and Math
- Level 00 / 07 User Input
- Level 0 / 02 Calculator Basics
- Level 0 / 03 Temperature Converter
- Level 0 / 04 Yes No Questionnaire
- Level 0 / 08 String Cleaner Starter
- Level 1 / 01 Input Validator Lab
- Level 1 / 02 Password Strength Checker
Quick check: Take the quiz
Review: Flashcard decks Practice reps: Coding challenges
| ← Prev | Home | Next → |
|---|---|---|