Python is widely supported because its grammar is simple and easy to read. This “readability” is enforced by strict rules regarding indentation. While many other programming languages use curly braces {} to define a “block” of code, Python uses the depth of indentation to express it.
This article explains the basic elements of a Python program: indentation, control flow (if statements and for loops), function definitions (def), and the standard syntax for executing scripts.
Importance of Indentation
In Python, indentation is not just for styling; it is part of the grammar. Blocks starting with if, for, or def are indicated by indenting the following lines. If the indentation depth is not consistent, an IndentationError will occur, and the program will not run.
# Good Example: Consistent indentation
user_level = 10
if user_level > 5:
print("Access granted.")
print("Welcome.")
# Bad Example: IndentationError
# if user_level > 5:
# print("Access granted.") # No indentation
You can use tabs or spaces, but the official style guide (PEP 8) strongly recommends using 4 spaces.
Control Flow
These are structures used to control the flow of the program. They also define processing blocks using indentation.
Conditional Branching (if statement)
Use if, elif (else if), and else to branch processing based on conditions.
def check_temperature(temp_celsius):
"""
Receives temperature in Celsius and judges the status.
"""
if temp_celsius >= 30:
print(f"{temp_celsius} degrees: It's hot.")
elif temp_celsius <= 5:
print(f"{temp_celsius} degrees: It's cold.")
else:
print(f"{temp_celsius} degrees: It's comfortable.")
# Execution Examples
check_temperature(32.5)
check_temperature(18.0)
Repetition (for loop)
This repeats processing by taking elements one by one from a list or tuple (iterable objects).
# List of file names
file_list = ["report_2023.pdf", "image.png", "document.txt", "archive.zip"]
print("Searching for text files only:")
for filename in file_list:
# Check if it ends with .txt
if filename.endswith(".txt"):
print(f" - Found: {filename}")
Function Definition (def)
A “function” groups a series of processes, names them, and makes them reusable. It is defined using the def keyword. The body of the function is also indicated by indentation.
def calculate_stats(numbers):
"""
Receives a list of numbers and returns the sum and average.
"""
total = sum(numbers)
count = len(numbers)
if count == 0:
return (0, 0.0) # Return sum and average as a tuple
average = total / count
return (total, average)
# Calling the function
data_points = [15, 20, 25, 30, 35]
total_sum, avg_value = calculate_stats(data_points)
print(f"Data: {data_points}")
print(f"Sum: {total_sum}, Average: {avg_value}")
Standard Script Execution Form
To perform specific processing when a Python file is executed directly, the following syntax is used. This is a very common method.
def main_process():
"""
Main processing of this script
"""
print("Starting main process.")
results = calculate_stats([10, 20, 30])
print(f"Calculation Result: {results}")
# The following block runs only if this .py file is executed directly
if __name__ == "__main__":
main_process()
The special variable __name__ becomes the string "__main__" when the file is executed directly. If this file is imported by another Python file as a module, __name__ becomes the filename (e.g., basic_code_structure), so main_process() inside the if block will not run. This makes it easier to reuse the code as a module.
Other Syntax
pass Statement
pass means “do nothing.” It is used when a block is syntactically required, but you do not want to perform any processing (or plan to write it later).
# Example: Do nothing under certain conditions
for filename in file_list:
if filename.endswith(".png") or filename.endswith(".zip"):
# Skip processing for images and zip files
pass
else:
print(f"Processing target: {filename}")
Line Continuation (Backslash \ and Parentheses)
If the code does not fit on one line, placing a backslash \ at the end of the line tells Python the code continues on the next line.
# Line continuation using backslash
total_score = 10 + 20 + 30 + 40 + 50 \
+ 60 + 70 + 80 + 90 + 100
However, inside () (parentheses), [] (brackets), and {} (braces), lines are automatically continued without a backslash. Using parentheses is recommended.
# Newline inside parentheses (Recommended method)
allowed_users = [
"user_alpha",
"user_beta",
"user_gamma",
"admin_delta",
]
Summary
Python code structure is strictly managed by indentation. if statements, for loops, and def function definitions all have indented code blocks. Also, the if __name__ == "__main__": syntax is the standard way to check if a script was executed directly. Understanding these basic structures is the first step to writing readable and maintainable Python code.
