Chapter 3: Python Syntax
Learn the basic rules of writing Python code, including indentation and statements.
Understanding Python Syntax
Python’s syntax is the set of rules that defines how Python code is written and interpreted. Known for its simplicity and readability, Python uses indentation to structure code, unlike many languages that use braces (e.g., C++ or Java). This chapter introduces the basics of Python syntax, including statements, indentation, and code structure, to help you write your first Python programs.
Basic Python Statements
A Python statement is a single line of code that performs an action. For example, the print()
function outputs text to the console:
print("Hello, World!")This statement displays “Hello, World!” when executed. Statements can be simple (like above) or complex (e.g., loops or conditionals, covered in later chapters).
Indentation in Python
Indentation is a core feature of Python’s syntax. It defines the scope and hierarchy of code blocks, such as loops, functions, or conditionals. Unlike other languages that use curly braces, Python uses spaces or tabs (typically four spaces) to indent code. For example:
if True: print("This is indented") print("This is not indented")The indented
print
statement is part of the if
block, while the unindented one is outside it. Incorrect indentation causes errors, so consistency is key.
Line Continuation
Python statements typically end at a newline. For long statements, you can use a backslash (\
) to continue onto the next line:
total = 1 + 2 + 3 + \ 4 + 5 print(total)This outputs
15
. Alternatively, parentheses can wrap long expressions without a backslash:
total = (1 + 2 + 3 + 4 + 5) print(total)
Multiple Statements on a Single Line
You can write multiple statements on one line using a semicolon (;
), though this is rare due to Python’s emphasis on readability:
x = 10; y = 20; print(x + y)This outputs
30
. However, it’s better to write each statement on a new line for clarity.
Blank Lines and Whitespace
Blank lines are ignored by Python and can improve readability. Whitespace within a line (e.g., spaces around operators) is optional but recommended:
x = 10 + 5 # Good x=10+5 # Less readablePython’s style guide, PEP 8, recommends spaces around operators and after commas for consistency.
Next Steps
Now that you understand Python’s syntax, proceed to Chapter 4: Python Comments to learn how to add notes to your code. Use the sticky sidebar to navigate the 50-chapter learning path. For support, contact us at Contact or email info@bloggytech.com. Bloggy Tech, based in Wah Cantt, Pakistan, is here to guide you through your Python journey.