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.
- `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 age
age = 25
# Float (float) to store price with decimals
price = 14.99
# Complex number (complex) - not as common in everyday use
complex_num = 3 + 2j # Imaginary unit represented by j
- `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 name
name = "Alice"
# String with a sentence
greeting = "Hello, how are you?"
# Multi-line string using triple quotes
message = """This is a message
that spans multiple lines."""
- `bool`: Represents logical values: `True` or `False`. Used for conditional statements and boolean expressions.
# Boolean (bool) for a true/false condition
is_raining = True
# Using booleans in an if statement
if is_raining:
print("Bring an umbrella!")
Write a Python program that:
type()
function to check the data type of each number.Example Output:
The type of variable x is: <class 'int'>
The type of variable y is: <class 'float'>
The type of variable z is: <class 'complex'>