If you’re dipping your toes into the world of programming, Python is a fantastic language to start with. It’s designed to be readable, approachable, and incredibly versatile. One of the key aspects of Python that sets it apart from other languages is its emphasis on clean, readable syntax. In this tutorial, we’ll walk through some of the foundational aspects of Python syntax to help you hit the ground running.
Let’s start with one of Python’s most unique and defining features: whitespace and indentation. If you’ve worked with languages like Java, C++, or C#, you may be used to semicolons (;
) separating statements or braces ({}
) wrapping blocks of code. Python, however, has no time for extra clutter. Instead, it enforces indentation as part of its syntax. This isn’t just for style—it’s how Python organizes code blocks and defines their structure.
Here’s a quick example:
import math
# Function to calculate the area of a circle
def calculate_circle_area(radius):
# Check if the radius is valid
if radius < 0:
return "Radius cannot be negative."
# Calculate area
area = math.pi * radius ** 2
return area
# Example usage
radius = 5 # You can change the radius value
area = calculate_circle_area(radius)
print(f"The area of the circle with radius {radius} is {area:.2f}")
In this snippet:
Why is this great? Readability. Python’s indentation makes the structure of your code immediately apparent, even at a glance. You always know where a block begins and ends, and Python’s simplicity helps keep things concise and clean. If you’ve ever wrestled with mismatched braces or tangled code blocks in other languages, you’ll appreciate this more than you think.
There will be no more debates over formatting. Python enforces consistent style, so there will be no more
If you’re like most programmers, you’ve written a piece of code only to come back months later, scratch your head, and wonder, what on earth was I thinking? That’s where comments come in. Good commenting habits help you explain what your code does and why confident choices were made. They can be a lifesaver when you revisit your code later or when someone else does.
In Python, writing a comment is easy:
# This is a comment explaining the code below
Anything after the #
the Python interpreter ignores symbol on that line. So, sprinkle them liberally, but don’t overdo it—your code should still be readable without a running commentary on every line.
And if you need to write a longer explanation, Python also supports multi-line docstrings:
"""
This is a longer explanation
that spans multiple lines.
"""
Technically, docstrings are strings, not comments, but they serve a similar purpose—often used at the beginning of functions or classes to explain their purpose.
You’ll often write lines of code that just won’t fit on one line, whether due to long conditions or complex expressions. No problem! Python allows you to break up long lines of code with a backslash (\
), telling the interpreter that the statement continues on the next line.
Example:
# Calculating the sum of several numbers split across multiple lines
sum_of_numbers = 1 + 2 + 3 + 4 + \
5 + 6 + 7 + 8 + \
9 + 10
print("Sum of numbers:", sum_of_numbers)
This allows you to keep your code readable and your lines from running off the page.
Identifiers are the names you give to variables, functions, classes, and other objects. You’ll be using them a lot. Here are some basic rules for creating valid Python identifiers:
_
).myVariable
and MyVariable
are two different identifiers.def
or class
because those words already have a special purpose.Keywords are reserved words in Python that hold special meanings. These include words like if
, else
, while
, and for
, among others. They form the backbone of Python’s control flow and structure. Here’s a short list of some common Python keywords:
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
If you’re ever unsure whether a word is a Python keyword, you can check using the keyword
module:
print(keyword.kwlist)
Text in Python is handled through string literals, and Python is incredibly flexible in how you can define them. You can use:
'This is a string'
"This is also a string"
'''This string can span multiple lines'''
Here’s a quick example:
single_quote_string = 'Hello, World!'
double_quote_string = "Hello, World!"
multi_line_string = '''This is a string
that spans multiple lines.'''
Each type of quote is interchangeable, and Python treats them the same way (make sure you close them with the same quote you opened them with!).
Let’s quickly recap what we’ve covered:
#
for single-line comments and triple quotes ("""
) for multi-line docstrings.\
) to break lengthy statements into multiple lines.By understanding these basics, you’re well on becoming proficient in Python. The beauty of Python lies in its simplicity and readability, which is why it’s such a favourite among developers—whether they’re just starting or have been coding for years. Keep exploring, and you’ll find that Python’s syntax is easy to learn and a joy to work with!