Basic Syntax and Data Types in Python
Python provides a variety of built-in data types, each with distinct behaviors and use cases. Let's dive into each of these data types with details, use cases, and examples.
Subtopic 1: Python Syntax and Structure (Recap)
Python’s structure is designed for readability and simplicity, mainly relying on:
- Indentation to define code blocks.
- Comments using
#for single lines and""" ... """for multi-line.
Example:
# Define a function
def greet(name):
# Print a greeting
print(f"Hello, {name}!")
greet("Vijay")
Subtopic 2: Variables and Assignment (Recap)
Python variables can hold any data type and do not require explicit type declaration. Example:
count = 10 # Integer
price = 12.99 # Float
name = "Python" # String
is_active = True # Boolean
Subtopic 3: Data Types in Python
-
Numeric Data Types
Python provides three primary types for numbers:
- Integer (
int): Whole numbers, positive or negative.- Example:
x = 10 y = -5
- Example:
- Floating-point (
float): Numbers with decimal points.- Example:
pi = 3.14159 temperature = -4.5
- Example:
- Complex (
complex): Numbers with a real and imaginary part, written asa + bj.- Example:
z = 3 + 4j
- Example:
Use Cases:
- int: Counting items, indexing, calculations that don't need precision.
- float: Measurements, calculations with precision, financial data.
- complex: Scientific computations, signal processing, and other advanced math operations.
- Integer (
-
String (
str)Text data, created with single, double, or triple quotes.
- Example:
greeting = "Hello, World!" multiline = """This is a multi-line string""" - Common String Methods:
upper(),lower(): Case manipulationfind(),replace(): Searching and replacing substringsstrip(),split(): Trimming and splitting strings
Use Cases:
- Displaying messages, handling text input/output, storing names, descriptions.
- Example:
-
Boolean (
bool)Represents
TrueorFalse, often used in conditions and comparisons.- Example:
is_valid = True is_empty = False
Use Cases:
- Conditional checks, loops, logical expressions in control flow.
- Example:
-
Sequence Types
These data types store a sequence of values and allow indexing and slicing:
- List (
list): Mutable ordered collection, which can contain mixed data types.- Example:
fruits = ["apple", "banana", "cherry"] fruits[0] = "mango" # Lists are mutable
- Example:
- Tuple (
tuple): Immutable ordered collection.- Example:
coordinates = (4, 5) # coordinates[0] = 7 # Error: Tuples are immutable
- Example:
- Range (
range): Immutable sequence of numbers, often used in loops.- Example:
for i in range(5): print(i) # 0, 1, 2, 3, 4
- Example:
Use Cases:
- list: Storing and modifying collections of items, such as a dynamic list of numbers.
- tuple: Fixed set of values, often used to store records or coordinates.
- range: Generating a sequence of numbers, mainly in looping constructs.
- List (
-
Mapping Type
-
Dictionary (
dict): Stores key-value pairs, allowing efficient data retrieval by key. -
Example:
user = {"name": "Vijay", "age": 25, "active": True} print(user["name"]) # Output: Vijay
Use Cases:
- Database-like storage of information, structured data that can be accessed by unique identifiers.
-
-
Set Types
Unordered collections of unique elements, suitable for membership testing and removing duplicates.
- Set (
set): Mutable collection with unique elements.- Example:
fruits = {"apple", "banana", "cherry"} fruits.add("orange")
- Example:
- Frozen Set (
frozenset): Immutable version of a set.- Example:
frozen_fruits = frozenset(["apple", "banana"])
- Example:
Use Cases:
- set: Removing duplicates, membership checks, set operations like union and intersection.
- frozenset: Immutable set operations, particularly when working with constant sets.
- Set (
-
Binary Types
For handling binary data, such as files and network data.
- Bytes (
bytes): Immutable sequence of bytes.- Example:
data = b"Hello"
- Example:
- Bytearray (
bytearray): Mutable sequence of bytes.- Example:
data = bytearray(b"Hello") data[0] = 72 # Changing byte value
- Example:
- Memoryview (
memoryview): Provides a view of byte data without copying it.- Example:
view = memoryview(data)
- Example:
Use Cases:
- bytes: Immutable binary data, used in network communications, binary file storage.
- bytearray: Mutable binary data, modifying parts of binary files.
- memoryview: Accessing slices of binary data for optimized memory usage.
- Bytes (
Subtopic 4: Type Conversion and Casting (Recap)
Python allows easy conversion between types using functions like int(), float(), str(), bool(), etc.
Examples of Type Conversion:
age_str = "25"
age_int = int(age_str) # Converts to integer
height = 5.9
height_str = str(height) # Converts to string