Fast Track Python Mastery
Python Syntax Essentials
The Rules of the Road
Every language has its grammar and etiquette. In Python, the community-written style guide is called . Its main goal is simple: make code readable. Since you spend more time reading code than writing it, this is a big deal.
The most important rule in Python isn't about style, it's about syntax: indentation matters. Unlike languages that use curly braces {} to define blocks of code, Python uses whitespace. A consistent indent (the standard is four spaces) tells the interpreter which lines of code belong together inside a function, loop, or conditional statement.
Consistent indentation is not optional. Incorrect indentation will cause your code to fail with an
IndentationError.
# This is correct Python syntax
name = "Alice"
if name == "Alice":
print("Hello, Alice!") # This line is indented
# This will raise an IndentationError
if name == "Alice":
print("This will break!") # This line is NOT indented
Data and Descriptions
Python uses dynamic typing, which means you don't have to declare a variable's type. The interpreter figures it out at runtime. You can assign an integer to a variable and then reassign a string to that same variable without any issue.
While this offers flexibility, modern Python encourages using type hints. These are optional annotations that specify the expected type of a variable or a function's return value. They don't change how the code runs, but they drastically improve readability and allow tools to catch potential errors before you even run the program.
# Dynamic typing in action
my_variable = 101 # It's an integer
my_variable = "Hello" # Now it's a string
# Using type hints for clarity
def greet(name: str) -> str:
return "Hello, " + name
age: int = 30
When it comes to working with strings, Python provides a powerful and clean way to embed expressions inside string literals: . They are prefixed with an f and use curly braces {} to evaluate expressions in place.
name = "Bob"
age = 42
# Old way using str.format()
old_greeting = "Hello, my name is {} and I am {} years old.".format(name, age)
# New, cleaner way using an f-string
new_greeting = f"Hello, my name is {name} and I am {age} years old."
print(new_greeting)
# Output: Hello, my name is Bob and I am 42 years old.
Making Decisions
Conditional logic in Python is straightforward, using if, elif (short for else if), and else. The conditions in these statements rely on boolean logic, but Python has a broader concept called .
Essentially, many things besides True and False can be evaluated in a boolean context. For example, any non-empty string, non-zero number, or non-empty collection (like a list or dictionary) is considered "truthy." Empty strings, the number 0, and empty collections are considered "falsy."
my_list = [1, 2, 3]
if my_list: # This is considered True because the list is not empty
print("The list has items.")
user_name = ""
if not user_name: # This is considered True because an empty string is falsy
print("Username is missing.")
For more complex conditional logic that involves matching a value against several possible patterns, Python 3.10 introduced the match-case statement. It's similar to a switch statement in other languages but offers more advanced pattern matching capabilities.
status_code = 404
match status_code:
case 200:
print("OK")
case 404:
print("Not Found")
case 500:
print("Internal Server Error")
case _:
print("Unknown status") # The underscore is a wildcard
Time to check your understanding of these core syntax rules.
What is the primary goal of PEP 8, the official Python style guide?
How does Python define the scope of a code block, such as the body of a function or a loop?
With these rules in hand, you have the foundation to write clean, readable, and functional Python code.