Master Python data types with this comprehensive guide. Learn about numeric, string, boolean, and collection data types with examples, exercises, and tasks. Perfect for beginners and professionals to enhance their Python programming skills.
In Python, data types define the kind of value a variable can hold and the operations that can be performed on it. They act as blueprints, specifying how data is stored and manipulated in your programs.
1. Numeric Types (int, float, complex)
- `int`: Stores whole (non-decimal) numbers, like `10`, `-5`, or `9999`.
- `float`: Represents floating-point numbers with decimals, like `3.14`, `-2.5e2` (scientific notation), or `1.2345678901234567` (limited precision).
- `complex`: Holds complex numbers with a real and imaginary part, like `3+2j` or `1.5-4.7j`.
# Integer (int) to store ageage = 25# Float (float) to store price with decimalsprice = 14.99# Complex number (complex) - not as common in everyday usecomplex_num = 3 + 2j # Imaginary unit represented by j
2. Text Type (str)
- `str`: Represents textual data enclosed in single or double quotes, such as `"Hello, world!"`, `'This is a string'`, or multi-line strings using triple quotes (''' or """).
# String (str) to store a namename = "Alice"# String with a sentencegreeting = "Hello, how are you?"# Multi-line string using triple quotesmessage = """This is a messagethat spans multiple lines."""
3. Boolean Type (bool)
- `bool`: Represents logical values: `True` or `False`. Used for conditional statements and boolean expressions.
# Boolean (bool) for a true/false conditionis_raining = True# Using booleans in an if statementif is_raining: print("Bring an umbrella!")