Python Fundamentals to Application
Python Syntax and Data Types
Python's Clean Slate: Syntax and Types
Unlike many programming languages that rely on brackets or keywords to define the structure of code, Python uses a much simpler approach: indentation. This design choice isn't just about aesthetics; it forces a clean, readable style that makes Python code remarkably easy to follow. The core idea is that code that looks good should also work well.
Statements in Python are typically written on a single line. If a statement is too long, you can use a backslash (\) to continue it on the next line, although Python is often smart enough to handle line breaks within parentheses, brackets, and braces without it.
# This is a comment
# A simple variable assignment
user_name = "Alex"
# Python knows this is one statement because it's inside parentheses
total_value = (100 + 200 +
300 + 400)
# Using a backslash for a long string
long_string = "This is a very long string that spans multiple \
lines for readability purposes."
The Power of Whitespace
Indentation is Python's way of grouping statements. Where languages like Java or C++ use curly braces {} to create code blocks, Python uses a consistent number of spaces. This is one of the most significant syntactic rules in the language.
Any block of code, such as the body of a loop or a conditional statement, must be indented. The standard convention is to use four spaces for each level of indentation. Failing to indent, or indenting incorrectly, will result in an IndentationError.
This strict indentation rule ensures that all Python code has a similar structure, making it easier for any developer to read and understand code written by others.
Types on the Fly
Python is dynamically typed. This means you don't have to declare the data type of a variable when you create it. The Python interpreter figures out the type at runtime based on the value you assign.
A variable in Python is essentially a name that points to a value. The type is associated with the value itself, not the variable name. This allows a single variable name to refer to different data types throughout a program's execution, though this is a practice to be used with care.
# No type declaration needed
data = 42 # data is an integer
print(type(data))
data = "hello" # Now, data is a string
print(type(data))
data = [1, 2, 3] # And now it's a list
print(type(data))
Core Data Types
Python has several built-in data types that form the building blocks of almost any program. These types can be broadly categorised into numeric types, sequences, sets, and mappings.
Everything in Python is an object, and every object has a type. You can always check an object's type using the built-in
type()function.
Numeric Types: int and float
Integers (int) are whole numbers, and their size is only limited by your computer's memory. Floating-point numbers (float) represent real numbers with a decimal point.
my_integer = 1_000_000 # Underscores can be used for readability
my_float = 3.14159
Sequences: str, list, and tuple
Sequences are ordered collections of items. The main difference between them lies in their mutability, meaning whether they can be changed after creation.
- Strings (
str): An immutable sequence of characters. You can create them with single, double, or triple quotes. Triple quotes are useful for multi-line strings. - Lists (
list): A mutable, or changeable, ordered sequence of items. Lists are created with square brackets[]. - Tuples (
tuple): An immutable, or unchangeable, ordered sequence. Tuples are created with parentheses()and are generally faster than lists. They are useful for data that shouldn't change, like coordinates or configuration settings.
# String (immutable)
language = "Python"
# List (mutable)
fibonacci_sequence = [1, 1, 2, 3, 5, 8]
# Tuple (immutable)
rgb_color = (255, 165, 0)
Sets: set
A set is an unordered collection of unique items. They are mutable but do not allow duplicate elements. Sets are highly optimised for membership testing (checking if an element is present) and for mathematical set operations like union, intersection, and difference. They are created with curly braces {} or the set() function.
# A list with duplicates
numbers = [1, 2, 2, 3, 4, 4, 4]
# Creating a set removes duplicates
unique_numbers = set(numbers) # Result: {1, 2, 3, 4}
Mappings: dict
A dictionary (dict) is a mutable, unordered collection of key-value pairs (though as of Python 3.7, they maintain insertion order). Each key must be unique and is used to access its corresponding value. Dictionaries are incredibly useful for storing structured data and are created with curly braces {} containing key-value pairs.
user_profile = {
"username": "jdoe",
"user_id": 101,
"is_active": True
}
# Accessing a value by its key
print(user_profile["username"]) # Outputs: jdoe
| Data Type | Description | Syntax Example | Mutable? |
|---|---|---|---|
int | Integer numbers | x = 10 | N/A |
float | Floating-point numbers | y = 2.5 | N/A |
str | Sequence of characters | s = "hello" | No |
list | Ordered sequence of items | l = [1, "a", 3.0] | Yes |
tuple | Ordered, immutable sequence | t = (1, "a", 3.0) | No |
set | Unordered, unique items | s = {1, 2, 3} | Yes |
dict | Key-value pairs | d = {"key": "value"} | Yes |
Understanding these fundamental types and Python's straightforward syntax is the first step to writing clean and effective code.
Ready to check your understanding?
What does Python use to define blocks of code, such as the body of a loop or function?
Consider the following code snippet:
x = 10
x = "Hello, World!"
What concept does this demonstrate about Python's variables?
With these basics in hand, you are now equipped to start building more complex logic and structures in Python.